<?php
class Network extends CFormModel
{
    public $type = 'network';
    private $trType;

    private $idServiceURL;
    private $txnServiceURL;

    private $apikey;
    private $outletRef;

    public $action;
    public $contentType;

    /* - ----- - - - - -- - - - - - - -*/
    public $mode = 'SALE'; // 'AUTH';
    public $value;
    public $currencyCode;
    public $emailAddress;
    public $language = 'en';
    public $merchantOrderReference;
    public $redirectUrl;
    public $redirectUrlDomain;

    public $shopperId;


    public $modelErrors = array();
    /* - ----- - - - - -- - - - - - - -*/

    //response
    public $orderId;
    public $account;
    public $currency;
    public $amount;
    public $resultCode;
    public $resultMessage = '';

    public $originalDomain;
    public $redirectedDomain;


    // return
    public $ref;
    public $code;
    /* - ----- - - - - -- - - - - - - -*/

    private $currencies = array('USD'=>'USD', 'AED'=>'AED');
    private $aedRate = 3.72;
    private $hex2bin = '000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f';


    public function rules() {
        return array(
            array('value, currencyCode, merchantOrderReference, emailAddress, redirectUrl', 'required', 'on'=>'deposit', 'message'=> Yii::t("main","36_cannot_be_blank")),
            //array('firstName, lastName, phone, email, country, city', 'safe', 'on'=>'deposit', 'message'=> Yii::t("main","36_cannot_be_blank")),

           // array('ref', 'required', 'on'=>'return', 'message'=> Yii::t("main","36_cannot_be_blank")),
            array('orderId, account, currency, amount, resultCode, resultMessage', 'required', 'on'=>'response', 'message'=> Yii::t("main","36_cannot_be_blank")),

            array('code, ref', 'safe', 'on'=>'response, return'),
        );
    }

