<?php
class BfoPay extends CFormModel
{
	public $type = 'bfopay';
	
	public $MemberID;
	public $TerminalID;
	public $InterfaceVersion = '4.0';
	public $KeyType = '1';
	public $PayID = '';
	public $TradeDate;
	public $TransID;
	public $OrderMoney;
	public $ProductName;
	public $Username;
	public $Amount;
	public $AdditionalInfo;
	public $PageUrl = 'http://my.fxcentral.com/bfopayPage.html';
	public $ReturnUrl = 'http://my.fxcentral.com/bfopayNotify.html';
	public $Signature;
	public $NoticeType = '1';
	public $Md5key;
	
	
	private $currencies = array('USD','CNY');
	
	
	public $action;
	
	
	// withdrawal
	public $member_id; //100000178
	public $terminal_id; //100000710
	public $data_type = 'json';
	public $data_content;
	public $version = '4.0.0';
	public $with_action; 		//'http://api-cgwfo.asias.com/asias-fo-pay/pay/BF0040001.do';     //'https://api.asiaswift.com/fopay/pay/BF0040001.do';
	public $with_check_action; //'http://api-cgwfo.asias.com/asias-fo-pay/pay/BF0040002.do';     //'https://api.asiaswift.com/fopay/pay/BF0040002.do';
	public $with_multy_action; //'http://api-cgwfo.asias.com/asias-fo-pay/pay/BF0040004.do';     //'https://api.asiaswift.com/fopay/pay/BF0040004.do';
	public $trans_no;
	public $trans_money;
	public $to_acc_name; //'Zhangsan';
	public $to_acc_no; //'6222601234567890';
	public $to_bank_name;
	public $to_pro_name = '';  // optional
	public $to_city_name = '';  // optional
	public $to_acc_dept = '';  // optional
	public $trans_sysflag = 1;  // optional
	public $trans_summary = '';  // Return 
	
	
	public $bank_names = array(''=>'',
		'China Merchant Bank'=>'招商银行',
		'Industrial and Commercial Bank of China'=>'中国工商银行',
		'China Construction Bank'=>'中国建设银行',
		'Shanghai Pudong Development Bank'=>'浦发银行',
		'Agricultural Bank of China'=>'中国农业银行',
		'China Minsheng Banking'=>'中国民生银行',
		'Ping An Bank'=>'平安银行',
		'Industrial Bank'=>'兴业银行',
		'Bank of Communications'=>'交通银行',
		'China Everbright Bank'=>'中国光大银行',
		'Bank of China'=>'中国银行',
		'Bank of Beijing'=>'北京银行',
		'Bohai Bank'=>'渤海银行',
		'Postal Savings Bank of China'=>'中国邮政储蓄银行',
		'China Citic Bank'=>'中信银行',
		'Bank of Hangzhou'=>'杭州银行',
		'Huishang Bank'=>'徽商银行',
		'Bank of Nanjing'=>'南京银行',
		'China Zheshang Bank'=>'浙商银行',
		'JCBank'=>'晋城银行',
		'Bank of Ningbo'=>'宁波银行',
		'Bank of Rizhao'=>'日照银行',
		'Bank of Hebei'=>'河北银行',
		'Hua Xia Bank'=>'华夏银行',
		'Weihai City Commercial Bank'=>'威海市商业银行',
		'Bank of Wenzhou'=>'温州银行',
		'Bank of Guangzhou'=>'广州银行',
		'Bank of Dalian'=>'大连银行',
		'Bank of Dongguan'=>'东莞银行',
		'Fudian Bank'=>'富滇银行',
		'Bank of Shanghai'=>'上海银行',
		'Bank of Chengdu'=>'成都银行',
		'Bank of Xian'=>'西安银行',
		'Bank of Qingdao'=>'青岛银行',
		'Harbin Bank'=>'哈尔滨银行',
		'Bank of Zhengzhou'=>'郑州银行',
		'Bank of Jining'=>'济宁银行',
		'Bank of Changsha'=>'长沙银行',
		'Bank of Shaoxing'=>'绍兴银行',
		'Guilin Bank'=>'桂林银行',
		'Qishang Bank'=>'齐商银行',
		'Bank of Jiangsu'=>'江苏银行',
		'Qilu Bank'=>'齐鲁银行',
		'HKB'=>'汉口银行',
		'Bank of Liuzhou'=>'柳州银行',
		'Bank of Chongqing'=>'重庆银行',
		'Bank of Tianjin'=>'天津银行');
	
	
	
