<?php
class kNet2 extends CFormModel
{
	public $type = 'knet2';

    public $action;

    /* - ----- - - - - -- - - - - - - -*/
    public $price;
    public $qty = 1;
    public $TranportalId;
    public $TranportalPassword;
    public $TranTrackid;
    public $currency;
    public $langid = 'USA';
    public $actionParam = '1';
    public $ResponseUrl;
    public $ErrorUrl;
    public $udf1; // account
    public $udf2;
    public $udf3;
    public $udf4;
    public $udf5;
    private $termResourceKey;

    /* - ----- - - - - -- - - - - - - -*/

    private $currencies = array('KWD');
    private $currencyCode = array('KWD'=>414);


    public $paymentid;
    public $trackid;
    public $result;
    public $postdate;
    public $tranid;
    public $auth;
    public $ref;
    public $amt;
    public $ErrorText;
    public $Error;
    public $trandata;

    public $server;

	public function rules(){
		return array(
            array('price, udf1, currency', 'required', 'on'=>'deposit', 'message'=> Yii::t("main","36_cannot_be_blank")),

            array('paymentid, trackid, result, amt, udf1, udf2, udf3, udf4, udf5', 'required', 'on'=>'response', 'message'=> Yii::t("main","36_cannot_be_blank")),
           /* array('postdate, tranid, auth, ref', 'required', 'on'=>'response', 'message'=> Yii::t("main","36_cannot_be_blank"), 'when' => function ($model) {
                return $model->result != 'CANCELED';
            }),*/
            array('postdate, tranid, auth, ref', 'safe', 'on'=>'response', 'message'=> Yii::t("main","36_cannot_be_blank")),
            array('ErrorText, Error, trandata', 'safe', 'on'=>'response', 'message'=> Yii::t("main","36_cannot_be_blank")),
            //array('auth, postdate, tranid, ref, udf5', 'safe', 'on'=>'response', 'message'=> Yii::t("main","36_cannot_be_blank")),
		);
	}
	
	public function init()
	{
        $this->action = 'https://kpay.com.kw/kpg/PaymentHTTP.htm?param=paymentInit'; //test: kpaytest.com.kw
        $this->TranportalId = "247401"; //test: 140601
        $this->TranportalPassword = "pqNfbjY1"; //test: 140601pg
        $this->termResourceKey = "9204394891179204"; //test: 9178055535229178

        $this->langid = Yii::app()->language == 'ar' ? 'AR' : 'USA';
	}

    public function getAttribute($name){
        return $this->$name;
    }

    public function attributeLabels(){
        return array(
            'udf1' => Yii::t("main",'157_account'),
            'price' => Yii::t("funds",'9_amount'),
        );
    }

    public function getSalt()
    {
        return $this->termResourceKey;
    }

