 <?php
class ZotaPay extends CFormModel
{
	public $type = 'zotapay';
	public $endpointId  = 5595;
	public $action;
	private $merchantControl;
	private $login;
	
	public $merchantOrderID;
	public $merchantOrderDesc;
	public $card_printed_name;
	public $customerFirstName;
	public $customerLastName;
	//public $ssn;
	public $birthday;
	public $customerAddress;
	public $customerCity;
	public $customerState = 'ACT';
	public $customerZipCode = '98102';
	public $customerCountryCode;
	public $customerPhone;
	public $customerEmail;
	public $orderAmount;
	public $orderCurrency;
	public $credit_card_number;
	public $expire_month;
	public $expire_year;
	public $cvv2;
	public $customerIP;
	//public $destination-card-no;
	public $customParam;
	public $signature;
	public $redirectUrl;
	public $callbackUrl;
	public $checkoutUrl;
	public $merchant_data;
	
	private $currencies = array('USD', 'VND' /*, 'EUR','THB','VND','MYR','IDR','PHP'  ,'CNY'*/);
    private $endpoints = array('USD' => 402720, 'VND' => 402716 /* 'MYR' => 402717  5595, 'EUR' => 5596, 'CNY' => 5571*/);
    //private $endpoints = array('USD' => 503316, 'EUR' => 503317, 'THB' => 402715, , 'MYR' => 402717, 'IDR' => 402718, 'PHP' => 402719,);

	public function rules(){
		
		return array(
			//deposit
			array('merchantOrderID, merchantOrderDesc, card_printed_name, customerFirstName, customerLastName, birthday, customerAddress, customerCity, customerZipCode, customerCountryCode, customerPhone, customerEmail, amount, orderCurrency, credit_card_number, expire_month, expire_year, cvv2, customerIP, signature, redirectUrl, callbackUrl, customParam', 'required', 'message'=> Yii::t("main","36_cannot_be_blank"), 'on'=>'deposit'),
			array('merchantOrderID, card_printed_name, customParam, redirectUrl, callbackUrl, checkoutUrl', 'length', 'max'=>128, 'tooLong'=>Yii::t("main","529_max_length_is"), 'on'=>'deposit'),
			array('merchantOrderDesc', 'length', 'max'=>64, 'tooLong'=>Yii::t("main","529_max_length_is"), 'on'=>'deposit'),
			array('customerFirstName, customerLastName, customerAddress, customerCity, customerEmail, merchant_data', 'length', 'max'=>50, 'tooLong'=>Yii::t("main","529_max_length_is"), 'on'=>'deposit'),
			array('expire_year, cvv2', 'length', 'max'=>4, 'tooLong'=>Yii::t("main","529_max_length_is"), 'on'=>'deposit'),
			array('birthday', 'length', 'max'=>8, 'tooLong'=>Yii::t("main","529_max_length_is"), 'on'=>'deposit'),
			array('customerState, orderCurrency', 'length', 'max'=>3, 'tooLong'=>Yii::t("main","529_max_length_is"), 'on'=>'deposit'),
			array('customerZipCode, orderAmount', 'length', 'max'=>10, 'tooLong'=>Yii::t("main","529_max_length_is"), 'on'=>'deposit'),
			array('customerCountryCode, expire_month', 'length', 'max'=>2, 'tooLong'=>Yii::t("main","529_max_length_is"), 'on'=>'deposit'),
			array('customerPhone', 'length', 'max'=>15, 'tooLong'=>Yii::t("main","529_max_length_is"), 'on'=>'deposit'),
			array('credit_card_number, customerIP', 'length', 'max'=>20, 'tooLong'=>Yii::t("main","529_max_length_is"), 'on'=>'deposit'),
			array('signature', 'length', 'max'=>40, 'tooLong'=>Yii::t("main","529_max_length_is"), 'on'=>'deposit'),
			
			array('credit_card_number, expire_month, expire_year, cvv2', 'numerical', 'integerOnly'=>true, 'allowEmpty' => false, 'message'=>Yii::t("funds","530_numbers_allowed"), 'tooSmall'=>Yii::t("funds","79_amount_cant_be_null"), 'on'=>'deposit'),
			array('orderAmount', 'numerical', 'integerOnly'=>false,'numberPattern'=>'/^\d*[\.]?\d{0,2}$/', 'allowEmpty' => false, 'message'=>Yii::t("funds","530_numbers_allowed"), 'tooSmall'=>Yii::t("funds","79_amount_cant_be_null"), 'on'=>'deposit'),
			array('customerEmail' , 'customerEmail', 'on'=>'deposit', 'message'=>Yii::t("main","22_this_customerEmail_address_is_not_a_valid")),
			
		);
	}
	
