<?php

class Neteller extends CFormModel
{
	public $action;
	private $clientId;
	private $clientSecret;
	public $transactionAmount;
	public $paymentMethodValue; //Email or Account ID
	public $transactionMerchantRefId;
	public $transactionCurrency;
	public $verificationCode; //Secure ID or Authentication Code

	private $currencies = array('USD'/* , 'EUR'*/);
		

    public function rules(){
	
		return array(
			array('transactionAmount, paymentMethodValue, transactionMerchantRefId, transactionCurrency, verificationCode', 'required', 'message'=> Yii::t("main","36_cannot_be_blank")),
			array('transactionCurrency', 'in', 'range' => $this->currencies, 'message' => Yii::t("sp","120_not_listed")),
			array('transactionAmount', 'numerical', 'integerOnly'=>true, 'message' => Yii::t("main","371_numbers_allowed")),
		);
	}
	
	public function init()
	{
		$this->action = Yii::app()->params['neteller_action'];
		$this->clientId = Yii::app()->params['neteller_clientId'];
		$this->clientSecret = Yii::app()->params['neteller_clientSecret'];

        $this->currencies = array('USD', 'EUR', 'AED', 'AUD', 'BGN', 'BRL', 'CHF', 'DKK', 'GBP', 'HUF', 'INR', 'MAD', 'MXN', 'MYR', 'NGN', 'NOK', 'PLN', 'RON', 'RUB', 'SEK', 'SGD', 'TND', 'TWD', 'ZAR');
        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            //var_dump($this->currencies);die();
        } */
	}
	
    public function getAttribute($name){
		return $this->$name;
	}
	
	public function sendRequest(){
		require $_SERVER['DOCUMENT_ROOT']."/protected/config/Neteller/NetellerAPI.php";
		
		extract($_POST);
		
		define('NETELLER_BASE_URL', $this->action);
		define('NETELLER_CLIENT_ID', $this->clientId);
		define('NETELLER_CLIENT_SECRET', $this->clientSecret);

		$Ntlr_DepositCurrency = $this->transactionCurrency;
		$Ntlr_DepositAmount = $this->transactionAmount;
		$Ntlr_DepositEmail = $this->paymentMethodValue;
		$Ntlr_DepositSecureId = $this->verificationCode;
		
		if($Ntlr_DepositCurrency != "JPY" || $Ntlr_DepositCurrency != "HUF" || $Ntlr_DepositCurrency != "KRW" )
		{
			$Ntlr_DepositAmount = $Ntlr_DepositAmount * 100;
		}

		//Also, decimal values are not allowed - only integers.
		$Ntlr_DepositAmount = round($Ntlr_DepositAmount);

		$deposit = new RequestPayment();

		//var_dump($Ntlr_DepositEmail);die();

		$deposit->setPaymentMethodValue($Ntlr_DepositEmail)
				//this should be generating a unique string, for example using the current date/time
				->setTransactionMerchantRefId($this->transactionMerchantRefId)
				->setTransactionAmount($Ntlr_DepositAmount)
				//you should set here the transaction currency. USD is just an example here. Depending on your implementation, you might need to make this a customer input.
				->setTransactionCurrency($this->transactionCurrency)
				->setVerificationCode($Ntlr_DepositSecureId);
				
		$result = $deposit->doRequest();


        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump($result, $this->action, $this->clientId, $this->clientSecret, $_POST, $Ntlr_DepositCurrency, $Ntlr_DepositAmount, $Ntlr_DepositEmail, $Ntlr_DepositSecureId);die();
        }*/
				/* if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
					var_dump($deposit, $result);die();
											
		} */
		


		//These lines are just for debugging purposes, you don't need them in your live code

		$errors = $deposit->getExecutionErrors();
		$ip = $deposit->getIP();
		
		
		$f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/neteller.txt',"a");
			fwrite($f, 'NetellerDepositFirstRequest refId '.$this->transactionMerchantRefId.'  -  '.$Ntlr_DepositAmount.'  -  '.$Ntlr_DepositEmail.'  -  '.json_encode($result).' - '.json_encode($errors).' - <br/>\n
		')
		;
		

 		//var_dump($result);
		//var_dump($errors);
		//var_dump($ip);



		if($result != false)
		{
			if(isset($result->transaction->amount) && isset($result->transaction->fees)){
				$amount = (float)$result->transaction->amount/100;
				foreach($result->transaction->fees as $fee){
					$amount = $amount - (float)$fee->feeAmount/100;
				}
			}

			//This means that the transaction was successful. You can choose what to do with the result here.
			//For example, show success message to the customer, or redirect him somewhere.
			return array('status'=>'ok', 'amount'=>$amount);
		}
		else
		{
           /* if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
                var_dump($errors);die();
            }*/
            if(isset($errors["api_error_message"]) && !empty($errors["api_error_message"])){
                $tmp_error = $errors["api_error_message"];
            }elseif(isset($errors["api_error_code"]) && !empty($errors["api_error_code"])){
                $tmp_error = $errors["api_error_code"];
            }

			if(isset($tmp_error)){
				return $tmp_error;
			}else{
				return 'Neteller Deposit Error.';
			}
		}
	}
	
	
	public function newTransaction($accountID, $value, $transactionID, $currency = 'USD'){
        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            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=5');
        }*/
		$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=5');
        //var_dump($Info);

        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump($Info);die();
        }*/

        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/neteller.txt',"a");
            fwrite($f, 'NewTransaction Neteller  -  '.Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.$transactionID.'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType=5'.' :response: '.json_encode($Info).' <br/>\n
		');

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

        if(strstr($transactionid, 'eforex')){
            $server = Yii::app()->params['json_server_eforex'];
        }else{
            $server = Yii::app()->params['json_server'];
        }

        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump($server.'/API/Transactions/ApplyNettellerTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue);die();
        }*/

        $Info = Yii::app()->curl->get($server.'/API/Transactions/ApplyNettellerTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.($netValue == '0' ? '' :'&currency='.$currency));



		$f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/neteller.txt',"a");
			fwrite($f, 'ApplyNettellerTransaction  -  '.$server.'/API/Transactions/ApplyNettellerTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency='.$currency.' :response: '.json_encode($Info).' <br/>\n
		');
		
		return  $Info;
	}

    
    
  
    
   
}