    public function initData($data)
    {
        $data2 = array();
        //var_dump($_SERVER['DOCUMENT_ROOT'], $data.'/assets/knet/');die();
        $Registration = new Registration('Individual');
        $Registration->initIndv();

        $server = ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:').'//'.$_SERVER["SERVER_NAME"];
        if(wlParams::get('officeCode') == 44){
            $server = 'https://my.swissfs.com';
        }
        $data2['data']['currency'] = $data["currency"];

        $this->price = $data2['data']['amount'] = $data["amount"];

        $this->udf1 = $data2['data']['transferTo'] = (int)$data["transferTo"];
        $this->udf2 = $this->price.$this->currency;
        $this->udf3 = substr(str_replace(" ","",$Registration->phone), -8);

        if($_SERVER['HTTP_HOST'] == 'my.sifx.sa.com'){
            $office_code = '44sifx';
        }else{
            $office_code = wlParams::get('officeCode');
        }

        $this->udf5 = $this->TranTrackid = $data2['data']["tr"] = uniqid().'_'.$office_code.'_k2';
        $this->udf4 = /*$this->md5 =*/ md5($this->udf1.$this->udf3.$this->udf2.$this->udf5.$this->termResourceKey);

        $this->ResponseUrl = $server."/payment/kNet2Trans";
        $this->ErrorUrl = $server."/payment/kNet2Trans";

        $this->currency = $this->currencyCode[$data["currency"]];

        /* ----------------------------------------------------------- */

        $ReqTranportalId="id=".$this->TranportalId;
        $ReqTranportalPassword="password=".$this->TranportalPassword;
        $ReqAmount="amt=".($this->price * $this->qty);
        $ReqTrackId="trackid=".$this->TranTrackid;
        $ReqCurrency="currencycode=".$this->currency;
        $ReqLangid="langid=USA";
        $ReqAction="action=1";
        $ReqResponseUrl="responseURL=".$this->ResponseUrl;
        $ReqErrorUrl="errorURL=".$this->ErrorUrl;

        $ReqUdf1="udf1=".$this->udf1;
        $ReqUdf2="udf2=".$this->udf2;
        $ReqUdf3="udf3=".$this->udf3;
        $ReqUdf4="udf4=".$this->udf4;
        $ReqUdf5="udf5=".$this->udf5;

        $param = $ReqTranportalId."&".$ReqTranportalPassword."&".$ReqAction."&".$ReqLangid."&".$ReqCurrency."&".$ReqAmount."&".$ReqResponseUrl."&".$ReqErrorUrl."&".$ReqTrackId."&".$ReqUdf1."&".$ReqUdf2."&".$ReqUdf3."&".$ReqUdf4."&".$ReqUdf5;
        $param = $this->encryptAES($param,$this->termResourceKey)."&tranportalId=".$this->TranportalId."&responseURL=".$this->ResponseUrl."&errorURL=".$this->ErrorUrl;
      //  $param = $param."&tranportalId=".$this->TranportalId."&responseURL=".$this->ResponseUrl."&errorURL=".$this->ErrorUrl;

        $data2["action"] = $this->action."&trandata=".$param;

//        var_dump($ReqLangid);
//        var_dump($ReqCurrency);
//        var_dump($param);
//        exit();

        /* ----------------------------------------------------------- */
        /*if((wlParams::get('officeCode')==44) && isset($data2['action'])){
            $data2['data']['link'] = $data2['action'];
            $data2['action'] = 'https://my.swissfs.com/payment/paymentRedirect';
        }*/


        $data2["message"] = Yii::t("funds","446_you_will_redir_secure_payment");
        $data2['type'] = $this->type;

        return $data2;
    }
	
	public function newTransaction($accountID, $value, $transactionID, $currency = 'KWD', $Id = ''){
        $Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.trim($transactionID).'&currency='.$currency.'&value='.$value.'&Id='.$Id.'&accountID='.$accountID.'&trType=18');

//var_dump($Info, Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.trim($transactionID).'&currency='.$currency.'&value='.$value.'&Id='.$Id.'&accountID='.$accountID.'&trType=18');die();



        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/knet2.txt',"a");
        fwrite($f, date('Y-m-d H:i:s').' newkNetTransaction  '.Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.trim($transactionID).'&currency='.$currency.'&value='.$value.'&Id='.$Id.'&accountID='.$accountID.'&trType=18'.' ||||| '.json_encode($Info).'<br/>\n
		');

        return  $Info;
	}