    public function init()
    {

        //$this->outletRef = '3b8320b0-7677-4b5b-80fe-a1abd8000f8a'; //test
        $this->outletRef = Yii::app()->params['network_outletRef']; //'a5876a12-1f49-49d5-a88f-d37b030b19cb'; //live
        //$this->apikey = 'YmY1MzljYTAtM2Q0MS00NTEyLWJmZTgtZmMwY2Y5MGExNGE0OjhiY2FmOTczLTYzNGYtNDI1ZC04M2FjLTA0NzQzMjJlNDM2Yg=='; //test
        $this->apikey = Yii::app()->params['network_apikey']; //'OWRkNTczMjQtYTY0NS00NWZiLTllY2EtYzRjNDZjNTk0OGNkOjg2MjhmMmUxLWQ4YmItNDBiYy1hMDQ0LTE4OTA2ZGJkOTc4NQ=='; //live

        //$this->idServiceURL = 'https://identity-uat.ngenius-payments.com/auth/realms/ni/protocol/openid-connect/token'; //test
        $this->idServiceURL = Yii::app()->params['network_idServiceURL']; //'https://identity.ngenius-payments.com/auth/realms/NetworkInternational/protocol/openid-connect/token'; //live
        // $this->txnServiceURL = 'https://api-gateway-uat.ngenius-payments.com/transactions/outlets/'.$this->outletRef.'/orders';  //test
        $this->txnServiceURL = Yii::app()->params['network_txnServiceURL'].$this->outletRef.'/orders';  //live

        /*$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->outletRef, $this->apikey);die();
        }*/

        $this->contentType = 'urlencoded';

        /*$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', $this->apikey,  $this->outletRef);die();

        }*/

        /*$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->outletRef, $this->apikey, $this->idServiceURL, $this->txnServiceURL);die();
        }*/



        $ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if(in_array(wlParams::get('officeCode'), [60]) ){
            $this->redirectedDomain = 'https://deposit.swiss-global.info';
            $this->originalDomain = 'https://my.swisscapital.me';
            $this->trType = 6;
            $this->redirectUrlDomain = 'https://pay.swiss-global.info';
            $this->redirectUrl = $this->redirectUrlDomain.'/payment/userPaymentRedirect?type='.$this->type.'&code='.wlParams::get('officeCode');
        }elseif(in_array(wlParams::get('officeCode'), [72]) ){
            $this->redirectedDomain = 'https://payments.tradeduinvestment.com';
            //$this->redirectedDomain = 'https://pay.tradeduinvestment.com';
            $this->originalDomain = 'https://my.tradedu.com';
            $this->trType = 6;
            $this->redirectUrlDomain = 'https://pay.tradeduinvestment.com';
            $this->redirectUrl = $this->redirectUrlDomain.'/payment/userPaymentRedirect?type='.$this->type.'&code='.wlParams::get('officeCode');
        }elseif(in_array(wlParams::get('officeCode'), [77]) ){
            $this->redirectedDomain = 'https://payments.efxcpi.ae';
            $this->originalDomain = 'https://private.efxcpi.com';
            $this->trType = 6;
            $this->redirectUrlDomain = 'https://pay.efxcpi.ae';
            $this->redirectUrl = $this->redirectUrlDomain.'/payment/userPaymentRedirect?type='.$this->type.'&code='.wlParams::get('officeCode');
        }elseif(in_array(wlParams::get('officeCode'), [78]) ){
            $this->redirectedDomain = 'https://payments.efxcpi.ae';
            $this->originalDomain = 'https://my.efxcpi.com';
            $this->trType = 6;
            $this->redirectUrlDomain = 'https://pay.efxcpi.ae';
            $this->redirectUrl = $this->redirectUrlDomain.'/payment/userPaymentRedirect?type='.$this->type.'&code='.wlParams::get('officeCode');
        }elseif(in_array(wlParams::get('officeCode'), [28]) ){
            $this->redirectedDomain = 'https://payments2.efxcpi.ae';
            $this->originalDomain = 'https://my.eforex.com';
            $this->trType = 6;
            $this->redirectUrlDomain = 'https://pay2.efxcpi.ae';
            $this->redirectUrl = $this->redirectUrlDomain.'/payment/userPaymentRedirect?type='.$this->type.'&code='.wlParams::get('officeCode');
        }elseif(in_array(wlParams::get('officeCode'), [80]) ){
            $this->redirectedDomain = 'https://pay1.platinumriskcontrol.com';
            $this->originalDomain = 'https://my.platinum-fx.com';
            $this->trType = 38;
            $this->redirectUrlDomain = 'https://pay.platinumriskcontrol.com';
            $this->redirectUrl = $this->redirectUrlDomain.'/payment/userPaymentRedirect?type='.$this->type.'&code='.wlParams::get('officeCode');
        }elseif(in_array(wlParams::get('officeCode'), [83]) ) {
            $this->redirectedDomain = 'https://deposit.swiss-global.info';
            $this->originalDomain = 'https://my.swiss-capital.ae';
            $this->trType = 6;
            $this->redirectUrlDomain = 'https://pay1.swiss-global.info';
            $this->redirectUrl = $this->redirectUrlDomain.'/payment/userPaymentRedirect?type=' . $this->type . '&code=' . wlParams::get('officeCode');
        }elseif(in_array(wlParams::get('officeCode'), [69]) ){
            $this->redirectedDomain = 'https://deposit.swiss-global.info';
            $this->originalDomain = 'https://my.simarkets.me';
            $this->trType = 6;
            $this->redirectUrlDomain = 'https://pay3.swiss-global.info';
            $this->redirectUrl = $this->redirectUrlDomain.'/payment/userPaymentRedirect?type='.$this->type.'&code='.wlParams::get('officeCode');
        }elseif(in_array(wlParams::get('officeCode'), [65]) ){
            $this->redirectedDomain = 'https://deposit.swiss-global.info';
            $this->originalDomain = 'https://my.simarkets.com';
            $this->trType = 6;
            $this->redirectUrlDomain = 'https://pay2.swiss-global.info';
            $this->redirectUrl = $this->redirectUrlDomain.'/payment/userPaymentRedirect?type='.$this->type.'&code='.wlParams::get('officeCode');
        }else{
            $http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';
            $this->redirectedDomain = 'https://payments.bmfnconsulting.com';
            $this->originalDomain = $http.'//'.$_SERVER["SERVER_NAME"];
            $this->trType = 30;
            $this->redirectUrlDomain = 'https://pay.bmfnconsulting.com';
            $this->redirectUrl = $this->redirectUrlDomain.'/payment/userPaymentRedirect?type='.$this->type.'&code='.wlParams::get('officeCode');
            //$this->redirectedDomain = 'https://my.bmfn.com';
        }
    }

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

    public function attributeLabels(){
        return array(
            // 'description' => Yii::t("main",'157_account'),
            'value' => Yii::t("funds",'9_amount'),
            'currencyCode' => Yii::t("funds",'450_currency'),
        );
    }

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

        $Registration = new Registration('Individual');
        $countries_code_three = $Registration->GetCountry('three');
        $Registration->initIndv();

