<?php
class Upay extends CFormModel
{
	public $type = 'upay';
	private $trType = 27; // ???

    public $action;

    private $ivp_store;
    private $ivp_authkey;

    private $ivp_method = 'create';


    /* - ----- - - - - -- - - - - - - -*/
    public $ivp_amount;
    public $ivp_currency;
    public $ivp_test;
    public $ivp_cart;
    public $ivp_desc;
    public $return_auth;
    public $return_decl;
    public $return_can;

    public $bill_fname;
    public $bill_sname;
    public $bill_country;
    public $bill_email;


    /* ----- */
    private $merchant_id;
    private $username;
    private $password;
    private $api_key;
    private $test_mode;
    public $order_id;
    public $total_price;
    public $CurrencyCode;
    public $CstFName;
    public $CstEmail;
    public $CstMobile;
    public $success_url;
    public $error_url;
    public $notifyURL;
    public $whitelabled = false;
    public $payment_gateway = 'knet';
    public $ProductName;
    public $ProductQty;
    public $ProductPrice;
    public $reference;


    /* response */
    public $OrderID;
    public $Result;

    // 'merchant_id',


    private $currencies = array('USD'=>'USD', 'KWD'=>'KWD');

	public function rules(){
		return array(
            //array('ivp_amount, ivp_currency, ivp_test, ivp_cart, ivp_desc, return_auth, return_decl, return_can', 'required', 'on'=>'deposit', 'message'=> Yii::t("main","36_cannot_be_blank")),
            array('merchant_id, username, password, api_key, order_id, total_price, CurrencyCode, CstFName, CstEmail, CstMobile, success_url, error_url, notifyURL, test_mode, whitelabled, payment_gateway, ProductName, ProductQty, ProductPrice, reference', 'required', 'on'=>'deposit', 'message'=> Yii::t("main","36_cannot_be_blank")),


            array('OrderID, Result', 'required', 'on'=>'callback, return', 'message'=> Yii::t("main","36_cannot_be_blank")),

		);
	}
	
	public function init()
	{
        $this->action = Yii::app()->params['upay_action'];
        //$this->action = 'https://api.upayments.com/payment-request';

        $this->merchant_id = Yii::app()->params['upay_merchant_id'];
        $this->username = Yii::app()->params['upay_username'];
        $this->password = Yii::app()->params['upay_password'];
        $this->api_key = Yii::app()->params['upay_api_key'];
        $this->test_mode = Yii::app()->params['upay_test_mode'];

	}


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

    public function attributeLabels(){
        return array(
            /*'ivp_desc' => Yii::t("main",'157_account'),
            'ivp_amount' => Yii::t("funds",'9_amount'),
            'ivp_currency' => Yii::t("funds",'450_currency'),*/

            'ProductName' => Yii::t("main",'157_account'),
            'total_price' => Yii::t("funds",'9_amount'),
            'CurrencyCode' => Yii::t("funds",'450_currency'),
        );
    }

    public function initData($data)
    {
        $data2 = array();

        $Registration = new Registration('Individual');
        $countries_code_two = $Registration->GetCountry('two');
        $Registration->initIndv();

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

        /*
        $data2['data']['ivp_method'] = $this->ivp_method;
        $data2['data']['ivp_store'] = $this->ivp_store;
        $data2['data']['ivp_authkey'] = $this->ivp_authkey;
        $data2['data']['ivp_amount'] = $this->ivp_amount = (int)$data["amount"];
        $data2['data']['ivp_currency'] = $this->ivp_currency = $data["currency"];
        $data2['data']['ivp_test'] = $this->ivp_test;
        $data2['data']['ivp_cart'] = $this->ivp_cart = uniqid();
        $data2['data']['ivp_desc'] = $this->ivp_desc = (int)$data["transferTo"];
        $data2['data']['return_auth'] = $this->return_auth = $server.'/returnTrans?type='.$this->type.'&stat=auth';
        $data2['data']['return_decl'] = $this->return_auth = $server.'/returnTrans?type='.$this->type.'&stat=decl';
        $data2['data']['return_can']  = $this->return_auth = $server.'/returnTrans?type='.$this->type.'&stat=can';

        $data2['data']['bill_fname'] = $this->bill_fname = $Registration->firstName;
        $data2['data']['bill_sname'] = $this->bill_sname = $Registration->lastName;
        $data2['data']['bill_email'] = $this->bill_email = $Registration->email;
        $data2['data']['bill_country'] = $this->bill_country = $countries_code_two[$Registration->country];


        $Info = Yii::app()->curl->post($this->action, $data2['data']);
        */

        $data3 = array();

        $data2['data']['merchant_id'] = $this->merchant_id;
        $data2['data']['username'] = $this->username;
        $data2['data']['password'] = stripslashes($this->password);
        //$data2['data']['api_key'] = $this->api_key;
        $data2['data']['api_key'] = password_hash($this->api_key,PASSWORD_BCRYPT);
        $data2['data']['order_id'] = $data3['data']['order_id'] = $this->order_id = uniqid();
        $data2['data']['total_price'] = $data3['data']['total_price'] = $this->total_price = (int)$data["amount"];
        $data2['data']['CurrencyCode'] = $data3['data']['CurrencyCode'] = $this->CurrencyCode = $data["currency"];

        if($this->CurrencyCode != 'KWD'){
            $data2['data']['total_price'] = round(stFunctions::currConv($this->CurrencyCode, 'KWD', $this->total_price), 2);
            $data2['data']['CurrencyCode'] = 'KWD';
        }

        $data2['data']['CstEmail'] = $this->CstEmail = $Registration->email;
        $data2['data']['CstMobile'] = $this->CstMobile = $Registration->phone;
        $data2['data']['success_url'] = $this->success_url = $server.'/returnTrans?type='.$this->type.'&stat=success';
        $data2['data']['error_url'] = $this->error_url = $server.'/returnTrans?type='.$this->type.'&stat=error';
        $data2['data']['notifyURL'] = $this->notifyURL = $server.'/callbackTrans?type='.$this->type.'&dg=p';
        $data2['data']['test_mode'] = $this->test_mode;
        $data2['data']['whitelabled'] = $this->whitelabled;
        $data2['data']['payment_gateway'] = $this->payment_gateway;
        $data2['data']['ProductName'] = json_encode([(int)$data["transferTo"]]);
        $data2['data']['ProductQty'] = json_encode([1]);
        $data2['data']['ProductPrice'] = json_encode([$this->total_price]);
        $data2['data']['reference'] = $data3['data']['reference'] = $this->reference = (int)$data["transferTo"];


//var_dump($data2['data']);die();
        $res = $this->sendRequest($data2['data']);
//var_dump($res);die();

        if(isset($res['paymentURL'])){
            $data3['data']["link"] = $res['paymentURL'];
            $data3["action"] = $res['paymentURL'];
        }elseif(isset($res['error_msg'])){
            $_SESSION['message'][] = array("text"=>$res['error_msg'],"action"=>Yii::app()->controller->id."/".Yii::app()->controller->action->id,"type"=>"error");
        }

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


        return $data3;
    }

