<?php
class EMerchantPay extends CFormModel
{
	public $type = 'emerpay';
	public $action;
	public $sign;
	private $key;
	
	public $client_id;
	public $form_id;
	public $order_currency;
	public $order_reference;
	public $test_transaction;

	public $item_1_code = 'emerpay1';
	public $item_1_qty = '1';
	public $item_1_predefined = '0';
	public $item_1_name = 'deposit';
	public $item_1_description = 'deposit to trading account';
	public $item_1_digital = '1';
	public $item_1_unit_price_USD;
	
	public $customer_first_name;
	public $customer_last_name;
	public $customer_address;
	public $customer_city;
	public $customer_country;
	public $customer_phone;
	public $customer_email;
	
	public $form_language;
	private $currencies = array('USD');
	
	public function init()
	{
		$this->action = Yii::app()->params['emerpay_action']."/payment/form/post"; 
		$this->key = Yii::app()->params['emerpay_key']; 
		$this->client_id = Yii::app()->params['emerpay_client_id']; 
		$this->form_id = Yii::app()->params['emerpay_form_id']; 
		$this->test_transaction = Yii::app()->params['emerpay_test_transaction']; 
	}
	
	public function getAttribute($name){
		return $this->$name;
	}
	
	public function initData($post){
		$Registration = new Registration('Individual');
		$Registration->initIndv();
		$countries_code_two = $Registration->GetCountry('two');
		
		
		$this->item_1_unit_price_USD = $post['amount'];
		$this->order_currency = $post['currency'];
		$this->order_reference = (int)$post['transferTo'].','.uniqid();
		$this->customer_country = $countries_code_two[$Registration->country];
		$this->customer_first_name = $Registration->firstName;
		$this->customer_last_name = $Registration->lastName;
		$this->customer_address = $Registration->address;
		$this->customer_city = $Registration->city;
		$this->customer_phone = $Registration->phone;
		$this->customer_email = $Registration->email;
		
		$this->setSecret($this->key);
		$this->setParam('client_id', $this->client_id);
		$this->setParam('form_id', $this->form_id);
		$this->setParam('order_currency', $this->order_currency);
		$this->setParam('order_reference', $this->order_reference);
		$this->setParam('test_transaction', $this->test_transaction);
		
		$this->setParam('item_1_code', $this->item_1_code);
		$this->setParam('item_1_qty', $this->item_1_qty);
		$this->setParam('item_1_predefined', $this->item_1_predefined);
		$this->setParam('item_1_name', $this->item_1_name);
		$this->setParam('item_1_description', $this->item_1_description);
		$this->setParam('item_1_digital', $this->item_1_digital);
		$this->setParam('item_1_unit_price_USD', $this->item_1_unit_price_USD);
		
		$this->setParam('customer_first_name', $this->customer_first_name);
		$this->setParam('customer_last_name', $this->customer_last_name);
		$this->setParam('customer_address', $this->customer_address);
		$this->setParam('customer_city', $this->customer_city);
		$this->setParam('customer_country', $this->customer_country);
		$this->setParam('customer_phone', $this->customer_phone);
		$this->setParam('customer_email', $this->customer_email);

				
		$requestString = $this->getQueryString();
		
		return $this->action.'?'.$requestString;		
	}
	
