<?php
namespace common\helper;

use Yii;
use yii\web\View;

class Helper  {
    
    public static function potong($string,$cut)
    {
      $string = substr($string, 0, $cut); 
      $string = $string . "..."; 
      return $string; 
    }
    private static function generateReference()
    {
      $micro_date = microtime();
      $date_array = explode(" ",$micro_date);
      $date = date("YmdHis",$date_array[1]);
      $date_array[0] = preg_replace('/[^\p{L}\p{N}\s]/u', '', $date_array[0]);
      return "Ref".$date.$date_array[0].rand(100,999);
    }

    public static function nicepayprocess($id, $carabayar, $total, $nama, $telp, $email, $alamat, $city, $state, $postal){
      $nicepay = new NicepayLib();

        if(isset($carabayar) && $carabayar)
        {
          if($carabayar != 'CC'){
              $bankCd         = $carabayar;
              $dateNow        = date('Ymd');
              $vaExpiryDate   = date('Ymd', strtotime($dateNow . ' +1 day')); // Set VA expiry date +1 day (optional)

              // Populate Mandatory parameters to send
              $nicepay->set('payMethod', '02');
              $nicepay->set('currency', 'IDR');
              $nicepay->set('amt', $total); // Total gross amount
              $nicepay->set('referenceNo', Helper::generateReference()); // Invoice Number or Referenc Number Generated by merchant
              $nicepay->set('description', 'Payment of Invoice No '.$nicepay->get('referenceNo')); // Transaction description
              $nicepay->set('bankCd', $bankCd);

              $nicepay->set('billingNm', $nama); // Customer name
              $nicepay->set('billingPhone', $telp); // Customer phone number
              $nicepay->set('billingEmail', $email); //
              $nicepay->set('billingAddr', $alamat);
              $nicepay->set('billingCity', $city);
              $nicepay->set('billingState', $state);
              $nicepay->set('billingPostCd', $postal);
              $nicepay->set('billingCountry', 'Indonesia');

              $nicepay->set('deliveryNm', $nama); // Delivery name
              $nicepay->set('deliveryPhone', $telp);
              $nicepay->set('deliveryEmail', $email);
              $nicepay->set('deliveryAddr', $alamat);
              $nicepay->set('deliveryCity', $city);
              $nicepay->set('deliveryState', $state);
              $nicepay->set('deliveryPostCd', $postal);
              $nicepay->set('deliveryCountry', 'Indonesia');

              $nicepay->set('vacctValidDt', $vaExpiryDate); // Set VA expiry date example: +1 day
              $nicepay->set('vacctValidTm', date('His')); // Set VA Expiry Time

              $response = $nicepay->requestVA();

              if (isset($response->resultCd) && $response->resultCd == "0000") {
                $kembali = "<pre>";
                $kembali .= "tXid              : $response->tXid (Save to your database to check status) \n";
                $kembali .= "callbackUrl       : $response->callbackUrl\n";
                $kembali .= "description       : $response->description\n";
                $kembali .= "payment date      : $response->transDt\n"; // YYMMDD
                $kembali .= "payment time      : $response->transTm\n"; // HH24MISS
                $kembali .= "virtual account   : $response->bankVacctNo (For customer to transfer) \n";
                $kembali .= "result code       : $response->resultCd\n";
                $kembali .= "result message    : $response->resultMsg\n";
                $kembali .= "reference no      : $response->referenceNo\n";
                $kembali .= "payment method    : $response->payMethod";
                $kembali .= "</pre>";

              // $data = array('vTxid'=> $response->tXid);
              // $this->db->where('id', $id);
              // $this->db->update('order', $data); 

              } elseif(isset($response->resultCd)) {

                  // API data not correct, you can redirect back to checkout page or echo error message.
                  // In this sample, we echo error message
                  $kembali = "<pre>";
                  $kembali .= "result code       :".$response->resultCd."\n";
                  $kembali .= "result message    :".$response->resultMsg."\n";
                  $kembali .= "</pre>";
              } else {
                  // Timeout, you can redirect back to checkout page or echo error message.
                  // In this sample, we echo error message
                  $kembali = "<pre>Connection Timeout. Please Try again.</pre>";
              }

          }
    /*
     * ____________________________________________________________
     *
     * Credit Card Payment Method
     * ____________________________________________________________
     */
        else
          {

              // Populate Mandatory parameters to send
              $nicepay->set('payMethod', '01');
              $nicepay->set('currency', 'IDR');
              $nicepay->set('amt', $total); // Total gross amount
              $nicepay->set('referenceNo', helper::generateReference()); // Invoice Number or Referenc Number Generated by merchant
              $nicepay->set('description', 'Payment of Invoice No '.$nicepay->get('referenceNo')); // Transaction description

              $nicepay->set('billingNm', $nama); // Customer name
              $nicepay->set('billingPhone', $telp); // Customer phone number
              $nicepay->set('billingEmail', $email); //
              $nicepay->set('billingAddr', $alamat);
              $nicepay->set('billingCity', $city);
              $nicepay->set('billingState', $state);
              $nicepay->set('billingPostCd', $postal);
              $nicepay->set('billingCountry', 'Indonesia');

              $nicepay->set('deliveryNm', $nama); // Delivery name
              $nicepay->set('deliveryPhone', $telp);
              $nicepay->set('deliveryEmail', $email);
              $nicepay->set('deliveryAddr', $alamat);
              $nicepay->set('deliveryCity', $city);
              $nicepay->set('deliveryState', $state);
              $nicepay->set('deliveryPostCd', $postal);
              $nicepay->set('deliveryCountry', 'Indonesia');

              // Send Data
              $response = $nicepay->chargeCard();


              // Response from NICEPAY
      //        var_dump($response);
      //        exit();
              if (isset($response->data->resultCd) && $response->data->resultCd == "0000") {
                  // $data = array('vTxid'=> $response->tXid);
                  // $this->db->where('id', $id);
                  // $this->db->update('order', $data); 

                    // header("Location: ".$response->data->requestURL."?tXid=".$response->tXid);
             $kembali = $response->data->requestURL."?tXid=".$response->tXid;
      //            please save tXid in your database
      //            echo "<pre>";
      //            echo "tXid              : $response->tXid\n";
      //            echo "API Type          : $response->apiType\n";
      //            echo "Request Date      : $response->requestDate\n";
      //            echo "Response Date     : $response->requestDate\n";
      //            echo "</pre>";
              } elseif(isset($response->data->resultCd)) {
                  // API data not correct or error happened in bank system, you can redirect back to checkout page or echo error message.
                  // In this sample, we echo error message
                  // header("Location: "."http://example.com/checkout.php");
                    $kembali = "<pre>";
                    $kembali .= "result code       : ".$response->data->resultCd."\n";
                    $kembali .= "result message    : ".$response->data->resultMsg."\n";
                    $kembali .= "</pre>";
      //             echo "<pre>";
      //             echo "result code       : ".$response->data->resultCd."\n";
      //             echo "result message    : ".$response->data->resultMsg."\n";
      // //            echo "requestUrl        : ".$response->data->requestURL."\n";
      //             echo "</pre>";
              } else {
                  // Timeout, you can redirect back to checkout page or echo error message.
                  // In this sample, we echo error message
                  // header("Location: "."http://example.com/checkout.php");
                  $kembali = "<pre>Connection Timeout. Please Try again.</pre>";
              }
          }
      }
        else {
            $kembali = "Unknown method";
        }
        return $kembali;
    }

