<?php
class Tap extends CFormModel
{
	public $type = 'tap';
	private $trType = 28;

    public $action;

	private $ivp_test;
	private $ivp_test_usd;

	public $amount;
	public $currency;
	public $udf1;
	public $udf2;
	public $transaction;
	public $description;
	public $first_name;
	public $last_name;
	public $email;
	public $phone;
	public $notify_url;
	public $redirect_url;


	//response
    public $status;

    //return
    public $tap_id;

    //return2
    private $customer_id;

    private $currencies = array('USD'=>'USD', 'KWD'=>'KWD', 'AED'=>'AED', 'BHD'=>'BHD', 'OMR'=>'OMR', 'QAR'=>'QAR');


	public function rules(){
		return array(
            array('amount, currency, udf1, udf2, transaction, first_name, last_name, email, phone, notify_url, redirect_url', 'required', 'on'=>'deposit', 'message'=> Yii::t("main","36_cannot_be_blank")),
            array('status, transaction', 'required', 'on'=>'callback', 'message'=> Yii::t("main","36_cannot_be_blank")),
            array('tap_id, currency', 'required', 'on'=>'return', 'message'=> Yii::t("main","36_cannot_be_blank")),
            array('amount, currency, description, status', 'required', 'on'=>'return2', 'message'=> Yii::t("main","36_cannot_be_blank")),
		);
	}
	
	public function init()
	{
        /*$this->action = Yii::app()->params['tap_action'];
        $this->ivp_test = Yii::app()->params['tap_aut_key'];*/

        $this->action = 'https://api.tap.company/v2/charges';
         //$this->ivp_test = 'sk_test_XKokBfNWv6FIYuTMg5sLPjhJ';
         // $this->ivp_test = 'sk_test_WlVZtXLcpyAUuHhr9QOE358j'; //test secret key - Swiss Capital
         // $this->ivp_test = 'sk_live_WP6G7Hop41kRjNwEIqUYJgef'; //live secret key - Swiss Capital
         // $this->ivp_test       = 'sk_test_q6jos2g7F83UdBLYVWc1rCMt'; //test secret key - SwissFS Kuwait
          $this->ivp_test       = 'sk_live_5KSqfUgdAZhtOxIF9DQLJX7i'; //test secret key - SwissFS Kuwait
          $this->ivp_test_usd   = 'sk_live_WejLnbFa5Bkr6YdDAhxOcCN1'; //test secret key - SwissFS Kuwait
         // $this->ivp_test = 'sk_live_5KSqfUgdAZhtOxIF9DQLJX7i'; //live secret key - SwissFS Kuwait
	}


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

