<?php

class cashU extends CFormModel
{
    public $type = 'cashu';
    public $amount;
    public $currency = 'USD';
    public $txt1;			// account
    public $txt2;			// email
    public $txt3;			// name
    public $txt4;			// address
	public $txt5;			// currency - amount
	
	public $session_id;		
	public $token;
    public $language;
	
    private $display_text = 'funds|520_cashu_display_text';
    private $message = 'funds|446_you_will_redir_secure_payment';
	private $errorsList = array('2'=>'funds|510_cashu_error_2', '4'=>'funds|511_cashu_error_4', '6'=>'funds|512_cashu_error_6', '7'=>'funds|513_cashu_error_7', '8'=>'funds|514_cashu_error_8', '15'=>'funds|515_cashu_error_15', 
								'17'=>'funds|516_cashu_error_17', '20'=>'funds|517_cashu_error_20', '21'=>'funds|518_cashu_error_21', '22'=>'funds|519_cashu_error_22', '23'=>'funds|520_cashu_error_23');
	private $currencies = array('USD');
	private $langs = array('ar', 'en');
	
    private $service_name;						    //Deposit_Funds_bmfn.com
	private $merchant_id;							//BMFNARAB
																																								
	private $enc_key;														// 956ee5ffc2119e49c56bc5d33bf  	- live	
																			// b7941df472a9af2c3c957dff14819	- demo
			
			
	private $action; 														// https://secure.cashu.com/payment.wsdl 			- live
																			// https://sandbox.cashu.com/secure/payment.wsdl 	- demo
																			
	private $action2;														// https://www.cashu.com/cgi-bin/payment/pcashu.cgi		- live
																			// https://sandbox.cashu.com/cgi-bin/payment/pcashu.cgi	- demo
																			
	private $Transaction_Code;												
																			
	private $test_mode;														// 0 - live	
																			// 1 - demo

    public function rules(){
   
		return array(
		//	array('merchant_id, service_name, test_mode, display_text', 'required', 'message'=> Yii::t("main","36_cannot_be_blank")),
			array('amount, currency, language, txt2, txt3, txt4, txt5, token, session_id', 'required', 'message'=> Yii::t("main","36_cannot_be_blank")),
		   
		//	array('merchant_id', 'match', 'pattern' => '/^[A-Za-z_\.\-@0-9]+$/', 'message' => Yii::t("main","368_field_is_not_valid")),
			array('amount', 'numerical', 'integerOnly'=>false, 'tooBig'=>Yii::t("funds","506_month_validate")),
			array('currency', 'in', 'range' => $this->currencies), 
			array('language', 'in', 'range' => $this->langs),
		//	array('display_text', 'length', 'min'=>0, 'max'=>250, 'tooShort'=>Yii::t("main","528_min_length_is"), 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('txt2, txt3, txt4, txt5', 'length', 'min'=>0, 'max'=>250, 'tooShort'=>Yii::t("main","528_min_length_is"), 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('txt1', 'length', 'min'=>1, 'max'=>150, 'tooShort'=>Yii::t("main","528_min_length_is"), 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('txt1', 'match', 'pattern' => '/^[A-Za-z_\.\-@\’\”0-9]+$/', 'message' => Yii::t("main","368_field_is_not_valid")),
			array('token', 'length', 'is'=>32),
		//	array('test_mode', 'in', 'range' => array(0, 1)),
			array('session_id', 'length', 'min'=>1, 'max'=>100, 'tooShort'=>Yii::t("main","528_min_length_is"), 'tooLong'=>Yii::t("main","529_max_length_is")),
		//	array('service_name', 'length', 'min'=>1, 'max'=>50, 'tooShort'=>Yii::t("main","528_min_length_is"), 'tooLong'=>Yii::t("main","529_max_length_is")),
		//	array('service_name', 'match', 'pattern' => '/^[A-Za-z_\.\-@0-9]+$/', 'message' => Yii::t("main","368_field_is_not_valid")),
			array('txt2, txt3, txt4, txt5, session_id', 'match', 'pattern' => '/^[A-Za-z_\.\-@0-9]+$/', 'message' => Yii::t("main","368_field_is_not_valid")),

		);
	}
	
	public function init()
	{
		if($this->getScenario() != 'static'){
			$Registration = new Registration('Individual');
			$Registration->initIndv();	
			
			$this->txt2 = $Registration->email; 
			$this->txt3 = str_replace(array(' '), array('_'), $Registration->firstName.'_'.$Registration->lastName);
			$this->txt4 = str_replace(array('/', '\\', ' ', '№', '#', '\(', '\)'), array('l', 'l', '_', 'no.', 'no.', '', ''), $Registration->address.'-'.$Registration->city.'-'.$Registration->country); 

			$tmp = explode('|', $this->display_text);
			$this->display_text = Yii::t($tmp[0],$tmp[1]);
			
			$tmp = explode('|', $this->message);
			$this->message = Yii::t($tmp[0],$tmp[1]);
			
			
			$this->language = (Yii::app()->request->cookies['language']->value == 'ar') ? 'ar' : 'en';
		}

		$this->enc_key = Yii::app()->params['cashu_enc_key'];
		$this->action = Yii::app()->params['cashu_action'];
		$this->action2 = Yii::app()->params['cashu_action2'];
		$this->test_mode = Yii::app()->params['cashu_test_mode'];
        $this->service_name = Yii::app()->params['cashu_service_name'];
        $this->merchant_id = Yii::app()->params['cashu_merchant_id'];
    }
	