    public function sendRequest($params)
    {

       // var_dump($params);die();
            ###################### BEGIN #####################
            /*$post_field = '';
            foreach ($params as $key => $value){
                if ($post_field != '') $post_field .= '&';
                $post_field .= rawurlencode($key)."=".rawurlencode($value);
            }*/

            $post_field = http_build_query($params);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,$this->action);
            curl_setopt($ch, CURLOPT_ENCODING , 'UTF-8');
            curl_setopt($ch, CURLOPT_VERBOSE, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/x-www-form-urlencoded',
                'Connection: Keep-Alive'
            ));

            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_field);
            $result = curl_exec($ch);

            //var_dump('22', $this->action, $result, $post_field, $params);die();

            $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            if ($result != '' && $status==200){
                $nl_result  = json_decode($result, true);
                return $nl_result;
            }

            return false;
            ###################### END #####################


    }

    public function parseCallback($json)
    {
        $data = json_decode($json, true);
        $this->attributes = $data;

        if($this->isSuccess()){
            $res = $this->ApplyTransaction();
        }

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

    public function confirmOnReturn(){
        return true;
    }

	public function newTransaction($accountID, $value, $transactionID, $currency = 'KWD', $Id = ''){

	    //var_dump($this->cred_ar[$this->credentials]['trType'], $this->credentials);die();


        $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='.$this->trType); // $this->cred_ar[$this->credentials]['trType']

        //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='.$this->trType);die();


        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/fatoorah.txt',"a");
        fwrite($f, date('Y-m-d H:i:s').' newFatoorahTransaction  '.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='.$this->type.' ||||| '.json_encode($Info).'<br/>\n
		');

        return  $Info;
	}

	public function ApplyTransaction(){
	    //var_dump(Yii::app()->params['json_server'].'/API/Transactions/ApplyUpayTransaction?errorcode='.($this->Result == 'CAPTURED' ? 'APPROVED' : 'ERROR').'&transactionid='.$this->OrderID.'&depValue=0&currency=');die();
	    $Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/ApplyUpayTransaction?errorcode='.($this->Result == 'CAPTURED' ? 'APPROVED' : 'ERROR').'&transactionid='.$this->OrderID.'&depValue=0&currency=');

	    //var_dump($Info, Yii::app()->params['json_server'].'/API/Transactions/ApplyMyFatoorahTransaction?errorcode='.($this->IsSuccess ? 'APPROVED' : 'ERROR').'&transactionid='.$this->UserDefinedField.'&depValue=0&currency=');die();

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

        //var_dump($Info, Yii::app()->params['json_server'].'/API/Transactions/ApplyMyFatoorahTransaction?errorcode='.($this->status == 'success' ? 'success' : 'error').'&transactionid='.$this->transactionId.'&depValue=0&currency=');die();

        return  $Info;
	}

    public function checkResponse()
    {
        return true;

	}



    /*public function showRedirectLink()
    {
        $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.swissfs.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  ;
	}*/

   /* public function initResponse($data)
    {
        if(!empty($data)){
            $SignatureHandler = new SignatureHandler($this->getSecret());
            $this->Callback = new Callback($data, $SignatureHandler);


            $details = $this->Callback->getPayment();

            $this->transactionId = $this->Callback->getPaymentId();
            $this->status = $this->Callback->getPaymentStatus();
            $this->description = $details['description'];
            $this->amount = $details['sum']['amount'];
            $this->currency = $details['sum']['currency'];

        }
    }*/

    public function isSuccess()
    {
        return $this->Result === 'CAPTURED';
    }

    public function getRedirectLink()
    {
        if($this->isSuccess()){
            return '/transaction.html?ammount=&currency=&account=';
        }else{
            return '/transaction.html?errorText=';
        }
    }

}
