<?php
class PayTab extends CFormModel
{

	private $trType = 39;
    public $type = 'paytab';

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


    private $profile_id;
    private $tran_type = "sale"; // https://support.paytabs.com/en/support/solutions/articles/60000711310-what-is-the-tran-type-transaction-type-
    private $tran_class = "ecom"; // https://support.paytabs.com/en/support/solutions/articles/60000711330-what-is-the-tran-class-transaction-class-

    private $CallBackUrl;
    private $return;
    // card_details
    private $cart_id;
    private $cart_description;
    private $cart_currency;
    private $cart_amount;
    // customer_details
    private $CustomerName;
    private $CustomerEmail;
    private $CustomerMobile;
    private $Address;
    private $city;
    private $state;
    private $country;
    private $ip;

    public $originalDomain;
    public $redirectedDomain;

    private $CustomerReference;
    private $credentials;


	public function rules(){
		return array(
           );
	}
	public function init()
	{
        $this->action = Yii::app()->params['paytab_action'];
        $this->profile_id = Yii::app()->params['paytab_profile_id'];
        $this->secret_key = Yii::app()->params['paytab_server_key'];

        if(in_array(wlParams::get('officeCode'), [80])){
            $this->redirectedDomain = 'https://pay.platinumriskcontrol.com';
        }

        if(in_array(wlParams::get('officeCode'), [60])){
                $this->redirectedDomain = 'https://payments.swiss-global.info';
            }
        if(in_array(wlParams::get('officeCode'), [83])){
            $this->redirectedDomain = 'https://pay4.swiss-global.info';
        }

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

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

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
         var_dump($data);die();
        }*/