    public static function provid($prov)
    {
        $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => "https://api.rajaongkir.com/starter/province",
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_SSL_VERIFYPEER => false,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 30,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "GET",
          CURLOPT_HTTPHEADER => array(
            "key: ea1486dca9b6970cd238f7dba1cff9cb"
          ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
          $res = "cURL Error #:" . $err;
        } else {
          $res = $response;
        }
        $tres = json_decode($response);
        foreach ($tres->rajaongkir->results as $r) {
            if(trim(strtolower($prov)) == trim(strtolower($r->province)))
                $res = $r->province_id;
        }
        return $res;
    }
    public static function cityid($city, $tipe, $provid)
    {
        $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => "https://api.rajaongkir.com/starter/city?province=$provid",
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_SSL_VERIFYPEER => false,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 30,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "GET",
          CURLOPT_HTTPHEADER => array(
            "key: ea1486dca9b6970cd238f7dba1cff9cb"
          ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
          $res = "cURL Error #:" . $err;
        } else {
          $res = $response;
        }

        $tres = json_decode($response);
        foreach ($tres->rajaongkir->results as $r) {
            if(trim(strtolower($city)) == trim(strtolower($r->city_name)) && trim(strtolower($tipe)) == trim(strtolower($r->type)))
                $res = $r->city_id;
        }

        return $res;
    }
    public static function jenisongkir($po, $co, $to, $pd, $cd, $td, $kurir)
    {
        $pido = Helper::provid($po);
        $cido = Helper::cityid($co, $to, $pido);

        $pidd = Helper::provid($pd);
        $cidd = Helper::cityid($cd, $td, $pidd);
        $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => "https://api.rajaongkir.com/starter/cost",
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_SSL_VERIFYPEER => false,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 30,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "POST",
          CURLOPT_POSTFIELDS => "origin=".$cido."&destination=".$cidd."&weight=1000&courier=".$kurir,
          CURLOPT_HTTPHEADER => array(
            "content-type: application/x-www-form-urlencoded",
            "key: ea1486dca9b6970cd238f7dba1cff9cb"
          ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
          $res = "cURL Error #:" . $err;
        } else {
          $res = $response;
        }
        $tres = json_decode($response);
        $hasil = array();
        
        foreach ($tres->rajaongkir->results[0]->costs as $r) {
            $data['service'] = $r->service;
            $data['harga'] = $r->cost[0]->value;
            $hasil[]=$data;
        }
        //print_r($hasil);die();
        return json_encode($hasil);
    }
    
