<?php
class kNet extends CFormModel
{
	public $type = 'knet';

    public $action = '';

    public $currency;
    public $language;
    public $responseURL;
    public $errorURL;
    public $amount;
    public $resourcePath;
    public $alias;
    public $trackId;
    public $udf1;
    public $udf2;
    public $udf3;
    public $udf4;
    public $udf5;
    public $account;
    public $tr;
    public $md5;

    private $currencies = array('KWD');
    private $currencyCode = array('KWD'=>414);
    private $languages = array('en'=>'ENG', 'ar'=>'ARA');
    private $salt;

    public $paymentid;
    public $result;
    public $postdate;
    public $tranid;
    public $auth;
    public $ref;
    public $trackid;


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

            array('paymentid, result, trackid, udf1, udf2, udf3, udf4, udf5', 'required', '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")),
            //array('result, sod, pid, account, md5, currency, amount, domain', 'required', 'on'=>'return', 'message'=> Yii::t("main","36_cannot_be_blank")),
		);
	}
	
	public function init()
	{
        $this->language = isset($this->languages[Yii::app()->language]) ? $this->languages[Yii::app()->language] : 'ENG';
        $this->alias = 'swiss';
        //$this->trackId = '3434';
        //$this->trackId = mt_rand(11111,99999);
        //$this->trackId = uniqid("");
        $this->salt = 'mB3fyCHymMz';
	}

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

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

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

    public function initData($data)
    {
        $data2 = array();
        //var_dump($_SERVER['DOCUMENT_ROOT'], $data.'/assets/knet/');die();
        require_once $_SERVER['DOCUMENT_ROOT']."/protected/config/knet/e24PaymentPipe.inc.php";
        $Pipe = new e24PaymentPipe;

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

        if(wlParams::get('officeCode') == 44){
            $server = 'https://my.swissfs.com';
        }

        $this->responseURL = $server.'/payment/kNetTrans';
        $this->errorURL = $server.'/payment/kNetTrans';
        $this->resourcePath = $_SERVER['DOCUMENT_ROOT'].'/protected/config/knet/cert/';
        $this->amount = $data2['data']['amount'] = $data["amount"];
        $data2['data']['currency'] = $data["currency"];
        $this->currency = $data["currency"];


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

        $this->udf5 = $this->tr = $this->trackId = $data2['data']['tr'] = uniqid().'_'.$office_code;

        $Registration = new Registration('Individual');
        $Registration->initIndv();
        $this->udf3 = $Registration->email;

        $Pipe->setAction(1);
        $Pipe->setCurrency($this->currencyCode[$this->currency]);
        $Pipe->setLanguage($this->language);
        $Pipe->setResponseURL($this->responseURL);
        $Pipe->setErrorURL($this->errorURL);
        $Pipe->setAmt($this->amount);

        $Pipe->setResourcePath($this->resourcePath);
        $Pipe->setAlias($this->alias);
        $Pipe->setTrackId($this->trackId);

        $this->udf1 = $this->account = $data2['data']['transferTo'] = (int)$data["transferTo"];


        $this->udf2 = $this->amount.$this->currency;

        $this->udf4 = $this->md5 = md5($this->udf1.$this->udf3.$this->udf2.$this->udf5.$this->salt);

        $Pipe->setUdf1($this->udf1);
        $Pipe->setUdf2($this->udf2);
        $Pipe->setUdf3($this->udf3);
        $Pipe->setUdf4($this->udf4);
        $Pipe->setUdf5($this->udf5);

        //var_dump($this->currency, $this->language, $this->responseURL, $this->errorURL, $this->amount, $this->resourcePath, $this->alias, $this->trackId, 'udf', $this->account, $this->currency, $this->amount, $this->tr, $this->md5);die();


        if($Pipe->performPaymentInitialization()!=$Pipe->SUCCESS){

            //var_dump('11', $Pipe->getErrorMsg(), $Pipe->getDebugMsg());die();
            //var_dump($Pipe, '||||||||||||||||||||||||||||||', $Pipe->getDebugMsg(), '||||||||||||||||||||||||||||||', $Pipe->getErrorMsg());die();

            $_SESSION['message'][] = array("text"=>$Pipe->getErrorMsg(),"action"=>Yii::app()->controller->id."/".Yii::app()->controller->action->id,"type"=>"error");

            //echo "Result=".$Pipe->SUCCESS;
            //echo "<br>".$Pipe->getErrorMsg();
           // echo "<br>".$Pipe->getDebugMsg();
            //header("location: https://www.yourURL.com/error.php");
        }else {


            $payID = $Pipe->getPaymentId();
            $payURL = $Pipe->getPaymentPage();

            //var_dump($payURL.'?PaymentID='.$payID);die();


            $data2['action'] = $this->action = $payURL.'?PaymentID='.$payID;

            /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                var_dump($payURL.'?PaymentID='.$payID);die();
            }*/
            //var_dump($Pipe, '||||||||||||||||||||||||||||||', $Pipe->getPaymentId(), '||||||||||||||||||||||||||', $Pipe->getPaymentPage());die();

            //echo $Pipe->getDebugMsg();
            //header("location:".$payURL."?PaymentID=".$payID);
            //$_POST['transferTo'], $_POST['amount'], $_POST['token'], $_POST['currency']

        }


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

        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump($this->attributes);die();
        }*/

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

        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump(wlParams::get('officeCode')==22, isset($data2['action']), $data2);die();
        }*/

        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/knet.txt',"a");
        fwrite($f, '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/knet.txt',"a");
        fwrite($f, '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->salt) == $this->udf4 || $this->result == 'NOT CAPTURED');

	}

    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] === 444){
                $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  ;
	}


}