<?php
class Telr extends CFormModel
{
	public $type = 'telr';
	private $trType = 26;

    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_addr1;
    public $bill_city;
    public $bill_email;


    /*------ response --------*/
    public $amount;
    public $currency;
    public $description;
    public $ref;
    public $cartid;
    public $status;
    public $message;

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

	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('amount, currency, description, ref, cartid, status', 'required', 'on'=>'return', 'message'=> Yii::t("main","36_cannot_be_blank")),

		);
	}
	
	public function init()
	{
        $this->action = Yii::app()->params['telr_action'];
        $this->ivp_test = Yii::app()->params['telr_ivp_test'];
        $this->ivp_store = Yii::app()->params['telr_ivp_store'];
        $this->ivp_authkey = Yii::app()->params['telr_ivp_authkey'];
	}


    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'),
        );
    }

    public function initData($data)
    {
        $data2 = $params = 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"];


        $params['ivp_method'] = $this->ivp_method;
        $params['ivp_store'] = $this->ivp_store;
        $params['ivp_authkey'] =$this->ivp_authkey;

        $params['bill_addr2'] = $params['ivp_amount'] = $data2['data']['real_amount'] = $this->ivp_amount = (int)$data["amount"];
        $params['bill_addr3'] = $params['ivp_currency'] = $data2['data']['real_currency'] = $this->ivp_currency = $data["currency"];

        if($data['currency'] !== 'AED'){
            $params['ivp_amount'] = $this->ivp_amount = round(stFunctions::currConv($this->ivp_currency, 'AED', $this->ivp_amount), 2);
            $params['ivp_currency'] = $this->ivp_currency = 'AED';

        }

        $params['ivp_test'] = $this->ivp_test;
        $params['ivp_cart'] = $data2['data']['ivp_cart'] = $this->ivp_cart = uniqid();
        $params['ivp_desc'] = $data2['data']['ivp_desc'] = $this->ivp_desc = (int)$data["transferTo"];
        $params['return_auth'] = $this->return_auth = $server.'/returnTrans?type='.$this->type.'&stat=auth&pre=initRequest';
        $params['return_decl'] = $this->return_auth = $server.'/returnTrans?type='.$this->type.'&stat=decl&pre=initRequest';
        $params['return_can'] = $this->return_auth = $server.'/returnTrans?type='.$this->type.'&stat=can&pre=initRequest';


        $params['bill_fname'] = $this->bill_fname = $Registration->firstName;
        $params['bill_sname'] = $this->bill_sname = $Registration->lastName;
        $params['bill_email'] = $this->bill_email = $Registration->email;
        $params['bill_country'] = $this->bill_country = $countries_code_two[$Registration->country];
        $params['bill_city'] = $this->bill_city = $Registration->city;
        $params['bill_addr1'] = $this->bill_addr1 = $Registration->address;


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

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

        $res = $this->sendRequest($params);

        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            $_SESSION['message'][] = array("text" => $res['order']['ref'].', '.$this->ivp_cart, "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
        }*/

        if(isset($res['order']['url'])){
            $data2['data']["link"] = $res['order']['url'];
            $data2["action"] = $res['order']['url'];

            $_SESSION['telr_order'] = $res['order']['ref'];

            $cookie = new CHttpCookie('telr_order',$res['order']['ref']);
            Yii::app()->request->cookies['telr_order'] = $cookie;

        }elseif(isset($res['error']['message']) && isset($res['error']['note'])){
            $_SESSION['message'][] = array("text" => $res['error']['message'].'. '.$res['error']['note'], "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
        }else{
            $_SESSION['message'][] = array("text" => 'Telr deposit error', "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
        }

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


        return $data2;
    }

    public function initRequest($data)
    {

       /* $ipx = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ipx == '77.222.143.18' || $ipx == '46.98.252.74') {
            var_dump($_SESSION, $_COOKIE);die();
        }*/

        if(isset($_COOKIE['telr_order'])){
            $params = array(
                'ivp_method' => 'check',
                'ivp_store' => $this->ivp_store,
                'ivp_authkey' => $this->ivp_authkey,
                'order_ref' => $_COOKIE['telr_order'],
            );
            $res = $this->sendRequest($params);



            if(isset($res['order'])){
                $this->attributes = $res['order'];
                $this->status = $res['order']['status']['code'];

                if(isset($res['order']["customer"]['address']['line2'])){
                    $this->amount = $res['order']["customer"]['address']['line2'];
                }

                if(isset($res['order']["customer"]['address']['line3'])){
                    $this->currency = $res['order']["customer"]['address']['line3'];
                }


            }
        }

    }

    public function sendRequest($params)
    {

            ###################### BEGIN #####################
            $post_field = '';
            foreach ($params as $key => $value){
                if ($post_field != '') $post_field .= '&';
                $post_field .= rawurlencode($key)."=".rawurlencode($value);
            }
            $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);

            $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 confirmOnReturn()
    {
        return $this->ApplyTransaction();
    }

    public function checkTransaction($ref)
    {
        $params = array(
            'ivp_method' => 'check',
            'ivp_store' => $this->ivp_store,
            'ivp_authkey' => $this->ivp_authkey,
            'order_ref' => $ref,
        );
        $res = $this->sendRequest($params);

        if(isset($res['order'])){
            /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                var_dump($res);die();
            }*/
            $this->attributes = $res['order'];
            $this->status = $res['order']['status']['code'];
            $this->message = $res['order']['status']['text'];
        }elseif(isset($res['error']['message'])){
            $this->status = -1;
            $this->message = $res['error']['message'];
        }


        return $res;
    }

	public function newTransaction($accountID, $value, $transactionID, $currency = 'AED', $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='.$this->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/telr.txt',"a");
        fwrite($f, date('Y-m-d H:i:s').' newTelrTransaction '.$this->type .' '.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.' ||||| '.json_encode($Info).'<br/>\n
		');

        return  $Info;
	}

	public function ApplyTransaction(){
	    $Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/ApplyTerlTransaction?errorcode='.($this->status == 3 ? 'APPROVED' : 'ERROR').'&transactionid='.$this->cartid.'&depValue=0&currency=');

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

        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->status == 3;
    }

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

}