	public function getCurrencies(){
		return $this->currencies();
	}
	
	public function getAttribute($name){
		return $this->$name;
	}
	
	public function getError($errorCode){
		$erList = $this->errorsList;
		$tmp = explode('|', $erList[$errorCode]);
		return Yii::t($tmp[0],$tmp[1]);		
	}
	
	public function getStep2Params(){
		$data['action'] = $this->action2;
		$data['type'] = 'cashu';
		$data['message'] = $this->message;
		$data['data']['Transaction_Code'] = $this->Transaction_Code;
		$data['data']['token'] = $this->session_id;
		return $data;
	}
	
    public function getCashuParams($account, $amount, $currency){
		$this->currency = $currency;
		$this->amount = $amount;
		$this->txt1 = (int)$account;
		$this->txt5 = $currency.'-'.$amount;
		$this->session_id = uniqid();


		//$this->token = md5(strtolower($this->merchant_id.':'.$this->amount.':'.$this->currency).':'.$this->enc_key);
        $this->token = md5(strtolower($this->merchant_id) . ':' . $this->amount . ':' . strtolower($this->currency) . ':' /*. strtolower($this->session_id) . ':'*/ . $this->enc_key);
        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump($this->session_id, $this->token, '22222222222222222222');
        }*/

		if($this->validate()){					
			$client = new SoapClient($this->action, array('trace' => true));
			//echo strtolower($this->merchant_id.':'.$amount.':'.$currency.':'.$this->enc_key).'</br>';



			$response = $client->DoPaymentRequest($this->merchant_id, $this->token, $this->display_text, $this->currency, $this->amount, $this->language, $this->session_id, $this->txt1, $this->txt2, $this->txt3, $this->txt4, $this->txt5, $this->test_mode, $this->service_name);


            /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                //var_dump('token: '.strtolower($this->merchant_id.':'.$this->amount.':'.$this->currency));die();
                var_dump($this->merchant_id, $this->token, $this->display_text, $this->currency, $this->amount, $this->language, $this->session_id, $this->txt1, $this->txt2, $this->txt3, $this->txt4, $this->txt5, $this->test_mode, $this->service_name, '---', $response, $this->action, $this->enc_key, strtolower($this->merchant_id) . ':' . $this->amount . ':' . strtolower($this->currency) . ':' . strtolower($this->session_id) . ':' . $this->enc_key);die();
            }*/

			if(strstr($response, 'Transaction_Code')){
				$tmp = strstr($response, '='); 
				$this->Transaction_Code = substr($tmp, 1);	
				return true;
			}else{
				Yii::log(CVarDumper::dumpAsString(array('SOAP get "Transaction_Code" - fail')), 'error', 'cashuTrans');
				$_SESSION['message'][] = array("text" => Yii::t("funds","507_cashu_error").'<div class="trueError" style="display:none">'.$response.'</div>', "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
			}			
		}else{
			Yii::log(CVarDumper::dumpAsString(array('Validate data error')), 'error', 'cashuTrans');
			$_SESSION['message'][] = array("text" => Yii::t("funds","507_cashu_error").'<div class="trueError" style="display:none">Validate Error - '.json_encode($this->getErrors()).$this->txt4.'</div>', "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
		}
		return false;
	}
	
	public function newTransaction($accountID, $value, $transactionID, $currency = 'USD'){
		//$ourTransactionId = md5(strtolower($this->merchant_id.':'.$value.':'.$currency).':'.$this->enc_key);
		$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=1');

        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/cashuResponse.txt',"a");
        fwrite($f, date('d.m.Y H:i:s').' '.json_encode($Info).' '.Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.$transactionID.'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType=1<br/>\n
            ');

		return  $Info;
	}
	
	public function ApplyCashUTransaction($errorCode, $transactionid, $netValue){
		//var_dump(Yii::app()->params['json_server'].'/API/Transactions/ApplyCashUTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue);
		$Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/ApplyCashUTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue);
		//var_dump($Info, Yii::app()->params['json_server'].'/API/Transactions/ApplyCashUTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue);

        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/cashuResponse.txt',"a");
        fwrite($f, date('d.m.Y H:i:s').' '.json_encode($Info).' '.Yii::app()->params['json_server'].'/API/Transactions/ApplyCashUTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.'<br/>\n
            ');

		return  $Info;
	}

    
    
  
    
   
}