        $this->ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];

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

        $data2['data']['UserDefinedField'] = $this->cart_id = uniqid();
        $data2['data']['DisplayCurrencyIso'] = $this->cart_currency = $data["currency"];
        $data2['data']['InvoiceValue'] = $this->cart_amount =  (float)$data["amount"];
        $data2['data']['CustomerReference'] = $this->CustomerReference =  (int)$data["transferTo"];

        $this->CustomerName = $Registration->firstName.' '.$Registration->lastName;
        $this->CustomerMobile = stFunctions::randomizePhone(substr(str_replace(' ', '', $Registration->phone), -11));
        $this->CustomerEmail = stFunctions::randomizeEmail($Registration->email);
        $this->Address = $Registration->address;
        $this->city  = $Registration->city;
        $this->country  = $Registration->country;

        $this->CallBackUrl = $this->redirectedDomain.'/payment/response/'.$this->type.'?d=i&code='.wlParams::get('officeCode');
        //$data2['data']['error_url'] = $this->return = $http.'//'.$_SERVER["SERVER_NAME"].'/returnTrans?type='.$this->type.'&stat=error';
        $data2['data']['error_url'] = $this->return = $this->redirectedDomain.'/payment/return/'.$this->type.'?code='.wlParams::get('officeCode').'&d=i';

        if($this->cart_currency !== 'AED') {
            $this->cart_amount = round(stFunctions::currConv($this->cart_currency, 'AED', $this->cart_amount), 2);
            $this->cart_currency = 'AED';
        }

        $data = [
            'profile_id' => $this->profile_id,
            'tran_type' => $this-> tran_type,
            'tran_class' => $this->tran_class,
            'cart_id' => $this->cart_id,
            'cart_description' => $this->CustomerReference.'|'.$data2['data']['InvoiceValue'].'|'.$data2['data']['DisplayCurrencyIso'].'|'.$this->type,
            'cart_currency' => $this->cart_currency,
            'cart_amount' => $this->cart_amount,
            'callback' => $this->CallBackUrl,
            'return' => $this->return,
            'hide_shipping' => true,
            'customer_details' => [
                'name' => $this->CustomerName,
                'email' => $this->CustomerEmail,
                'phone' => $this->CustomerMobile,
                'street1' => $this->Address,
                'city' => $this->city,
                'state' => '',
                'country' => isset($countries_code_two[$this->country]) ? $countries_code_two[$this->country] : '',
                'ip' => $this->ip,
            ]
        ];

        $result = $this->getPaymentUrl($data);

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            var_dump($data, $result, $this->redirectedDomain.'/payment/handler');die();
        }*/

        if(isset($result['serviceId']) && $result['serviceId']){
            $data2['data']["link"] = $result['redirect_url'];
            $data2["action"] = $this->redirectedDomain.'/payment/handler';
        }else{
            $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/payTab.txt',"a");
            fwrite($f, date('Y-m-d H:i:s').' initData '.$this->type .' '.json_encode($result).'  ||||| '.json_encode($data2).'<br/>\n');

            $_SESSION['message'][] = array("text" => $result['message'], "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;
    }

    private function getPaymentUrl($data) {

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

        $curl = curl_init();

        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump($this->action."/v2/SendPayment", $this->token, $this->cred_ar[$this->credentials]['ref'], json_encode($data));die();
        }*/

        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->action,
            CURLOPT_CUSTOMREQUEST => "POST",
            //CURLOPT_CONNECTTIMEOUT => 5,
            //CURLOPT_REFERER => $this->cred_ar[$this->credentials]['ref'],
            //CURLOPT_POSTFIELDS => "{\"NotificationOption\":\"LNK\",\"CustomerName\": \"Ahmed\",\"DisplayCurrencyIso\": \"KWD\", \"MobileCountryCode\":\"+965\",\"CustomerMobile\": \"92249038\",\"CustomerEmail\": \"aramadan@myfatoorah.com\",\"InvoiceValue\": 100,\"CallBackUrl\": \"https://google.com\",\"ErrorUrl\": \"https://google.com\",\"Language\": \"en\",\"CustomerReference\" :\"ref 1\",\"CustomerCivilId\":12345678,\"UserDefinedField\": \"Custom field\",\"ExpireDate\": \"\",\"CustomerAddress\" :{\"Block\":\"\",\"Street\":\"\",\"HouseBuildingNo\":\"\",\"Address\":\"\",\"AddressInstructions\":\"\"},\"InvoiceItems\": [{\"ItemName\": \"Product 01\",\"Quantity\": 1,\"UnitPrice\": 100}]}",
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => array("authorization: ".$this->secret_key,"Content-Type: application/json"),

        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($curl);
        $err = curl_error($curl);
        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump($response, $err);die();

        }*/

        //var_dump($err);die();
        curl_close($curl);



        return json_decode($response, true);
    }

    public function getPaymentStatus() {
        $curl = curl_init();

        $data = [
            'Key' => $this->paymentId,
            'KeyType' => 'PaymentId',
        ];

        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->action."/v2/GetPaymentStatus",
            CURLOPT_CUSTOMREQUEST => "POST",
           // CURLOPT_REFERER => $this->cred_ar[$this->credentials]['ref'],
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => array("authorization".$this->secret_key,"Content-Type: application/json"),

        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

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

        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/payTab.txt',"a");
        fwrite($f, date('Y-m-d H:i:s').' getPaymentStatus  '.$this->credentials .' '.$_SERVER['REMOTE_ADDR'].' '.date('Y-m-d H:i:s').' '.json_encode($response).'<br/>\n
		');


        $this->attributes = $response;
        if(isset($response["Data"])){
            $this->attributes = $response["Data"];
        }

        $lastTr = array_pop($response["Data"]['InvoiceTransactions']);
///!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        $this->TransactionStatus = $lastTr['TransactionStatus'];
///!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        $this->Message = $lastTr['Error'];

        /*if ($_SERVER['REMOTE_ADDR'] == '46.98.17.9' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump(222, $this->TransactionStatus);die();
        }*/
        $tmp = explode('|',$this->CustomerReference);
        $this->CustomerReference = $tmp[0];
     //   $this->Summary = $tmp[1];
        $this->cart_currency = $tmp[2];
    //    $this->pc_type = $tmp[3];

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

        return $response;
    }

    // ???
    public function confirmOnReturn(){
        return true;
    }

//        createTrans	"1"
//        type	"paytab"
//        UserDefinedField	"64dcce6f5261e"
//        DisplayCurrencyIso	"AED"
//        InvoiceValue	"51"
//        CustomerReference	"777407297"
//        link	"https://secure.paytabs.com/payment/wr/5E2F0B7682E404B0457FAE2E62432EC4B6045ECFA908318359A51361"
	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='.$this->trType);
//echo 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); exit();
        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/payTab.txt',"a");
        fwrite($f, date('Y-m-d H:i:s').' - '.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(){
        // ApplyPayTabsTransaction(string errorcode, string transactionid, double depValue, string currency)
	    $Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/ApplyPayTabsTransaction?errorcode='.($this->TransactionStatus == 'Succss' ? 'APPROVED' : 'ERROR').'&transactionid='.$this->cart_id.'&depValue=0&currency=');


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


        return  $Info;
	}

    public function checkResponse()
    {
        return true;

	}

    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'];

        }
    }

    //request payment sys -> PaymentController->actionReturnTrans ->
    public function getRedirectLink()
    {
        $f=fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/payTabRedirect.txt', "a");
        fwrite($f, date('Y-m-d H:i:s').' initData  '.json_encode($_REQUEST).'  ||||| <br/>\n');

        if($_REQUEST['status'] === 'success'){
            return '/transaction.html?ammount=&currency=&account=';
        }else{
            // {"type":"paytab","stat":"error","acquirerMessage":"","acquirerRRN":"","cartId":"64df7a222b892","customerEmail":"aa@bmfn.com","respCode":"321","respMessage":"Cancelled","respStatus":"C","signature":"9024f636fa5f576074f4ee519f64fe72e0a4da6860eecd65eaa27fe32e47c83d","token":"","tranRef":"TST2323001703926"}  |||||
            return '/transaction.html?errorText='.(isset($_REQUEST['respMessage']) ? $_REQUEST['respMessage'] : 'Something went wrong');
        }
    }

    public function parseCallback($json)
    {
        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/payTabCallback.txt',"a");
        fwrite($f, date('Y-m-d H:i:s').' initData  '.$json.'  ||||| <br/>\n');

        $data = json_decode($json, true);
        $this->attributes = $data;

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

    }

    public function initRequest($data)
    {
        $this->setScenario('return2');

        $this->attributes = $data;
    }

}