	public function rules(){
		return array(
			// deposit
			array('MemberID, TerminalID, InterfaceVersion, KeyType, TradeDate, TransID, OrderMoney, PageUrl, ReturnUrl, Signature, NoticeType', 'required', 'message'=> Yii::t("main","36_cannot_be_blank"), 'on'=>'deposit'),
			array('TransID', 'length', 'is'=>20, 'tooShort'=> 'must be {length} characters', 'on'=>'deposit'),
			array('ProductName', 'length', 'max'=>50, 'tooShort'=> 'max {max} characters allowed', 'on'=>'deposit'),
			array('AdditionalInfo', 'length', 'max'=>255, 'tooShort'=> 'max {max} characters allowed', 'on'=>'deposit'),
			
			// withdrawal
			array('to_acc_name, to_acc_no, to_bank_name', 'required', 'message'=> Yii::t("main","36_cannot_be_blank"), 'on'=>'withdrawal'), //  , to_pro_name, to_city_name, to_acc_dept
			array('to_acc_name, to_acc_no, to_bank_name, trans_money', 'required', 'message'=> Yii::t("main","36_cannot_be_blank"), 'on'=>'withdrawalSend'), 
		);
	}
	
	public function init()
	{
		$this->MemberID = $this->member_id = Yii::app()->params['bfopay_merchantid']; //'300224'; //'100000178';
		$this->TerminalID = $this->terminal_id = Yii::app()->params['bfopay_terminalid']; //'19616'; //'10000001'; 
		$this->Md5key = Yii::app()->params['bfopay_key']; //'rjhgywqmnkqjexbd'; //'abcdefg'; 
		$this->action = Yii::app()->params['bfopay_action']; // https://gw.bfopay.com/payindex // http://tgw.bfopay.com/payindex
		
		$this->with_action = Yii::app()->params['bfopay_with_action']; 
		$this->with_check_action = Yii::app()->params['bfopay_with_check_action']; 
		$this->with_multy_action = Yii::app()->params['bfopay_with_multy_action']; 
		
		$http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';
		$this->PageUrl = $http.'//'.$_SERVER['HTTP_HOST'].'/bfopayPage.html';
		$this->ReturnUrl = $http.'//'.$_SERVER['HTTP_HOST'].'/bfopayNotify.html';
	}

	
	public function getAttribute($name){
		return $this->$name;
	}
	
	public function sendRequest($params){
		die('assia swift not available');
		$Registration = new Registration('Individual');
		$Registration->initIndv();
		
		$post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
		$post_data['action'] = $this->action;
		$post_data['type'] = $this->type;
		
		$post_data['data']['MemberID'] = $this->MemberID;
		$post_data['data']['TerminalID'] = $this->TerminalID;
		$post_data['data']['InterfaceVersion'] = $this->InterfaceVersion;
		$post_data['data']['KeyType'] = $this->KeyType;
		$post_data['data']['PayID'] = $this->PayID;
		$post_data['data']['TradeDate'] = $this->TradeDate = date('Ymdhis');
		$post_data['data']['TransID'] = $this->TransID = uniqid();
		$post_data['data']['OrderMoney'] = $this->OrderMoney = $params['amount']*100;
		$post_data['data']['Amount'] = $this->Amount;
		$post_data['data']['ProductName'] = $this->ProductName = (int)$params['account'];
		$post_data['data']['Username'] = $this->Username = rawurlencode($Registration->firstName.' '.$Registration->lastName);
		$post_data['data']['AdditionalInfo'] = $this->AdditionalInfo = (int)$params['account'].','.$params['real_amount'].','.$params['real_currency'].','.$this->Username.','.rawurlencode($Registration->email);
		$post_data['data']['PageUrl'] = $this->PageUrl;
		$post_data['data']['ReturnUrl'] = $this->ReturnUrl;
		$post_data['data']['Signature'] = md5($this->Signature = $this->MemberID.'|'.$this->PayID.'|'.$this->TradeDate.'|'.$this->TransID.'|'.$this->OrderMoney.'|'.$this->PageUrl.'|'.$this->ReturnUrl.'|'.$this->NoticeType.'|'.$this->Md5key);
		$post_data['data']['NoticeType'] = $this->NoticeType;
		
		return $post_data;
	}
	
