<?php

class Neteller2 extends CFormModel
{
    public $type = 'neteller2';
    private $paymentType = "NETELLER";
    private $transactionType = "PAYMENT";
    public $merchantRefNum;
    public $currencyCode;
    public $amount;
    public $defaultLink;
    public $onCompletedLink;
    public $onFailedLink;

    public $consumerId;
    public $consumerIdLocked;
    public $detail1Description;
    public $detail1Text;

    public $street;
    public $street2;
    public $city;
    public $zip;
    public $country;

    public $locale;
    public $firstName;
    public $lastName;
    public $email;
    public $phone;

    public $day;
    public $month;
    public $year;


    public $customerIp;

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

	private $netellerApiUrl;
	private $netellerApiKey;

    public $status;
    public $account;
    public $currency;

    //callback
    public $payload;
    public $eventType;

    public function rules(){
	
		return array(
			array('amount, merchantRefNum, currencyCode', 'required', 'on' => 'deposit', 'message'=> Yii::t("main","36_cannot_be_blank")),
			array('currencyCode', 'in', 'range' => $this->currencies, 'message' => Yii::t("sp","120_not_listed")),
			//array('transactionAmount', 'numerical', 'integerOnly'=>true, 'message' => Yii::t("main","371_numbers_allowed")),
			array('status, account, amount, currency', 'required', 'on' => 'return',  'message'=> Yii::t("main","36_cannot_be_blank")),
		);
	}
	
	public function init()
	{
        $this->netellerApiUrl = Yii::app()->params['neteller2_url'];
        $this->netellerApiKey = Yii::app()->params['neteller2_key'];

        $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');

	}
	
    public function getAttribute($name){
		return $this->$name;
	}

    public function initData($data)
    {
        require_once $_SERVER["DOCUMENT_ROOT"]."/protected/config/Neteller2/paysafe-neteller-api.php";
        require_once $_SERVER["DOCUMENT_ROOT"]."/protected/config/Neteller2/Neteller/PaymentHandle.php";
        /*if ($_SERVER['REMOTE_ADDR'] == '46.98.17.9' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            //var_dump($postFund);die();
            var_dump('1111', $data);die();
        }*/
        require_once $_SERVER["DOCUMENT_ROOT"]."/protected/config/Neteller2/Neteller/Link.php";
        require_once $_SERVER["DOCUMENT_ROOT"]."/protected/config/Neteller2/Neteller/Neteller.php";
        require_once $_SERVER["DOCUMENT_ROOT"]."/protected/config/Neteller2/Neteller/BillingDetails.php";
        require_once $_SERVER["DOCUMENT_ROOT"]."/protected/config/Neteller2/Neteller/Profile.php";
        require_once $_SERVER["DOCUMENT_ROOT"]."/protected/config/Neteller2/Neteller/DateOfBirth.php";
       // require_once('../source/paysafe-neteller-api.php');

        $http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';
        $Registration = new Registration('Individual');
        $countries_code_two = $Registration->GetCountry('two');
        $Registration->initIndv();


        $this->merchantRefNum = uniqid().'_'.Yii::app()->params['type'];

        $paymentHandle = new PaymentHandle;
        $paymentHandle->paymentType = $this->paymentType;
//this should contain your unuique transaction ID
        $paymentHandle->merchantRefNum = $data2['data']['merchantRefNum'] = $this->merchantRefNum;
//change this to your transaction currency
        $paymentHandle->currencyCode = $data2['data']['currency'] = $data["currency"];
//change this to the desired deposit amount
        $data2['data']['amount'] = (float)$data["amount"];
        $paymentHandle->amount = (float)$data["amount"]*100;

        $defaultLink = new Link;

        $defaultLink->rel = "default";
        $defaultLink->href = $http.'//'.$_SERVER['HTTP_HOST'].'/funds/deposit.html';


        $onCompletedLink = new Link;
        $onCompletedLink->rel = "on_completed";
        $onCompletedLink->href = $http.'//'.$_SERVER['HTTP_HOST'].'/returnTrans?type='.$this->type.'&status=success'.'&account='.(int)$data['transferTo'].'&amount='.$data["amount"].'&currency='.$data["currency"];

        $onFailedLink = new Link;
        $onFailedLink->rel = "on_failed";
        $onFailedLink->href = $http.'//'.$_SERVER['HTTP_HOST'].'/returnTrans?type='.$this->type.'&status=error'.'&account='.(int)$data['transferTo'].'&amount='.$data["amount"].'&currency='.$data["currency"];


        $paymentHandle->returnLinks = $defaultLink;
        $paymentHandle->returnLinks = $onCompletedLink;
        $paymentHandle->returnLinks = $onFailedLink;

        $paymentHandle->transactionType = $this->transactionType;

        $neteller = new Neteller;
//change this to the email of the customer
        //var_dump($data);die();
        $neteller->consumerId = $data['ntlrAccId'];
        $neteller->consumerIdLocked = false;
        $neteller->detail1Description = $data2['data']['account'] = (int)$data['transferTo'];
        $neteller->detail1Text= 'Trading account';

        $paymentHandle->neteller = $neteller;
//and the below to the details of the customer
        $billingDetails = new BillingDetails;
        $billingDetails->street = $Registration->address;
        $billingDetails->street2 = $Registration->address;
        $billingDetails->city = $Registration->city;
        $billingDetails->zip = "1234";
        $billingDetails->country = $countries_code_two[$Registration->country];

        $paymentHandle->billingDetails = $billingDetails;

        $profile = new Profile;
        $profile->locale = Yii::app()->language;
        $profile->firstName = $Registration->firstName;
        $profile->lastName = ($Registration->lastName == '') ? $Registration->firstName : $Registration->lastName;
        $profile->email = $Registration->email;
        $profile->phone = $Registration->phone;

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '78.46.17.32') {
            var_dump($Registration->lastName == '', $Registration);die();
        }*/

