<?php
class CCAvenue extends CFormModel
{
	public $type = 'ccavenue';
	private $trType = 31;

    public $action;

    private $working_key;
    private $access_code;
    private $merchant_id;

    public $order_id;
    public $currency;
    public $amount;
    public $redirect_url;
    public $cancel_url;

    public $billing_name;
    public $billing_address;
    public $billing_city;
    public $billing_country;
    public $billing_tel;
    public $billing_email;

    public $merchant_param1;
    public $merchant_param2;

	//response
    public $status;

    // return
    public $encResp;
    public $orderNo;

    // returnData
    public $order_status;
    public $status_message;

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

    private $codeTypes = [65 => 33, 69 => 31, 70 => 34, 80 => 37];

	public function rules() {
		return array(
            array('order_id, currency, amount, redirect_url, cancel_url, billing_email, billing_name, billing_address, billing_city, billing_country, billing_tel, merchant_param1', '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://secure.ccavenue.ae/transaction/transaction.do?command=initiateTransaction';

        $this->action = Yii::app()->params['ccavenue_action'];

//        $this->working_key = '619F4A8B8FD70A5BE4861F3B4B758690';
//        $this->access_code = 'AVRU03IB71BV51URVB';
//        $this->merchant_id = '45990';

        if(in_array(wlParams::get('officeCode'), array_keys($this->codeTypes))){
            $this->trType = $this->codeTypes[wlParams::get('officeCode')];
        }


        $this->working_key = Yii::app()->params['ccavenue_working_key'];
        $this->access_code = Yii::app()->params['ccavenue_access_code'];
        $this->merchant_id = Yii::app()->params['ccavenue_merchant_id'];
	}


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

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

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

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

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

        $params = [];
        //$params['merchant_id'] = $this->merchant_id;
        $params['order_id'] = $this->order_id = $data2['data']['order_id'] = uniqid();
        $params['currency'] = $this->currency = $data2['data']['currency'] = $data2['data']['real_currency'] = $data['currency'];
        $params['amount'] = $this->amount = $data2['data']['amount'] = $data2['data']['real_amount'] = (int)$data['amount'];
        $params['redirect_url'] = $this->redirect_url = Yii::app()->params['ccavenue_alt_redirect_url'];
        $params['cancel_url'] = $this->cancel_url = Yii::app()->params['ccavenue_alt_redirect_url'];

        // 'https://payments.swiss-global.info/payment/return/ccavenue';



        $params['billing_name'] = $this->billing_name = $Registration->firstName.' '.$Registration->lastName;
        $params['billing_address'] = $this->billing_address = $Registration->address;
        $params['billing_city'] = $this->billing_city = $Registration->city;
        $params['billing_country'] = $this->billing_country = $Registration->country;
        $params['billing_tel'] = $this->billing_tel = stFunctions::randomizePhone(str_replace('+', '', $Registration->phone));

        $params['billing_email'] = $this->billing_email = stFunctions::randomizeEmail($Registration->email);
        $params['merchant_param1'] = $this->merchant_param1 = $data2['data']['account'] = (int)$data["transferTo"];
        $params['merchant_param2'] = $this->merchant_param2 = wlParams::get('officeCode'); // spost value


        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '46.211.108.157') {
            var_dump($params['billing_email'], $params['billing_tel']);
            $params['billing_email'] = stFunctions::randomizeEmail($params['billing_email']);
            $params['billing_tel'] = stFunctions::randomizePhone($params['billing_tel']);
           var_dump($params['billing_email'], $params['billing_tel']);die();
        }*/

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

        $data2['data']['merchant_data'] = '';
        foreach ($params as $key => $value){
            $data2['data']['merchant_data'] .= $key.'='.$value.'&';
        }

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

        $data2['data']['spost'] = wlParams::get('officeCode');

        //$data2['data']["link"] = '';
        $data2["action"] = $this->action;

        $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'];
        }
        //$this->attributes = $data;

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

    public function initRequest($data)
    {

        $res = $this->getRequest();

        $this->setScenario('return2');

        $this->attributes = $res;
    }

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

        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/ccavenue.txt',"a");
        fwrite($f, date('Y-m-d H:i:s').' parsed '.$_SERVER['REMOTE_ADDR'].' '.date('Y-m-d H:i:s').' '.json_encode($response).'
                ');

        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 = ''){
        $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/ccavenue.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/ApplyCCAvenueTransaction?errorcode='.($this->order_status == 'Success' ? 'APPROVED' : 'ERROR').'&transactionid='.$this->order_id.'&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/ccavenue.txt',"a");
        fwrite($f, date('Y-m-d H:i:s').' ApplyCCAvenueTransaction  '.$this->type .' '.Yii::app()->params['json_server'].'/API/Transactions/ApplyCCAvenueTransaction?errorcode='.($this->order_status == 'Success' ? '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->order_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;
        }
    }

    function encrypt($plainText,$key)
    {
        $key = $this->hextobin(md5($key));
        $initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
        $openMode = openssl_encrypt($plainText, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $initVector);
        $encryptedText = bin2hex($openMode);
        return $encryptedText;
    }

    function decrypt($encryptedText,$key)
    {
        $key = $this->hextobin(md5($key));
        $initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
        $encryptedText = $this->hextobin($encryptedText);
        $decryptedText = openssl_decrypt($encryptedText, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $initVector);
        return $decryptedText;
    }
    //*********** Padding Function *********************

    function pkcs5_pad ($plainText, $blockSize)
    {
        $pad = $blockSize - (strlen($plainText) % $blockSize);
        return $plainText . str_repeat(chr($pad), $pad);
    }

    //********** Hexadecimal to Binary function for php 4.0 version ********

    function hextobin($hexString)
    {
        $length = strlen($hexString);
        $binString="";
        $count=0;
        while($count<$length)
        {
            $subString =substr($hexString,$count,2);
            $packedString = pack("H*",$subString);
            if ($count==0)
            {
                $binString=$packedString;
            }

            else
            {
                $binString.=$packedString;
            }

            $count+=2;
        }
        return $binString;
    }

}