	public function newTransaction($accountID, $value, $transactionID, $currency = 'CNH'){		
		$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=7');
		//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=7', $Info);die();
		
		$f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/bfopay.txt',"a");
			fwrite($f, 'ApplyBfoPayTransaction  '.Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.$transactionID.'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType=7'.' ||||| '.json_encode($Info).'<br/>\n
		'); 
		
		return  $Info;
	}
	
	public function ApplyBfoPayTransaction($errorCode, $transactionid, $netValue){
		$Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/ApplyBfoPayTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency=CNY');
		$f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/bfopay.txt',"a");
			fwrite($f, 'ApplyBfoPayTransaction  '.Yii::app()->params['json_server'].'/API/Transactions/ApplyBfoPayTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency=CNY'.' ||||| '.json_encode($Info).'<br/>\n
		'); 
		
		return  $Info;
	}
	
	public function checkResult($result){
		$MemberID=$result['MemberID'];
		$TerminalID =$result['TerminalID'];
		$TransID =$result['TransID'];
		$Result=$result['Result'];
		$ResultDesc=$result['ResultDesc'];
		$FactMoney=$result['FactMoney'];
		$AdditionalInfo=$result['AdditionalInfo'];
		$SuccTime=$result['SuccTime'];
		$Md5Sign=$result['Md5Sign'];
		$Md5key = $this->Md5key;
		$MARK = "~|~";

		$WaitSign=md5('MemberID='.$MemberID.$MARK.'TerminalID='.$TerminalID.$MARK.'TransID='.$TransID.$MARK.'Result='.$Result.$MARK.'ResultDesc='.$ResultDesc.$MARK.'FactMoney='.$FactMoney.$MARK.'AdditionalInfo='.$AdditionalInfo.$MARK.'SuccTime='.$SuccTime.$MARK.'Md5Sign='.$Md5key);
		if ($Md5Sign == $WaitSign) {			
			return true;			
		}else{
			return false;
		} 
	} 
	 
	public function sendWithdrawalData($transactionID, $json){
		$Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/sendWithdrawalData?guid='.Yii::app()->user->id.'&transactionID='.$transactionID.'&json='.$json);
		//var_dump(Yii::app()->params['json_server'].'/API/Transactions/sendWithdrawalData?guid='.Yii::app()->user->id.'&transactionID='.$transactionID.'&json='.$json, $Info);die();
		
		return $Info;
	}
	
	public function sendWithdrawalResponse($transactionID, $trans_batchid, $trans_no){
		$Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/sendWithdrawalResponse?transactionID='.$transactionID.'&transBatchID='.$trans_batchid.'&transNo='.$trans_no);
		//var_dump(Yii::app()->params['json_server'].'/API/Transactions/sendWithdrawalResponse?transactionID='.$transactionID.'&transBatchID='.$trans_batchid.'&transNo='.$trans_no, $Info);die();
		
		return $Info;
	}
	
	public function applyWithdrawalTransaction($transactionID, $return_code){
		//var_dump(Yii::app()->params['json_server'].'/API/Transactions/applyWithdrawalTransaction?transactionID='.$transactionID.'&return_code='.$return_code);die();
		$Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/applyWithdrawalTransaction?transactionID='.$transactionID.'&returnCode='.$return_code);
		
		return $Info;
	}
	
	public function getErrorCodes(){
		return array(
			'0000'=>'The withdrawal request is successfully accepted.',
			'200'=>'The withdrawal is successful.',
			'0001'=>'The format of common parameters is not right.',
			'0002'=>'The merchant digital certificate is invalid.',
			'0003'=>'The format of request message is not right.',
			'0004'=>'The number of transactions within the request message is being above the limit.',
			'0201'=>'The withdrawal service is not available to the merchant.',
			'0202'=>'The merchant doesn’t exist. Please contact Bfopay.',
			'0203'=>'The IP of the server is not registered at Bfopay. Please contact Bfopay technical support engineers.',
			'0204'=>'The terminal number doesn’t exist for the withdrawal service. Please contact Bfopay technical support engineers.',
			'0205'=>'The recipient of the withdrawal is on the bank black list. The withdrawal is failed.',
			'0206'=>'The withdrawal is restricted.',
			'0300'=>'The transaction status is unknown. Please look up the transaction with the query interfaces.',
			'0301'=>'The withdrawal is failed.',
			'0401'=>'There is no record for this transaction. Please perform reconciliation for your account to have a double confirmation.',
			'0501'=>'The system has failed to add the recipient to the white list.',
			'0999'=>'The system is busy.',
		);
	}
	
	
}