        $birthday = explode('/', $Registration->birthday);

        $dob = new DateOfBirth;
        $dob->day = $birthday[1];
        $dob->month = $birthday[0];
        $dob->year = $birthday[2];

        $profile->dateOfBirth = $dob;

        $paymentHandle->profile = $profile;

        $paymentHandle->customerIp = $_SERVER['REMOTE_ADDR'];

        try{
            $paymentHandle->create($this->netellerApiKey, $this->netellerApiUrl);

            //$data2['data']['link'] = $paymentHandle->links[0]->href;
            $data2["action"] = $paymentHandle->links[0]->href;

            $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/neteller2.txt',"a");
            fwrite($f, date('Y-m-d H:i:s').' getLink  -  Payment Handle ID: '.$paymentHandle->id.' PaymentHandleToken: '.$paymentHandle->paymentHandleToken.' <br/>\n
		');

            //var_dump($paymentHandle);die();

            /*print "Redirect URL: " . $paymentHandle->links[0]->href. "<br />";
            print "Payment Handle ID: " . $paymentHandle->id . "<br />";
            print "PaymentHandleToken: " . $paymentHandle->paymentHandleToken;*/
            /* Do something with the data here */

        }catch(NetellerException $e){
            //$data2['data']['link'] = '';


            $data2["action"] = '';
            $_SESSION['message'][] = array("text"=>$e->getMessage(),"action"=>Yii::app()->controller->id."/".Yii::app()->controller->action->id,"type"=>"error");
        }

        $data2["message"] = Yii::t("funds","446_you_will_redir_secure_payment");
        $data2['type'] = $this->type;


        return $data2;
    }
	
	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/neteller2.txt',"a");
            fwrite($f, date('Y-m-d H:i:s').' 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, '_')){
            $tmp = explode('_', $transactionid);
            $server = (isset($tmp[1]) && in_array($tmp[1], ['t2', 'eforex', 'tm', 'gt'])) ? Yii::app()->params['json_server_eforex'] : Yii::app()->params['json_server'];
        }else{
            $server = Yii::app()->params['json_server'];
        }

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


//var_dump($server.'/API/Transactions/ApplyNettellerTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.($netValue == '0' ? '' :'&currency='.$currency));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/neteller2.txt',"a");
			fwrite($f, date('Y-m-d H:i:s').' ApplyNettellerTransaction  -  '.$server.'/API/Transactions/ApplyNettellerTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency='.$currency.' :response: '.json_encode($Info).' <br/>\n
		');
		
		return  $Info;
	}

    public function confirmOnReturn(){
        return true;
    }

    public function isSuccess()
    {
        return $this->status == 'success';
    }

    public function getRedirectLink()
    {
        if($this->isSuccess()){
            return '/transaction.html?ammount='.$this->amount.'&currency='.$this->currency.'&account='.$this->account;
        }else{
            return '/transaction.html?errorText=';
        }
    }

    public function parseCallback($json)
    {

        $webhook_object = json_decode($json);

        if($webhook_object->eventType == "PAYMENT_HANDLE_PAYABLE"){
            require_once $_SERVER["DOCUMENT_ROOT"]."/protected/config/Neteller2/Neteller/PaymentHandle.php";
            $paymentHandle = new PaymentHandle();

            $paymentHandle->id = $webhook_object->payload->id;

            try{
                $paymentHandle->lookupById($this->netellerApiKey, $this->netellerApiUrl);
            }
            catch(NetellerException $e){
                //echo $e->getMessage(); //handle the exception

                        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/neteller2.txt',"a");
                        fwrite($f, date('Y-m-d H:i:s').' ApplyNettellerTransaction  -   '.json_encode($e->getMessage()).' <br/>\n
                ');
            }


            if($paymentHandle->status == "PAYABLE"){
                $this->ApplyNettellerTransaction('yes', $paymentHandle->merchantRefNum);
                /*require_once $_SERVER["DOCUMENT_ROOT"]."/protected/config/Neteller2/Neteller/Payment.php";
                $payment = new Payment();
                //this should contain your unuique transaction ID, here we use the same ID as the payment handle just for simplicity.

                $payment->merchantRefNum = $paymentHandle->merchantRefNum;
                $payment->paymentHandleToken = $paymentHandle->paymentHandleToken;
                $payment->amount = $paymentHandle->amount;
                $payment->currencyCode = $paymentHandle->currencyCode;

                try{
                    $payment->create($this->netellerApiKey, $this->netellerApiUrl);

                    print "Payment ID : " . $payment->id. "<br />";
                    print "Payment Status: " . $payment->status . "<br />";
                    // Do something with the data here

                }catch(NetellerException $e){
                    print $e->getMessage(); //handle the exception
                }*/
            }else{

                /*$payment->merchantRefNum = $paymentHandle->merchantRefNum;
                $payment->paymentHandleToken = $paymentHandle->paymentHandleToken;
                $payment->amount = $paymentHandle->amount;
                $payment->currency = $paymentHandle->currency;*/
                //var_dump($paymentHandle, $paymentHandle->merchantRefNum, $paymentHandle->paymentHandleToken, $paymentHandle->amount, $paymentHandle->currency);die();
                //var_dump($paymentHandle, $paymentHandle->merchantRefNum, $paymentHandle->status);die();
                $this->ApplyNettellerTransaction($paymentHandle->status, $paymentHandle->merchantRefNum);

            }
        }
    }

}