	public function init(){
	    if(Yii::app()->params['type'] === 'efx'){
            $this->currencies = ['VND'];
        }

	    if($this->getScenario() == 'withdrawal') {
            $this->endpointId = 503316;
            $this->login = 'BMFN';
            $this->merchantControl = '21df5cba-65ea-4bf8-b139-ba0ce721f679';
        }else{
            $this->merchantControl = Yii::app()->params['zotapay_merchantControl'];
            $this->action = Yii::app()->params['zotapay_action'];
            $this->login = Yii::app()->params['zotapay_login'];

            $countryCode = Yii::app()->geoip->lookupCountryCode($_SERVER['REMOTE_ADDR']);

            if(in_array($countryCode, ['AR','BR','CO','CL','CR','EC','SV','MX','PA','PE'])){
                $this->endpoints['USD'] = 402720;
            }else{
                $this->endpoints['USD'] = 405720;
                $this->endpoints['EUR'] = 405734;
            }
        }
    }

	public function sendRequest($url, array $requestFields)
	{
		$curl = curl_init($url);

		curl_setopt_array($curl, array
		(
			CURLOPT_HEADER         => 0,
			CURLOPT_USERAGENT      => 'Zotapay-Client/1.0',
			CURLOPT_SSL_VERIFYHOST => 0,
			CURLOPT_SSL_VERIFYPEER => 0,
			CURLOPT_POST           => 1,
			CURLOPT_RETURNTRANSFER => 1
		));

		curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($requestFields));

		$response = curl_exec($curl);
        $err = curl_error($curl);


        $responseFields = json_decode($response, true);


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

