<?php

class dcPay extends CFormModel
{
    public $type = 'dcpay';
	public $apiversion = '3';
	public $version = '11';
	
		private $action;
		private $partner_control;
		
	public $merchant_account;
	public $server_return_url;		
	public $amount; // $amount*100
	public $currency = 'CNH'; 
	public $first_name; 
	public $last_name; 
	public $address1;  
	public $city;  
	public $zip_code;  
	public $country;  
	public $phone;  
	public $email;  
	public $merchant_order;  
	public $merchant_product_desc;  
	public $return_url;  
	public $ipaddress; 
		
	private $currencies = array('USD'/*,'CNY'*/); //allows deposits in CNY less than 50 USD. commented by Arsen

    public function rules(){
		$Registration = new Registration('Individual');
		$Registration->initIndv();	
		$countries_code_two = $Registration->GetCountry('two');
		return array(
			array('apiversion, version, return_url, server_return_url, currency, city, merchant_order, amount, zip_code, merchant_account, first_name, last_name, address1, country, phone, email, ipaddress', 'required', 'message'=> Yii::t("main","36_cannot_be_blank")),
			
			array('merchant_order, merchant_account', 'length', 'max'=>12, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('amount, zip_code, version', 'length', 'max'=>10, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('first_name, last_name, address1, city', 'length', 'max'=>50, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('country', 'length', 'max'=>2, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('country', 'in', 'range' => $countries_code_two, 'not'=>false, 'message' => Yii::t("main","36_cannot_be_blank")),
			array('phone, ipaddress', 'length', 'max'=>15, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('email', 'length', 'max'=>50, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('email' , 'email', 'message' => Yii::t("main","22_this_email_address_is_not_a_valid")),
			array('currency', 'length', 'max'=>3, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('return_url, server_return_url', 'length', 'max'=>100, 'tooLong'=>Yii::t("main","529_max_length_is")),   // ????? in documentation max - 40

		);
	}
	
	public function init()
	{
		$http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';
		if (!Yii::app()->user->isGuest) {
			$Registration = new Registration('Individual');
			$Registration->initIndv();
            $countries_code_two = $Registration->GetCountry('two');

			$this->first_name = $Registration->firstName.' '.$Registration->lastName;
			$this->address1 = substr($Registration->address, 0, 49);
			$this->city = $Registration->city;
			$this->zip_code = (!empty($Registration->zipcode)) ? $Registration->zipcode : '1000';;
			$this->phone = trim($Registration->phone);
			$this->email = $Registration->email;
			$this->ipaddress = $_SERVER["REMOTE_ADDR"];
			
			if(isset($countries_code_two[$Registration->country])){
				$country_code = $countries_code_two[$Registration->country];
			}else{
				preg_match('/(.*)\(/', $Registration->country, $matches);
				if(isset($countries_code_two[$matches[1]])){
					$country_code = $countries_code_two[$matches[1]];
				}else{
					$country_code = 'CN';
				}
			}
			$this->country = $country_code;
		}
		
		$this->return_url = $http.'//'.$_SERVER["SERVER_NAME"].'/dcpayTrans.html?isUser';
		
		$this->action = 'https://payment.ccp.dcpay.biz/ChinaDebitCard';
		$this->merchant_account = Yii::app()->params['dcpay_merchant_acc']; 				// live - 567654543
		$this->partner_control = Yii::app()->params['dcpay_partner_control'];				// live - aac9fe064ba3c8ac1a6d4b2f3bd8b632
		$this->server_return_url = $http.'//'.$_SERVER["SERVER_NAME"].'/dcpayTrans.html';
	}
	
	public function getAttribute($name){
		return $this->$name;
	}
	
    public function getDcpayParams($account, $amount){
		$post_data['type'] = $this->type;
		$post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
		$post_data['action'] = $this->action;
		$post_data['data']['apiversion'] = $this->apiversion; 	  
		$post_data['data']['version'] = $this->version;	 
		$tstring = $post_data['data']['merchant_account'] = $this->merchant_account;  
		$tstring .= $post_data['data']['amount'] = $this->amount  = (float)$amount*100; 
		$tstring .= $post_data['data']['currency'] = ($this->currency == 'CNH') ? 'CNY' : $this->currency;
		$tstring .= $post_data['data']['first_name'] = trim($this->first_name); 
		$tstring .= $post_data['data']['last_name'] = $this->last_name  = (int)$account; 
		$tstring .= $post_data['data']['address1'] = trim($this->address1); 
		$tstring .= $post_data['data']['city'] = trim($this->city); 
		$tstring .= $post_data['data']['zip_code'] = $this->zip_code; 
		$tstring .= $post_data['data']['country'] = $this->country;
		$tstring .= $post_data['data']['phone'] = trim($this->phone);
		$tstring .= $post_data['data']['email'] = $this->email; 
		$uniq = uniqid();
		$tstring .= $post_data['data']['merchant_order'] = $this->merchant_order = substr($uniq, -12, strlen($uniq));
		$tstring .= $post_data['data']['merchant_product_desc'] = $this->merchant_product_desc = (int)$account; 
		$tstring .= $post_data['data']['return_url'] = $this->return_url;
		$post_data['data']['ipaddress'] = $this->ipaddress;
		$post_data['data']['server_return_url'] = $this->server_return_url; 
		$post_data['data']['control'] = hash_hmac('SHA1', $tstring, $this->partner_control); 
		
		/* if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
			var_dump($tstring, '--------', $post_data, $this->partner_control);
		} */

		if(!$this->validate()){
			$post_data = array();
			$getErrors = $this->getErrors();
			$errors = current($getErrors);
			$_SESSION['message'][] = array("text" => Yii::t("funds", "555_payment_error", array('{errorText}'=>$errors[0])), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
		}		
		
		return $post_data;
	}
	
	public function newTransaction($accountID, $value, $transactionID, $currency = 'CNH'){
		//var_dump(Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.$transactionID.'&currency=CNH&value='.$value.'&Id=&accountID='.$accountID.'&trType=3');
		$Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.$transactionID.'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType=3');
		//var_dump($Info);
		return  $Info;
	}
	
	public function ApplyDCPayTransaction($errorCode, $transactionid, $netValue){
		//var_dump(Yii::app()->params['json_server'].'/API/Transactions/ApplyDCPayTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue);die();
		$Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/ApplyDCPayTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency=CNY');
		//var_dump($Info);
		
		return  $Info;
	}

    public function ApplyDcPayMobileTransaction($errorCode, $transactionid, $netValue){
        //ApplyTransaction(string transactionKey, double? transactionAmount,  TransactionStateEnum transactionState)
        $transactionState = ($errorCode == 'A0') ? 0 : 1;
        //120.136.42.148

        $Info = Yii::app()->curl->get('http://cc.bmfn.com/API/Transaction/ApplyTransaction?transactionKey='.$transactionid.'&transactionAmount='.$netValue.'&transactionState='.$transactionState);
        
        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/dcpayResponse.txt',"a");
        fwrite($f, 'ApplyDcPayMobileTransaction: http://cc.bmfn.com/API/Transaction/ApplyTransaction?transactionKey='.$transactionid.'&transactionAmount='.$netValue.'&transactionState='.$transactionState.'  response:'.json_encode($Info).'<br/>\n
');



        return  $Info;
    }

    
    
  
    
   
}