    public static function ongkir($po, $co, $to, $pd, $cd, $td, $kurir, $jeniskirim)
    {
        $pido = Helper::provid($po);
        $cido = Helper::cityid($co, $to, $pido);

        $pidd = Helper::provid($pd);
        $cidd = Helper::cityid($cd, $td, $pidd);
        $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => "https://api.rajaongkir.com/starter/cost",
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_SSL_VERIFYPEER => false,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 30,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "POST",
          CURLOPT_POSTFIELDS => "origin=".$cido."&destination=".$cidd."&weight=1000&courier=".$kurir,
          CURLOPT_HTTPHEADER => array(
            "content-type: application/x-www-form-urlencoded",
            "key: ea1486dca9b6970cd238f7dba1cff9cb"
          ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
          $res = "cURL Error #:" . $err;
        } else {
          $res = $response;
        }
        $tres = json_decode($response);
        foreach ($tres->rajaongkir->results[0]->costs as $r) {
            if($r->service == $jeniskirim){
                $res = $r->cost[0]->value;
                $res2 = $r->cost[0]->etd;
            }
        }
        //print_r($hasil);die();
        return $res."|".$res2;
    }

    public static function randompass($digit)
    {
        $char = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789';
        $character = '';
        for ($i = 0; $i < $digit; $i++) {
        $pos = rand(0, strlen($char)-1);
        $character .= $char{$pos};
        }
        return $character;
    }
    
    
            
    public static function diskonbesar($string,$cut)
    {
      $string = substr($string, 0, $cut); 
      $string = $string . "..."; 
      return $string; 
    }
	
	public static function tgl_indonesia($date){
	    /* ARRAY u/ hari dan bulan */
	    $Hari = array ("Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu",);
	    $Bulan = array ("Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember");
		/* Memisahkan format tanggal bulan dan tahun menggunakan substring */
		$tahun     = substr($date, 0, 4);
		$bulan     = substr($date, 5, 2);
		$tgl    = substr($date, 8, 2);
		$waktu    = substr($date,11, 5);
		$hari    = date("w", strtotime($date));
		$result = $Hari[$hari].", ".$tgl." ".$Bulan[(int)$bulan-1]." ".$tahun." | ".$waktu." WIB";
		return $result;
	}
	
	public static function tgl_indonesia_doank($date){
	    /* ARRAY u/ hari dan bulan */
	    $Hari = array ("Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu",);
	    $Bulan = array ("Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember");
		/* Memisahkan format tanggal bulan dan tahun menggunakan substring */
		$tahun     = substr($date, 0, 4);
		$bulan     = substr($date, 5, 2);
		$tgl    = substr($date, 8, 2);
		$waktu    = substr($date,11, 5);
		$hari    = date("w", strtotime($date));
		$result = " ".$tgl." ".$Bulan[(int)$bulan-1]." ".$tahun." ";
		return $result;
	}

  public static function registerSchema(array $data)
    {
        $view = Yii::$app->view;

        $view->registerJs(
            '<script type="application/ld+json">' .
            json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) .
            '</script>',
            View::POS_HEAD
        );
    }
    
}