		return $responseFields;
	}

	public function signString($s, $merchantControl)
	{
		return hash('sha256', $s . $merchantControl);
	}

	/**
	 * Signs payment (sale/auth/transfer) request
	 *
	 * @param 	array		$requestFields		request array
	 * @param	string		$endpointOrGroupId	endpoint or endpoint group ID
	 * @param	string		$merchantControl	merchant control key
	 */
	public function signPaymentRequest($requestFields, $endpointOrGroupId, $merchantControl)
	{
		$base = '';
		$base .= $endpointOrGroupId;
		$base .= $requestFields['merchantOrderID'];
		$base .= $requestFields['orderAmount'];
		$base .= $requestFields['customerEmail'];

		return $this->signString($base, $merchantControl);
	}

	/**
	 * Signs status request
	 *
	 * @param 	array		$requestFields		request array
	 * @param	string		$login				merchant login
	 * @param	string		$merchantControl	merchant control key
	 */
	public function signStatusRequest($requestFields, $login, $merchantControl)
	{
		$base = '';
		$base .= $login;
		$base .= $requestFields['merchantOrderID'];
		$base .= $requestFields['orderid'];

		return $this->signString($base, $merchantControl);
	}
	
	public function initSaleParams($data){
		$Registration = new Registration('Individual');
		$Registration->initIndv();
		$countries_code_three = $Registration->GetCountry('two');
		$http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';


        $numId = time();
		$params = [];
		$params['merchantOrderID'] = uniqid().'_'.Yii::app()->params['type'];
		$params['merchantOrderDesc'] = $this->merchantOrderDesc = $data['amount'].','.$data['currency'].','.$data['account'];
		$params['orderAmount'] = $this->orderAmount = number_format($data['amount'], 2, '.', '');
        $params['orderCurrency'] = $this->orderCurrency = $data['currency'];
		$params['customerEmail'] = $this->customerEmail = $Registration->email;
		$params['customerFirstName'] = $this->customerFirstName = $Registration->firstName;
		$params['customerLastName'] = $this->customerLastName = $Registration->lastName;
		$params['customerPhone'] = $this->customerPhone = $Registration->phone;
		$params['customerIP'] = $this->customerIP = $_SERVER['REMOTE_ADDR'];

		//$params['birthday'] = $this->birthday = date("Ymd", strtotime($Registration->birthday));
		$params['customerAddress'] = $this->customerAddress = $Registration->address;
		$params['customerCity'] = $this->customerCity = $Registration->city;
		$params['customerState'] = $this->customerState;
		$params['customerZipCode'] = $this->customerZipCode;
		$params['customerCountryCode'] = $this->customerCountryCode = $countries_code_three[$Registration->country];

        if(in_array(wlParams::get('officeCode'), [67]) ) {
            $server = 'https://my1.bmfnvt.com';
        }elseif(in_array(wlParams::get('officeCode'), [74]) ) {
            $server = 'https://my2.bmfnvt.com';
        }elseif(in_array(wlParams::get('officeCode'), [76]) ) {
            $server = 'https://my3.bmfnvt.com';
        }elseif(in_array(wlParams::get('officeCode'), [77]) ) {
            $server = 'https://my4.bmfnvt.com';
        }elseif(in_array(wlParams::get('officeCode'), [78]) ) {
            $server = 'https://my5.bmfnvt.com';
        }elseif(in_array(wlParams::get('officeCode'), [79]) ) {
            $server = 'https://my6.bmfnvt.com';
        }else{
            $server = 'https://my.bmfnvt.com';
        }

        $params['checkoutUrl'] = $this->checkoutUrl = $server.'/zotopayTrans/'.$numId;
        $params['redirectUrl'] = $this->redirectUrl = $server.'/payment/userPaymentRedirect?isUser&account='.$data['account'].'&amount='.$data['amount'].'&currency='.$data['currency'];
        $params['callbackUrl'] = $this->callbackUrl = $server.'/zotopayTrans/'.$numId;


        /*if ($_SERVER['REMOTE_ADDR'] == '46.98.64.234' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump($params['callbackUrl'], time());die();
        }*/


		$params['signature'] = $this->signature = $this->signPaymentRequest($params, $this->endpoints[$this->orderCurrency], $this->merchantControl);
		
		/* echo 'control:';
		var_dump($params['control']); */
		
		
		return $params;
	}
	
	
	
	public function sendSaleRequest($requestFields){
		$responseFields = $this->sendRequest($this->action.$this->endpoints[$this->orderCurrency], $requestFields);
		
		return $responseFields;
	}
	
	public function getAttribute($name){
		return $this->$name;
	}
	
	public function initStatusParams($data){
		
		
		$params = [
			'login' => $this->login, 
			'merchantOrderID' => trim($data['merchant-order-id']),
			'orderid' => trim($data['paynet-order-id']), 
			'by-request-sn' => trim($data['serial-number'])
		];
		
		//var_dump($params);
		
		$params['control'] = $this->signStatusRequest($params, $this->login, $this->merchantControl);
		
		return $params;
	}
	
	public function sendStatusRequest($requestFields){
		
		$responseFields = $this->sendRequest($this->action.'status/'.$this->endpoints[$this->orderCurrency], $requestFields);
		
		//var_dump($responseFields);die();

		/* echo 'sendStatusRequest';
		var_dump($this->action.'status/'.$this->endpointId, $requestFields, $responseFields);	
		echo '------------------'; */
		
		return $responseFields;
	}
	
	public function makeDeposit($data){
		/* $data = [
			'amount' => 50.00,
			'currency' => 'USD',
			'account' => '1003879',
			'ccFullNumber' => '4444444444444448',
			'cardholder_name' => 'Sergei Chenskyi',
			'exp_month' => '07',
			'exp_year' => '18',
			'cvc_code' => '321',
		]; */
		

		$return = [];


		$requestFields = $this->initSaleParams($data);


		$responseFields = $this->sendSaleRequest($requestFields);
       /* $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($responseFields);die();
        }*/

        /*if ($_SERVER['REMOTE_ADDR'] == '46.98.64.234' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {

        var_dump($data, $responseFields);die();
        }*/

		return $responseFields;

	}
	
	public function checkResult($data){

//		$string = $data['status'].$data['orderID'].$data['merchantOrderID'].$this->merchantControl;
		$string = $data['endpointID'].$data['orderID'].$data['merchantOrderID'].$data['status'].$data['amount'].$data['customerEmail'].$this->merchantControl;

		//var_dump($data['endpointID'].$data['orderID'].$data['merchantOrderID'].$data['status'].$data['amount'].$data['customerEmail'].$this->merchantControl);die();


        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/zotapayResponse.txt',"a");
        fwrite($f, date('Y-m-d H:i:s').' checkResult'.$data["signature"].' | '.hash('sha256', $string).' | '.$data['endpointID'].$data['orderID'].$data['merchantOrderID'].$data['status'].$data['amount'].$data['customerEmail'].$this->merchantControl.'<br/>\n
		');

		return ($data["signature"] == hash('sha256', $string));
	}
	
	public function newTransaction($accountID, $value, $transactionID, $currency) {
	    if(wlParams::get('officeCode') === 78){
	        $trType = 36;
        }else{
            $trType = 36;
        }

		$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=&accountID='.$accountID.'&trType='.$trType);

		$f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/zotapayResponse.txt',"a");
			fwrite($f, date('Y-m-d H:i:s').' NewZotapayTransaction  '.Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.trim($transactionID).'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType='.$trType.' ||||| '.json_encode($Info).'<br/>\n
		'); 
		 
		return  $Info;
	}
	
	public function ApplyZotapayTransaction($errorCode, $transactionid, $netValue, $currency = 'USD'){
        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump(Yii::app()->params['json_server'].'/API/Transactions/ApplyZotapayTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency='.$currency);die();
        }*/

        // will stay in pending for manual approval - Arsen 7.10.20
        if(strtolower($errorCode) === 'processing') return false;

        $tmp = explode('_', $transactionid);

        $type = 'bmfn';
        if(isset($tmp[1])){
            $type = $tmp[1];
        }

        $server = (in_array($type, ['t2', 'eforex', 'tm', 'gt', 'gwt', 'tom', 'efx'])) ? Yii::app()->params['json_server_eforex'] : Yii::app()->params['json_server'];

//var_dump(Yii::app()->params['json_server'].'/API/Transactions/ApplyZotapayTransaction?errorcode='.strtolower($errorCode).'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency='.$currency);die();
		 $Info = Yii::app()->curl->get($server.'/API/Transactions/ApplyZotapayTransaction?errorcode='.strtolower($errorCode).'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency='.$currency);
        //var_dump($Info, Yii::app()->params['json_server'].'/API/Transactions/ApplyZotapayTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency='.$currency);die();

		$f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/zotapayResponse.txt',"a");
fwrite($f, date('Y-m-d H:i:s').' ApplyZotapayTransaction: '.$server.'/API/Transactions/ApplyZotapayTransaction?errorcode='.strtolower($errorCode).'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency='.$currency.'  response:'.json_encode($Info).'
');
		//var_dump($Info, Yii::app()->params['json_server'].'/API/Transactions/ApplyZotapayTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency='.$currency);die();

		
		return  $Info;
	}

    public function withdrawal()
    {
        $url = 'https://api.zotapay-sandbox.com/api/v1/payout/request/'.$this->endpointId.'/';

        $data = [
            "merchantOrderDesc" => "Test order",
            "merchantOrderID" => uniqid(),
            "orderAmount" => "50.00",
            "orderCurrency" => "USD",
            "customerBankAccountName" => "John Doe",
            "customerBankAccountNumber" => "100200",
            "customerBankCode" => "BBL",
            "customParam" => [],
            "customerEmail" => "customer@email-address.com",
            "customerFirstName" => "John",
            "customerLastName" => "Doe",
           /* "customerBankBranch" => "Bank Branch",
            "customerBankZipCode" => "84280",*/
            "customerBankRoutingNumber" => "000",
        ];

        $data['signature'] = $this->signWithdrawalRequest($data);

        $res = $this->sendRequest($url, $data);

        //var_dump($url, $data, $res);die();
	}

    public function signWithdrawalRequest($requestFields)
    {
        //var_dump( $this->endpointId.$requestFields['merchantOrderID'].$requestFields['orderAmount'].$requestFields['customerEmail'].$requestFields['customerBankAccountNumber'].$this->merchantControl);die();
        /*$baseTest = $this->endpointId.'-'.$requestFields['merchantOrderID'].'-'.$requestFields['orderAmount'].'-'.$requestFields['customerEmail'].'-'.$requestFields['customerBankAccountNumber'].'-'.$this->merchantControl;
        var_dump($baseTest);*/

        $base = $this->endpointId.$requestFields['merchantOrderID'].$requestFields['orderAmount'].$requestFields['customerEmail'].$requestFields['customerBankAccountNumber'];
       // var_dump($base);

        return $this->signString($base, $this->merchantControl);
    }
	
	
	
}