        $http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';
        $data2['data']['merchantOrderReference'] = $this->merchantOrderReference = uniqid();

        $data2['data']['amount'] = $data2['data']['real_amount'] = $this->value = (float)$data['amount'];
        $data2['data']['currency'] = $data2['data']['real_currency'] = $this->currencyCode = $data['currency'];


        if(wlParams::get('officeCode') === 72 || wlParams::get('officeCode') === 19 ){
            if($data['currency'] === 'USD'){
                $this->value = round(((float)$this->value * $this->aedRate), 2);
                $this->currencyCode = 'AED';
            }
        }else{
            if($data['currency'] !== 'AED'){
                /*$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(stFunctions::currConv("USD", "AED", 51));die();
                    //var_dump($this->currencyCode, 'AED', $this->value);die();
                }*/
                $this->value = round(stFunctions::currConv($this->currencyCode, 'AED', $this->value), 2);
                $this->currencyCode = 'AED';
            }
        }

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

        $this->originalDomain = $http.'//'.$_SERVER["SERVER_NAME"];


        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            //$key = hex2bin($this->hex2bin);

            $encrypted = SaferCrypto::encrypt(time(), hex2bin($this->hex2bin), true);
            $decrypted = SaferCrypto::decrypt($encrypted, hex2bin($this->hex2bin), true);

            // 60*5

            var_dump($encrypted, $decrypted);