    public function attributeLabels(){
        return array(
            'description' => Yii::t("main",'157_account'),
            'amount' => Yii::t("funds",'9_amount'),
            '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"];

        $data2['data']['amount'] = $this->amount = (int)$data["amount"];
        $data2['data']['currency'] = $this->currency = $data["currency"];


//        if($data['currency'] === 'USD'){
//           /* $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($this->currency, $this->amount);die();
//            }*/
//            $this->amount = round(stFunctions::currConv($this->currency, 'KWD', $this->amount), 2);
//            $this->currency = 'KWD';
//        }



        $data2['data']['transaction'] = $this->transaction = uniqid();
        $data2['data']['description'] = $this->description = (int)$data["transferTo"];
        $this->first_name = $Registration->firstName;
        $this->last_name = $Registration->lastName;
        $this->email = $Registration->email;
        $this->phone = $Registration->phone;
        $this->notify_url = $server.'/callbackTrans?type='.$this->type;
        $this->redirect_url = $server.'/returnTrans?type='.$this->type.'&pre=initRequest&currency='.$this->currency;

        $params = [
            "amount"=>$this->amount,
            "currency"=>$this->currency,
            "threeDSecure"=>true,
            "save_card"=>true,
            "description"=>$this->description,
            "statement_descriptor"=>"Sample",
            "metadata"=>[
                "udf1"=>$this->description,
                "udf2"=>"test 2"
            ],
            "reference"=>[
                "transaction"=>$this->transaction,
                "order"=>"ord_0001"
            ],
            "receipt"=>[
                "email"=>false,
                "sms"=>true
            ],
            "customer"=>[
                "first_name"=>$this->first_name,
                "middle_name"=>$this->last_name,
                "last_name"=>$this->last_name,
                "email"=>$this->email,
                "phone"=>[
                    "country_code"=>substr($this->phone, 0, 4),
                    "number"=>substr($this->phone, 5, 0),
                ]
            ],
            "source"=>[
                "id"=>"src_all"
            ],
            "post"=>[
                "url"=>$this->notify_url
            ],
            "redirect"=>[
                "url"=>$this->redirect_url
            ]
        ];


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

        /*$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($res);die();
        }*/


        if(isset($res['transaction']['url'])){
            $data2['data']["link"] = $res['transaction']['url'];
            $data2["action"] = $res['transaction']['url'];
        }elseif(isset($res['response']['message'])){
            $_SESSION['message'][] = array("text" => $res['response']['message'], "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
        }else{
            $_SESSION['message'][] = array("text" => 'Tap 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 parseCallback($json)
    {
        $data = json_decode($json, true);

        if(isset($data['reference']['transaction'])){
            $this->transaction = $data['reference']['transaction'];
        }

        if(isset($data['status'])){
            $this->status = $data['status'];
        }

        if(isset($data['customer']['id'])){
            $this->customer_id = $data['customer']['id'];
            $res0 = $this->AddUserPaymentSystemAccount();
        }

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

    public function initRequest($data)
    {
        $res = $this->getRequest();

        $this->setScenario('return2');



        if(isset($res['status'])){
            $this->status = $res['status'];
        }
        if(isset($res['customer']['id']) && isset($res['reference'])){
            $this->customer_id = $res['customer']['id'];
        }
        if(isset($res['description'])){
            $this->description = $res['description'];
        }
        if(isset($res['transaction'])){
            $this->attributes = $res['transaction'];
        }

    }

    public function sendRequest($params)
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->action,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($params),
            CURLOPT_HTTPHEADER => array(
                "authorization: Bearer ".($this->currency === 'USD' ? $this->ivp_test_usd : $this->ivp_test),
                "content-type: application/json"
            ),
        ));

        $response = json_decode(curl_exec($curl), true);
        $err = curl_error($curl);
        curl_close($curl);

        if(isset($response['status'])){ // && $response['status'] == 'INITIATED'
            return $response;
        }

        return $err;
    }

    public function getRequest()
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->action.'/'.$this->tap_id,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            //CURLOPT_POSTFIELDS => json_encode($params),
            CURLOPT_HTTPHEADER => array(
                "authorization: Bearer ".($this->currency === 'USD' ? $this->ivp_test_usd : $this->ivp_test),
                "content-type: application/json"
            ),
        ));

        $response = json_decode(curl_exec($curl), true);
        $err = curl_error($curl);
        curl_close($curl);


        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/tap.txt',"a");
        fwrite($f, date('Y-m-d H:i:s').' return parse '.$_SERVER['REMOTE_ADDR'].' '.date('Y-m-d H:i:s').' | '.$this->action.'/'.$this->tap_id.' | '.json_encode($response).'
                ');

        if(isset($response['status'])){
            return $response;
        }



        return $err;
    }



    public function confirmOnReturn()
    {
        return true;
    }

    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();

        //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/tap.txt',"a");
        fwrite($f, date('Y-m-d H:i:s').' newTapTransaction  '.$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/ApplyTapTransaction?errorcode='.($this->status == 'CAPTURED' ? 'APPROVED' : 'ERROR').'&transactionid='.$this->transaction.'&depValue=0&currency=');
	    //var_dump(Yii::app()->params['json_server'].'/API/Transactions/ApplyTapTransaction?errorcode='.($this->status == 'CAPTURED' ? 'APPROVED' : 'ERROR').'&transactionid='.$this->transaction.'&depValue=0&currency=');die();

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

        return  $Info;
	}

	public function AddUserPaymentSystemAccount(){
	    $Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/AddUserPaymentSystemAccount?transactionid='.$this->transaction.'&code='.$this->customer_id.'&trType='.$this->trType);

        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/tap.txt',"a");
        fwrite($f, date('Y-m-d H:i:s').' AddUserPaymentSystemAccount  '.$this->type .' '.Yii::app()->params['json_server'].'/API/Transactions/AddUserPaymentSystemAccount?transactionid='.$this->transaction.'&code='.$this->customer_id.'&trType='.$this->trType.' ||||| '.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 === 'CAPTURED';
    }

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

}
