<?php
class Nowpay extends CFormModel
{
	public $type = 'nowpay';
	private $trType = 32;

    public $action;

    public $account;
    public $amount;
    public $currency;

    public $pay_address;
    public $payment_status;
    public $payment_id;

    public $ipn_callback_url;
    public $order_id;
    public $api_key;
    public $secret_key;


    private $currencies = array('USDT'=>'USDT'); // USDTTRC20

    private $shortCurrencies = ['USDT'=>'USDTTRC20'];

	public function rules(){
		return array(
            array('account, amount, currency', '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('encResp, orderNo', 'required', 'on'=>'return', 'message'=> Yii::t("main","36_cannot_be_blank")),
            //array('amount, currency, merchant_param1, order_id, order_status', 'required', 'on'=>'return2', 'message'=> Yii::t("main","36_cannot_be_blank")),
            //array('status_message', 'safe', 'on'=>'return2', 'message'=> Yii::t("main","36_cannot_be_blank")),
		);
	}
	
	public function init()
	{
        /*$this->action = 'https://api.sandbox.nowpayments.io/v1';
        $this->api_key = 'AP479ZC-RS14T05-KEC26NJ-PMRFYRD';
        $this->secret_key = 'DNkVHHCDp8lfNybqz20wwB61uuMmORLY';*/

        //var_dump(Yii::app()->params);die();


        $this->action = Yii::app()->params['nowpay_action'];
        $this->api_key = Yii::app()->params['nowpay_api_key'];
        $this->secret_key = Yii::app()->params['nowpay_secret_key'];


        /*$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->action, $this->api_key, $this->secret_key, Yii::app()->params['nowpay_action']);die();
        }*/


        /*$this->action = 'https://api.nowpayments.io/v1';
        $this->api_key = '1Z2WDBX-3QS4A6V-MCX7S9C-38AQZHQ';
        $this->secret_key = 'V9SBiSodeM6nyH1D2ynzXDO7nnAayTC6';*/


	}


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

    public function attributeLabels(){
        return array(
            'account' => Yii::t("main",'157_account'),
            'amount' => Yii::t("funds",'9_amount'),
            'currency' => Yii::t("funds",'450_currency'),
        );
    }

    public function initData($data)
    {
        $data2 = $params = array();
        $http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';
        $this->ipn_callback_url = $http.'//'.$_SERVER["SERVER_NAME"].'/returnTrans?type='.$this->type;


       /* $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->shortCurrencies, $data['currency']);die();
        }*/
        $this->amount = $data2["data"]['amount'] = $data['amount'];
        $this->currency = $this->shortCurrencies[$data['currency']];
        $data2["data"]['account'] = $this->account = (int)$data['transferTo'];

        $data2["data"]['order_id'] = $this->order_id = uniqid();

        $this->makePayment();

        $data2["data"]['pay_address'] = $this->pay_address;
        $data2["data"]['payment_id'] = $this->payment_id;
        $data2["data"]['payment_status'] = $this->payment_status;


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


        return $data2;
    }

    public function makePayment()
    {
        $url = $this->action.'/payment';

        $data = [
            'price_amount'=> $this->amount,
            'price_currency'=> $this->currency,
            'pay_currency' => 'usdttrc20',
            'ipn_callback_url' => $this->ipn_callback_url,
            'order_id' => $this->order_id,
            'order_description' => $this->account,

            'case'=>'success'
        ];

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

        $curl = curl_init($url);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS,  json_encode($data));

        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            'x-api-key: '.$this->api_key,   // Replace with your API Key
            'Content-Type: application/json'
        ]);

        $response = curl_exec($curl);
        curl_close($curl);

        $jsonObj = json_decode($response . PHP_EOL,true);

       /* $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($jsonObj, $url, $data, $this->api_key);die();
        }*/


        if(isset($jsonObj['pay_address'])){
            $this->pay_address = $jsonObj['pay_address'];
        }
        if(isset($jsonObj['payment_id'])){
            $this->payment_id = $jsonObj['payment_id'];
        }
        if(isset($jsonObj['payment_status'])){
            $this->payment_status = $jsonObj['payment_status'];
        }

    }

    public function checkStatus($payment_id)
    {
        //session_start();

        $url = $this->action.'/payment';



        $curl = curl_init($url.'/'.$payment_id);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            'x-api-key: '.$this->api_key  // Replace with your API Key

        ]);

        $response = curl_exec($curl);
        curl_close($curl);


        $jsonObj = json_decode($response . PHP_EOL,true);

        if(isset($jsonObj['payment_status'])){
            $this->payment_status = $jsonObj['payment_status'];
            //$this->payment_status = 'finished';

            if($this->payment_status == 'finished'){
                $res = $this->ApplyTransaction();
            }
        }

        /*$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($jsonObj, $url.'/'.$payment_id, $this->api_key);die();
        }*/
    }

    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($this->isSuccess()){
            $res = $this->ApplyTransaction();
        }
    }

    public function initRequest($data)
    {

        $res = $this->getRequest();


        $this->setScenario('return2');

        $this->attributes = $res;

        /*$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('33333333333', $this->attributes, $res);die();
        }*/

       /* if(isset($res['status'])){
            $this->status = $res['status'];
        }
        if(isset($res['description'])){
            $this->description = $res['description'];
        }
        if(isset($res['transaction'])){
            $this->attributes = $res['transaction'];
        }*/

    }

    function getRequest(){

        $rcvdString=$this->decrypt($this->encResp,$this->working_key);
        $decryptValues=explode('&', $rcvdString);
        $dataSize=sizeof($decryptValues);

        $response = [];
        for($i = 0; $i < $dataSize; $i++)
        {
            $info = explode('=',$decryptValues[$i]);
            $response[$info[0]] = $info[1];
        }

        return $response;
    }

    public function confirmOnReturn()
    {
        $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'])){

            $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 = ''){

        $this->order_id = $transactionID;

        $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/nowpay.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/ApplyCryptoTransferTransaction?errorcode='.($this->payment_status == 'finished' ? 'APPROVED' : 'ERROR').'&transactionid='.$this->order_id.'&depValue=0&currency=');
	    //var_dump(Yii::app()->params['json_server'].'/API/Transactions/ApplyCryptoTransferTransaction?errorcode='.($this->status == 'CAPTURED' ? 'APPROVED' : 'ERROR').'&transactionid='.$this->transaction.'&depValue=0&currency=');die();

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

        }*/
    }

    public function isSuccess()
    {
        return $this->payment_status  === 'Success';
    }

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



}
