<?php 

class NEO extends CFormModel
{
	public $type = 'neo';
	public $action;
	
	private $merchantID;
	private $encKey;
	
	public $merchantOrderNumber;	// purse number
	public $currency;
	public $amount;
	public $successURL;
	public $failureURL;
	public $transactionType;
	public $transactionMode;
	public $payModeType;
	public $udf1;				// trading account number
	
	public $billToFirstName;
	public $billToLastName;
	public $billToStreet1;
	public $billToStreet2;
	public $billToCity;
	public $billToState;
	public $billToPostalCode;
	public $billToCountry;
	public $billToEmail;
	
	public $gatewayID = '';
	public $creditCardNumber = '';
	public $cvv = '';
	public $expiryMonth = '';
	public $expiryYear = '';
	public $cardType = '';
	public $iv;
	
	public $enc = MCRYPT_RIJNDAEL_128;
	public $mode = MCRYPT_MODE_CBC;
	
	private $currencies = array('AED','USD');
	
	
	public function rules(){
		return array(
			//array('merchantID, merchantOrderNumber, currency, amount, successURL, failureURL, transactionType, transactionMode, payModeType, udf1, billToFirstName, billToStreet1, billToLastName, billToCity, billToState, billToPostalCode, billToCountry, billToEmail, gatewayID', 'required', 'message'=> Yii::t("main","36_cannot_be_blank")),
			
			//array('merchantID, creditCardNumber, cvv, expiryMonth, expiryYear, GatewayID', 'numerical', 'integerOnly'=>true, 'message' => Yii::t("main","371_numbers_allowed")),
			//array('merchantID', 'length', 'max'=>15, 'tooLong'=>Yii::t("main","529_max_length_is")),			
			array('merchantOrderNumber, billToEmail', 'length', 'max'=>100, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('currency', 'length', 'max'=>3, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('currency', 'in', 'range' => array('AED'), 'message' => Yii::t("funds","571_attr_is_not_in_the_list")),
			array('amount', 'numerical', 'integerOnly'=>false, 'allowEmpty'=>false, 'message' => Yii::t("main","371_numbers_allowed")),
			array('successURL, failureURL', 'length', 'max'=>200, 'tooLong'=>Yii::t("main","529_max_length_is")),
			//array('expiryMonth', 'length', 'max'=>2, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('transactionType, payModeType, billToCountry', 'length', 'max'=>2, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('transactionMode, billToState', 'length', 'max'=>20, 'tooLong'=>Yii::t("main","529_max_length_is")),
			//array('cardType', 'length', 'max'=>20, 'tooLong'=>Yii::t("main","529_max_length_is")),
			//array('creditCardNumber', 'length', 'max'=>16, 'tooLong'=>Yii::t("main","529_max_length_is")),
			//array('cvv, expiryYear', 'length', 'max'=>4, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('billToFirstName, billToLastName, billToCity', 'length', 'max'=>40, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('billToStreet1, billToStreet2', 'length', 'max'=>40, 'tooLong'=>Yii::t("main","529_max_length_is")), // 40 characters in manual
			array('billToPostalCode', 'length', 'max'=>9, 'tooLong'=>Yii::t("main","529_max_length_is")),
			//array('gatewayID', 'length', 'max'=>5, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('udf1', 'length', 'max'=>250, 'tooLong'=>Yii::t("main","529_max_length_is")),
			
			array('billToFirstName, billToLastName, billToStreet1', 'match','pattern' => '/^[a-z0-9\s\_\.\@\/\,\-\:\']*$/i', 'message' => Yii::t("funds","579_alphanumeric_with_spaces_and_spec_char")),	
			array('billToCity, billToState', 'match', 'pattern' => '/^[a-z\s]*$/i', 'message' => Yii::t("funds","578_alphameric_with_spaces")),	
			array('billToPostalCode', 'match', 'pattern' => '/^[a-z0-9\s]*$/i', 'message' => Yii::t("funds","577_alphanumeric_with_spaces")),	
		);
	}
	
	public function init()
	{
		$this->action = Yii::app()->params['neo_action_url'];
		$this->merchantID = Yii::app()->params['neo_merchant_id'];
		$this->encKey = Yii::app()->params['neo_enc_key'];
		
		$this->iv = '0123456789abcdef';
		
		$this->transactionType = '01'; 
		$this->transactionMode = 'INTERNET'; 
		$this->payModeType = 'CC'; 
		$http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';
		$this->successURL = $http.'//'.$_SERVER['HTTP_HOST'].'/neoTransSuccess.html'; 
		$this->failureURL = $http.'//'.$_SERVER['HTTP_HOST'].'/neoTransError.html';
		if(!Yii::app()->user->isGuest){
			$Registration = new Registration('Individual');
			$Registration->initIndv();	
			
			$this->billToFirstName = $Registration->firstName;
			$this->billToLastName = $Registration->lastName;
			if(strlen($Registration->address > 40)){
				$this->billToStreet1 = substr(str_replace('+', ' ', $Registration->address), 0, 39);
				$this->billToStreet2 = substr(str_replace('+', ' ', $Registration->address), 40, 79);
			}else{
				$this->billToStreet1 = str_replace('+', ' ', $Registration->address);
			}
			$this->billToCity = $Registration->city;
			$this->billToState = $Registration->city;
			$this->billToPostalCode = (isset($Registration->zipcode) && !empty($Registration->zipcode) && $Registration->zipcode != "null") ? $Registration->zipcode : '1000';
			$this->billToEmail = $Registration->email;
			
			$countries_code_two = $Registration->GetCountry('two');
			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->billToCountry = $country_code;			
		}
	}
	
	public function attributeLabels(){
		return array(
			'billToFirstName'=>Yii::t("main",'27_first_name'),
			'billToLastName' => Yii::t("main",'28_last_name'),
			'billToStreet1' => Yii::t("main",'133_address'),
			'billToStreet2' => Yii::t("main",'133_address'),
			'billToCity' => Yii::t("main",'132_city'),
			'billToState' => Yii::t("main",'132_city'),				
			'billToPostalCode' => 'Postal Code',
			'billToEmail' => Yii::t("main",'131_email'),
			'billToCountry' => Yii::t("main",'129_country'),
		);
    }
	
	public function getAttribute($name){
		return $this->$name;
	}
	
	public function sendRequestWithParams($data){
		
		$this->merchantOrderNumber = uniqid().rand(0,9);	//uniqid().rand(0,9);  // encode fields
		
		if($data['currency'] != 'AED'){
			$this->amount = round(stFunctions::currConv($data["currency"], 'AED', $data['amount']), 2);
		}else{
			$this->amount = $data['amount'];
		}
		$this->currency = 'AED';
		//$this->creditCardNumber = '5200000000000007';
		//$this->cvv = '123';		//test ???
		//$this->expiryMonth = '12';
		//$this->expiryYear = '2018';
		//$this->cardType = 'MASTERCARD';
		$this->udf1 = (int)$data['transferTo'];
		
		//var_dump($this->attributes);die();
		$this->billToStreet1 = str_replace(array('#','(',')','№'), array('','','',''), $this->billToStreet1);
		$this->billToStreet2 = str_replace(array('#','(',')','№'), array('','','',''), $this->billToStreet2);
		
		if($this->validate()){
			$textRequest = $this->merchantOrderNumber.'|'.$this->currency.'|'.$this->amount.'|'.$this->successURL.'|'.$this->failureURL.'|'.$this->transactionType.'|'.$this->transactionMode.'|'.$this->payModeType
			.'|'.$this->creditCardNumber.'|'.$this->cvv.'|'.$this->expiryMonth.'|'.$this->expiryYear.'|'.$this->cardType.'|'.$this->billToFirstName.'|'.$this->billToLastName.'|'.$this->billToStreet1.'|'.$this->billToStreet2.'|'
			.$this->billToCity.'|'.$this->billToState.'|'.$this->billToPostalCode.'|'.$this->billToCountry.'|'.$this->billToEmail.'|||||'.$this->gatewayID.'|||||||||||||||||||FALSE|'.$this->udf1.'|||||';
			
			//echo $textRequest.'<br />';
			
			$size = mcrypt_get_block_size($this->enc, $this->mode);
			$pad = $size - (strlen($textRequest) % $size);
			$padtext = $textRequest . str_repeat(chr($pad), $pad);

            /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
			var_dump($padtext);die();

            }*/

			$crypt = mcrypt_encrypt($this->enc, base64_decode($this->encKey), $padtext, $this->mode, $this->iv);
			$requestParameter = $this->merchantID.'|'.base64_encode($crypt);
			
			//echo $requestParameter.'<br />';
			
			/*  echo '<form action="'.$this->action.'" method="post" id="networkonline_checkout" name="networkonline_checkout">
			<input type="hidden" name="requestParameter" value="'.$requestParameter.'">
			<input type="submit" value="Pay via networkonline" name="suba" id="sub">
			</form>'; */
			
			return array('requestParameter'=>$requestParameter, 'order'=>$this->merchantOrderNumber);
		}else{
			$errors = $this->getErrors();
			
			return array('error'=>$errors);
		}
	}
	
	public function decodeResponse($response){
		$EncText=base64_decode($response);
		$padtext = mcrypt_decrypt($this->enc, base64_decode($this->encKey), $EncText, $this->mode, $this->iv);
		//var_dump($padtext);die();

		$pad = ord($padtext{strlen($padtext) - 1});
		if ($pad > strlen($padtext)) return false;
		if (strspn($padtext, $padtext{strlen($padtext) - 1}, strlen($padtext) - $pad) != $pad){
			$text = "Error";
		}
		$text = substr($padtext, 0, -1 * $pad);
		return $text;
	}
	
	public function encodeResponse($response){
		$size = mcrypt_get_block_size($this->enc, $this->mode);
		$pad = $size - (strlen($response) % $size);
		$padtext = $response . str_repeat(chr($pad), $pad);

		$crypt = mcrypt_encrypt($this->enc, base64_decode($this->encKey), $padtext, $this->mode, $this->iv);
		$requestParameter = $this->merchantID.'|'.base64_encode($crypt);
		
		return $requestParameter;
	}
	
	public function newTransaction($accountID, $value, $transactionID, $currency){
		//var_dump($transactionID.$accountID.$this->encKey);die(); 
		$trID = md5($transactionID.$accountID.$this->encKey);
		$Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.$trID.'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType=6');
		//var_dump(Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.$trID.'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType=6', $Info);die();
		
		$f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/neoResponse.txt',"a");
		fwrite($f, Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.$trID.'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType=6 ----> '.json_encode($Info).'<br/>\n
		'); 
		
		return  $Info;
	}
	
	public function ApplyNeoTransaction($errorCode, $errormessage, $transactionid){
		//var_dump('----', $transactionid.$this->encKey);
		$statuses = array('SUCCESS'=>'0', 'PENDING'=>'2000', 'FAILURE'=>'-6000');
		$transactionid = md5($transactionid.$this->encKey);
		//var_dump(Yii::app()->params['json_server'].'/API/Transactions/ApplyNeoTransaction?errorcode='.$errorCode.'&errormessage='.$errormessage.'&transactionid='.$transactionid);
		$Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/ApplyNeoTransaction?errorcode='.$statuses[$errorCode].'&errormessage='.$errormessage.'&transactionid='.$transactionid);
		//var_dump($Info);
		
		$f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/neoResponse.txt',"a");
		fwrite($f, Yii::app()->params['json_server'].'/API/Transactions/ApplyNeoTransaction?errorcode='.$statuses[$errorCode].'&errormessage='.$errormessage.'&transactionid='.$transactionid.' ----> '.json_encode($Info).'<br/>\n
		');
		
		return  $Info;
	}
}