	public function newTransaction($accountID, $value, $transactionID, $currency){		
		//var_dump(Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.$transactionID.'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType=9');die();
		$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=9');
		//var_dump($Info, Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.trim($transactionID).'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType=9');die();
		
		$f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/eMerPay.txt',"a");
			fwrite($f, 'newEMerPayTransaction  '.Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.trim($transactionID).'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType=9'.' ||||| '.json_encode($Info).'<br/>\n
		'); 
		
		return  $Info;
	}
	
	public function ApplyEMerPayTransaction($errorCode, $transactionid, $netValue, $currency){
		$Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/ApplyeMerchantPayTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency='.$currency);
		//var_dump(Yii::app()->params['json_server'].'/API/Transactions/ApplyeMerchantPayTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency='.$currency, $Info);die();
		
		$f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/eMerPay.txt',"a");
			fwrite($f, 'ApplyBfoPayTransaction  '.Yii::app()->params['json_server'].'/API/Transactions/ApplyeMerchantPayTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency=CNY'.' ||||| '.json_encode($Info).'<br/>\n
		'); 
		
		return  $Info;
	}
	
	//////////////////////////////////////////////////// ********* basic functions ********** //////////////////////////////////////////////////////////////// 
	public $secret;
	public $params;
	public $lifetime=24;
	public $signatureType='PSMD5';

	function setSecret($secret)
	{
		$this->secret=$secret;
	}

	function setLifeTime($lifetime)
	{
		$this->lifetime=$lifetime;
	}

	function setSignatureType($signatureType)
	{
		if ($this->_checkSignatureType($signatureType)){
			$this->signatureType=$signatureType;
		}else{
            throw new exception ("Invalid signatureType : $signatureType");
		}
	}

	function setParam ($param,$value)
	{
        if ($param!='PS_SIGNATURE')	$this->params[$param]=$value;
    }

    function setParams ($paramArray)
    {
        foreach ($paramArray as $param=>$value){
            $this->setParam($param,$value);
        }
    }

	function getQueryString()
	{
		return $this->getSignature(true);
	}

    function getSignedParams ()
    {
        $Sig = $this->getSignature();
        return $this->params  + array('PS_SIGNATURE' => $Sig);
    }


    function getSignature ($queryString=false)
    {
        if (empty($this->secret)){
            throw new exception ("Paramsigner secret is empty!");
        }
        $this->setParam('PS_EXPIRETIME',time()+(3600*$this->lifetime));
        $this->setParam('PS_SIGTYPE',$this->signatureType);
        $sigstring=$this->secret;
        $urlencstring='';
        ksort($this->params,SORT_STRING);
        foreach ($this->params as $key=>$value){
            $sigstring.="&".$key.'='.$value;
            $urlencstring.="&".urlencode($key).'='.urlencode($value);
        }
        switch ($this->params['PS_SIGTYPE']){
            case 'md5':
            case 'MD5':
            case 'PSMD5':
                $signature=md5($sigstring);
                break;
            case 'PSSHA1':
            case 'sha1':
            case 'SHA1':
                $signature=sha1($sigstring);
                break;
            default:
                throw new exception('Unknown key signatureType');
        }

        if ($queryString){
			$this->sign = $signature;
            return 'PS_SIGNATURE='.urlencode($signature).$urlencstring;
        }else{
            return $signature;
        }
    }

	private function _checkSignatureType($value)
	{
        if ($value=='md5') return true;
        if ($value=='MD5') return true;
        if ($value=='PSMD5') return true;
        if ($value=='sha1') return true;
        if ($value=='SHA1') return true;
        if ($value=='PSSHA1') return true;
        return false;
	}

    public static function paramAuthenticate ($paramArray, $secret = FALSE)
    {
        $sentSignature = @$paramArray['PS_SIGNATURE'];
        unset($paramArray['PS_SIGNATURE']);
        $string = '';
        ksort($paramArray, SORT_STRING);
        foreach ($paramArray as $key => $value) {
            $string .= "&" . $key . '=' . $value;
        }
        switch (@$paramArray['PS_SIGTYPE']) {
            case 'MD5':
            case 'md5':
            case 'PSMD5':
                $signature = md5($secret . $string);
                break;
            case 'sha1':
            case 'SHA1':
            case 'PSSHA1':
                $signature = sha1($secret . $string);
                break;
            default:
                return false;
        }
        if ($sentSignature != $signature) {
            return false;
        }

        unset($paramArray['PS_SIGTYPE']);
        unset($paramArray['PS_EXPIRETIME']);
        return $paramArray;
    }
}