	public function ApplykNetTransaction(){
	    //var_dump(Yii::app()->params['json_server'].'/API/Transactions/ApplykNetTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency='.$currency);die();

        //var_dump($this->attributes);die();


	    $Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/ApplykNetTransaction?errorcode='.($this->result == 'CAPTURED' ? 'APPROVED' : 'CANCELED').'&transactionid='.$this->udf5.'&depValue=0&currency=');

	    //var_dump($Info, Yii::app()->params['json_server'].'/API/Transactions/ApplykNetTransaction?errorcode='.($this->result == 'CAPTURED' ? 'APPROVED' : 'CANCELED').'&transactionid='.$this->udf5.'&depValue=0&currency=');die();

        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/knet2.txt',"a");
        fwrite($f, date('Y-m-d H:i:s').' ApplykNetTransaction  '.Yii::app()->params['json_server'].'/API/Transactions/ApplykNetTransaction?errorcode='.($this->result == 'CAPTURED' ? 'APPROVED' : 'CANCELED').'&transactionid='.$this->udf5.'&depValue=0&currency= ||||| '.json_encode($Info).'<br/>\n
		');

        return  $Info;
	}

    public function checkResponse()
    {
        return (md5($this->udf1.$this->udf3.$this->udf2.$this->udf5.$this->termResourceKey) == $this->udf4 || $this->result == 'NOT CAPTURED');

	}

    //AES Encryption Method Starts
    function encryptAES($str,$key) {
        $str = $this->pkcs5_pad($str);
        $encrypted = openssl_encrypt($str, 'AES-128-CBC', $key, OPENSSL_ZERO_PADDING, $key);
        $encrypted = base64_decode($encrypted);
        $encrypted = unpack('C*', ($encrypted));
        $encrypted = $this->byteArray2Hex($encrypted);
        $encrypted = urlencode($encrypted);
        return $encrypted;
    }

    function pkcs5_pad ($text) {
        $blocksize = 16;
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
    function byteArray2Hex($byteArray) {
        $chars = array_map("chr", $byteArray);
        $bin = join($chars);
        return bin2hex($bin);
    }

    public function showRedirectLink()
    {

        /*if(isset($_REQUEST['st']) && ($_REQUEST['st'] == 'success') && $AwePay->status == 'OK'){
            Yii::app()->getController()->redirect('/transaction.html?ammount='.$AwePay->ref3.'&currency='.$AwePay->ref4.'&account='.$AwePay->ref1);
        }else{
            Yii::app()->getController()->redirect('/transaction.html?errorText='.$AwePay->msg);
        }*/

        //$this->responseURL = $http.'//'.$_SERVER["SERVER_NAME"].'/payment/kNetTrans';

        $server = ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:').'//'.$_SERVER["SERVER_NAME"];

        if(strstr($this->udf5, '_')){
            $tmp = explode('_', $this->udf5);
            if(isset($tmp[1]) && $tmp[1] === 44){
                $server = 'https://my.sifxmarkets.sa.com';
            }elseif(isset($tmp[1]) && $tmp[1] === '44sifx'){
                $server = 'https://my.sifx.sa.com';
            }
        }

        return 'REDIRECT='.$server."/transaction.html?PaymentID=" . $this->paymentid . "&Result=" . $this->result . "&PostDate=" . $this->postdate . "&TranID=" . $this->tranid . "&Auth=" . $this->auth . "&Ref=" . $this->ref . "&TrackID=" . $this->trackid . "&UDF1=" . $this->udf1 . "&UDF2=" .$this->udf2  . "&UDF3=" . $this->udf3  . "&UDF4=" . $this->udf4 . "&UDF5=" . $this->udf5  ;
	}

    function decrypt($code) {
        $code =  $this->hex2ByteArray(trim($code));
        $code = $this->byteArray2String($code);
        $iv = $this->termResourceKey;
        $code = base64_encode($code);
        $decrypted = openssl_decrypt($code, 'AES-128-CBC', $this->termResourceKey, OPENSSL_ZERO_PADDING, $iv);
        return $this->pkcs5_unpad($decrypted);
    }

    function hex2ByteArray($hexString) {
        $string = hex2bin($hexString);
        return unpack('C*', $string);
    }


    function byteArray2String($byteArray) {
        $chars = array_map("chr", $byteArray);
        return join($chars);
    }


    function pkcs5_unpad($text) {
        $pad = ord($text{strlen($text)-1});
        if ($pad > strlen($text)) {
            return false;
        }
        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
            return false;
        }
        return substr($text, 0, -1 * $pad);
    }




}