            var_dump(time());die();
        }*/

        $data3["message"] = Yii::t("funds","446_you_will_redir_secure_payment");
        $data3['type'] = $this->type;
        $data3['action'] = $this->redirectUrlDomain.'/'.$this->type;
        $ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        $data3['data'] = [
            'link' => '',
            'real_amount'=>(float)$data['amount'],
            'real_currency'=>$data['currency'],
            'merchantOrderReference' => $this->merchantOrderReference,
            'ref' => 'cab',
            //'code' => wlParams::get('officeCode'),
            //'pi' => md5($ip+$this->outletRef),
            'TransactionKey' => $this->merchantOrderReference,
            'value' => $this->value,
            'currencyCode' => $this->currencyCode,
            'account' => $this->shopperId,
            'firstName' => $Registration->firstName,
            'lastName' => $Registration->lastName,
            'address' => $Registration->address,
            'city' => $Registration->city,
            'country' => $countries_code_three[$Registration->country],
            'emailAddress' => stFunctions::randomizeEmail($Registration->email),
            'redirectUrl' => $this->redirectUrl. '&pi=' . SaferCrypto::encrypt(time(), hex2bin($this->hex2bin), true),
        ];

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

        return $data3;

        /* OLD FLow */
        /*if($this->contentType == 'urlencoded'){
            $tokenHeaders  = array("Authorization: Basic ".$this->apikey, "Content-Type: application/x-www-form-urlencoded");
            $post_data = http_build_query(array('grant_type' => 'client_credentials'));
        }else{
            $tokenHeaders  = array(
                "accept: application/vnd.ni-identity.v1+json",
                "authorization: Basic ".$this->apikey,
                "content-type: application/vnd.ni-identity.v1+json"
            );
            $post_data = json_encode(array('realmName' => 'ni'));
        }

        $tokenResponse = json_decode($this->invokeCurlRequest("POST", $this->idServiceURL, $tokenHeaders, $post_data));

        if(isset($tokenResponse->access_token)){
            $access_token = $tokenResponse->access_token;

            $order = new StdClass();

            $order->action = $this->mode;                                        // Transaction mode ("AUTH" = authorize only, no automatic settle/capture, "SALE" = authorize + automatic settle/capture)
            $order->amount = new StdClass();
            $order->amount->currencyCode = $this->currencyCode;                           // Payment currency ('AED' only for now)
            $order->amount->value = (float)$this->value*100;                                   // Minor units (1000 = 10.00 AED)
            $order->language = "en";                                        // Payment page language ('en' or 'ar' only)
            $order->emailAddress = stFunctions::randomizeEmail($Registration->email);                                        // Payment page language ('en' or 'ar' only)
            $order->merchantDefinedData = new StdClass();
            //$order->merchantDefinedData[] = new StdClass();
            $order->merchantDefinedData->orderId = $order->merchantOrderReference = $this->merchantOrderReference;
            $order->merchantDefinedData->shopperId = $this->shopperId;
            $order->merchantDefinedData->account = $data2['data']['account'] = (int)$data['transferTo'];
            $order->merchantDefinedData->currency = $data2['data']['currency'];
            $order->merchantDefinedData->amount = $data2['data']['amount'];
            $order->merchantAttributes = new StdClass();
            $order->merchantAttributes->redirectUrl = $this->redirectUrl;     // A redirect URL to a page on your site to return the customer to
            $order->merchantAttributes->skipConfirmationPage = true;          // A redirect URL to a page on your site to return the customer to

            $order->billingAddress = new StdClass();
            $order->billingAddress->firstName = $Registration->firstName;
            $order->billingAddress->lastName = $Registration->lastName;
            $order->billingAddress->address1 = $Registration->address;
            $order->billingAddress->city = $Registration->city;
            $order->billingAddress->countryCode = $countries_code_three[$Registration->country];

            $orderTMP =  $order;
            $order = json_encode($order);


            $orderCreateHeaders  = array("Authorization: Bearer ".$access_token, "Content-Type: application/vnd.ni-payment.v2+json", "Accept: application/vnd.ni-payment.v2+json");
            $orderCreateResponse = $this->invokeCurlRequest("POST", $this->txnServiceURL, $orderCreateHeaders, $order);

            if(!isset($orderCreateResponse->reference)){
                $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/network.txt',"a");
                fwrite($f, Yii::app()->params['type'] .' '.date('Y-m-d H:i:s').' orderCreateResponse order:'.$this->merchantOrderReference.' '.$orderCreateResponse.'<br/>\n
                ');
            }
            $orderCreateResponse = json_decode($orderCreateResponse);

            if(isset($orderCreateResponse->_links->payment->href)){
                $data2['data']['link'] = $paymentLink = $orderCreateResponse->_links->payment->href;     // the link to the payment page for redirection (either full-page redirect or iframe)
                $orderReference      = $orderCreateResponse->reference;              // the reference to the order, which you should store in your records for future interaction with this order
            }else{
                $data2['data']['link'] = '';
                if(isset($orderCreateResponse->errors[0]->message)){
                    $_SESSION['message'][] = array("text" => $orderCreateResponse->errors[0]->message, "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                }
            }

        }elseif(isset($tokenResponse->error_description)){
            $_SESSION['message'][] = array("text" => $tokenResponse->error_description, "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
        }else{
            $_SESSION['message'][] = array("text" => 'Check Network Config', "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
        }




        $data2['action'] = $this->redirectedDomain.'/payment/paymentRedirect';

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

        return $data2;*/
    }

    public function getSecret()
    {
        return $this->secret;
    }

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



        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/network.txt',"a");
        fwrite($f, Yii::app()->params['type'] .' '.date('Y-m-d H:i:s').' newNetworkTransaction  '.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).' - '.get_browser()->browser_name_pattern.'<br/>\n
		');

        return  $Info;
    }

    public function ApplyTransaction(){
        $statuses = array('00'=>'0');

        if($this->trType == 6){
            $Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/ApplyNeoTransaction?errorcode='.(isset($statuses[$this->resultCode]) ? $statuses[$this->resultCode] : '-6000').'&errormessage='.$this->resultMessage.'&transactionid='.$this->orderId);

            $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/network.txt',"a");
            fwrite($f, Yii::app()->params['type'] .' '.date('Y-m-d H:i:s').' '.Yii::app()->params['json_server'].'/API/Transactions/ApplyNeoTransaction?errorcode='.(isset($statuses[$this->resultCode]) ? $statuses[$this->resultCode] : '-6000').'&errormessage='.$this->resultMessage.'&transactionid='.$this->orderId.' ----> '.json_encode($Info).'<br/>\n
            ');

        }else{
            $Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/ApplyNetworkGlobalTransaction?errorcode='.($this->resultCode == '00' ? 'APPROVED' : 'ERROR').'&transactionid='.$this->orderId.'&depValue=0&currency=');
            //var_dump(Yii::app()->params['json_server'].'/API/Transactions/ApplyCCAvenueTransaction?errorcode='.($this->status == 'CAPTURED' ? 'APPROVED' : 'ERROR').'&transactionid='.$this->transaction.'&depValue=0&currency=');die();

            $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/network.txt',"a");
            fwrite($f, Yii::app()->params['type'] .' '.date('Y-m-d H:i:s').' ApplyNetworkGlobalTransaction   '.Yii::app()->params['json_server'].'/API/Transactions/ApplyNetworkGlobalTransaction?errorcode='.($this->resultCode == '00' ? 'APPROVED' : 'ERROR').'&transactionid='.$this->orderId.'&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'];

        }
    }

    private function invokeCurlRequest($type, $url, $headers, $post) {

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ($type == "POST") {

            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

        }

        $server_output = curl_exec ($ch);
        curl_close ($ch);

        return $server_output;

    }

    private function getAccessToken(){

        if($this->contentType == 'urlencoded'){
            $tokenHeaders    = array("Authorization: Basic ".$this->apikey, "Content-Type: application/x-www-form-urlencoded");
            $tokenResponse   = $this->invokeCurlRequest("POST", $this->idServiceURL, $tokenHeaders, http_build_query(array('grant_type' => 'client_credentials')));
            /* $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($tokenResponse, $this->apikey);die();
             }*/
        }else{
            $tokenHeaders  = array(
                "accept: application/vnd.ni-identity.v1+json",
                "authorization: Basic ".$this->apikey,
                "content-type: application/vnd.ni-identity.v1+json"
            );
            $tokenResponse   = $this->invokeCurlRequest("POST", $this->idServiceURL, $tokenHeaders, json_encode(array('realmName' => 'ni')));
        }
        $tokenResponse   = json_decode($tokenResponse);

        /* $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->apikey, $this->idServiceURL, $tokenHeaders, in_array(wlParams::get('officeCode'), [60]), $tokenResponse);die();
         }*/

        return $tokenResponse->access_token;
    }

    private function getOrderResponse($access_token){
        $residServiceURL = $this->txnServiceURL.'/'.$this->ref;

        if($this->contentType == 'urlencoded'){
            $responseHeaders  = array("Authorization: Bearer ".$access_token, "Content-Type: application/vnd.ni-payment.v2+json", "Accept: application/vnd.ni-payment.v2+json");
            $orderResponse 	  = $this->invokeCurlRequest("GET", $residServiceURL, $responseHeaders, '');
        }else{
            $responseHeaders  = array(
                "accept: application/vnd.ni-identity.v1+json",
                "authorization: Basic ".$access_token,
                "content-type: application/vnd.ni-identity.v1+json"
            );
            $orderResponse 	  = $this->invokeCurlRequest("GET", $residServiceURL, $responseHeaders, '');
        }

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


        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/network.txt',"a");
        fwrite($f, Yii::app()->params['type'] .' '.date('Y-m-d H:i:s').' getOrderResponse  '.$orderResponse.'<br/>\n
		');

        /*$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('22222222', $orderResponse);die();
        }*/

        return json_decode($orderResponse, true);
    }

    public function confirmOnReturn() {
        $access_token = $this->getAccessToken();
        $order = $this->getOrderResponse($access_token);

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

        $this->setScenario('response');




        if(isset($order['_embedded']['payment'][0]['authResponse'])){
            $this->attributes = $order['_embedded']['payment'][0]['authResponse'];
            $this->resultMessage = (isset($order['_embedded']['payment'][0]['authResponse']['resultMessage']) && !$order['_embedded']['payment'][0]['authResponse']['success']) ? $order['_embedded']['payment'][0]['authResponse']['resultMessage'] : 'Success';
        }else{
            $this->resultCode = '-6000';
            $this->resultMessage = isset($order['message']) ? $order['message'] : 'Payment Provider Error';

            if(isset($order['_embedded']['payment'][0])){
                $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/network.txt',"a");
                fwrite($f, Yii::app()->params['type'] .' '.date('Y-m-d H:i:s').' errorResponse '.json_encode($order['_embedded']['payment'][0]).'<br/>\n
                ');
            }
        }

        if(isset($order['merchantDefinedData'])){
            $this->attributes = $order['merchantDefinedData'];
            $this->amount = $this->amount/100;
        }

        if($this->validate()){
            $res = $this->ApplyTransaction();
            if(isset($res->State) && $res->State == 1 && isset($res->Message)){
                $this->modelErrors[] = $res->Message;
            }else{
                return true;
            }
        }else{
            $this->modelErrors = array_merge($this->modelErrors, $this->getErrors());
        }

        return false;
    }

    public function isSuccess(){
        return $this->resultCode == '00';
    }

    public function getRedirectLink()
    {
        $officeCodes = [
            60 => 'https://my.swisscapital.me',
            72 => 'https://my.tradedu.com',
            32 => 'https://my.bmfn-solutions.com',
            19 => 'https://my.bmfn.ae'
        ];
        /*if(in_array(wlParams::get('officeCode'), [60]) ){
            $this->originalDomain = 'https://my.swisscapital.ae';
        }*/

        $this->originalDomain = isset($officeCodes[$this->code]) ? $officeCodes[$this->code] : $this->originalDomain;

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

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



}
