<?php

class Skrill extends CFormModel
{
    public $type = 'skrill';

	public $action;

	public $pay_to_email;
	public $transaction_id;
	public $return_url;
	public $return_url_target = '3';
	public $cancel_url;
	public $cancel_url_target = '3';
	public $status_url;
	public $status_url2;
	public $language;
	public $logo_url;
	public $merchant_fields;

	public $pay_from_email;
	public $firstname;
	public $lastname;
	public $date_of_birth;
	public $address;
	public $city;
	public $country;

	public $amount;
	public $currency;
	public $detail1_text;

	public $recipient_description;      // ???

	public $payment_methods;            // ???
		private $secretWord;



		static $skrill_lang = array('BG', 'CS', 'DA', 'DE', 'EL', 'EN', 'ES', 'FI', 'FR', 'IT', 'ZH', 'NL', 'PL', 'RO', 'RU', 'SV', 'TR', 'JA');
		static $denied_countries = array('AFG', 'CUB', 'MMR', 'NGA', 'PRK', 'SDN', 'SYR', 'SOM', 'YEM');
		private $currencies;

    private $currency_accs = [
        'EUR' => ['secretWord' => 'robinhood01EUR', 'pay_to_email' => 'operations_vt1@bmfn.com'],
        'GBP' => ['secretWord' => 'robinhood01GBP', 'pay_to_email' => 'operations_vt2@bmfn.com'],
        'AED' => ['secretWord' => 'robinhood01AED', 'pay_to_email' => 'operations_vt3@bmfn.com'],
        'KWD' => ['secretWord' => 'robinhood01KWD', 'pay_to_email' => 'operations_vt4@bmfn.com'],
        'SAR' => ['secretWord' => 'robinhood01SAR', 'pay_to_email' => 'operations_vt5@bmfn.com'],
    ];


	

    public function rules(){
		$Registration = new Registration('Individual');
		$Registration->initIndv();	
		$countries_code_three = $Registration->GetCountry('three');
		return array(
			array('pay_to_email, language, amount, currency', 'required', 'message'=> Yii::t("main","36_cannot_be_blank")),
			
			array('pay_to_email', 'length', 'max'=>50, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('recipient_description', 'length', 'max'=>30, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('transaction_id, pay_from_email, address', 'length', 'max'=>100, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('return_url, cancel_url, logo_url, merchant_fields, detail1_text', 'length', 'max'=>240, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('return_url_target, cancel_url_target', 'length', 'max'=>1, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('status_url, status_url2', 'length', 'max'=>400, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('language', 'length', 'max'=>2, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('firstname', 'length', 'max'=>50, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('lastname, city', 'length', 'max'=>50, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('date_of_birth', 'length', 'max'=>8, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('country, currency', 'length', 'max'=>3, 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('amount', 'length', 'max'=>19, 'tooLong'=>Yii::t("main","529_max_length_is")),
			
			array('country', 'in', 'range' => self::$denied_countries, 'not'=>true, 'message'=>Yii::t("funds","554_bad_skrill_country")),

		);
	}
	
	public function init()
	{
        if(wlParams::get('officeCode') == 13){
            $this->currencies = array('USD');
        }else{
            $this->currencies = array('USD');  //additional currencies are removed by Arsen. Email from Elena 30 Dec 2020
        }

		$http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';
		if (!Yii::app()->user->isGuest) {
			$Registration = new Registration('Individual');
			$Registration->initIndv(); 		
			if(!empty($Registration->birthday)){
				$_d =explode("/",$Registration->birthday);
				$birth = $_d[1].$_d[0].$_d[2];				
			}else{
				$birth = '';
			}
			$countries_code_three = $Registration->GetCountry('three');
			$lang = (in_array(strtoupper(Yii::app()->language), self::$skrill_lang)) ? Yii::app()->language : 'EN';

			$this->pay_from_email = $Registration->email;
			$this->firstname = $Registration->firstName;
			$this->lastname = $Registration->lastName;
			$this->date_of_birth = $birth;
			$this->address = $Registration->address;
			$this->city = $Registration->city;
			$this->language = $lang;
			$this->recipient_description = Yii::app()->params['name_company'];
			$this->detail1_text = Yii::t("funds","433_payment_through_skrill");
			$this->logo_url = 'https://my.bmfn-solutions.com/assets/img/'.str_replace(' ', '_', Yii::app()->params['name_company']).'.png';
			$this->status_url2 = 'mailto:'.Yii::app()->params['paymentsEmail'];
			
			
			
			if(isset($countries_code_three[$Registration->country])){
				$country_code = $countries_code_three[$Registration->country];
			}else{
				preg_match('/(.*)\(/', $Registration->country, $matches);
				if(isset($countries_code_three[$matches[1]])){
					$country_code = $countries_code_three[$matches[1]];
				}else{
					$country_code = 'CN';
				}
			}
			$this->country = $country_code;
		}


		//$this->secretWord = Yii::app()->params['skrill_secretWord'];		// live  -
		//$this->pay_to_email = Yii::app()->params['skrill_pay_to_email'];	// live  - ips@bmfn.com
																			// demo  - ipetrov@bmfn.com

		$this->action = 'https://pay.skrill.com'; //'https://www.skrill.com/app/pay.pl'; //https://www.moneybookers.com/app/payment.pl



        if(wlParams::get('officeCode') == 13){
            $callbackUrl = 'https://my.bmfn.com.au';
        }else{
            $callbackUrl = 'https://my.bmfnvt.com';
        }
		$this->status_url = $callbackUrl.'/skrillTrans.html';

        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            $this->currencies = array('USD', 'EUR');
        }*/

	}

    public function initCredentials()
    {
        if($this->currency != 'USD' && isset($this->currency_accs[$this->currency])){
            $this->secretWord = $this->currency_accs[$this->currency]['secretWord'];
            $this->pay_to_email = $this->currency_accs[$this->currency]['pay_to_email'];
        }else{
            $this->secretWord = Yii::app()->params['skrill_secretWord'];
            $this->pay_to_email = Yii::app()->params['skrill_pay_to_email'];
        }

        /*if ($_SERVER['REMOTE_ADDR'] == '46.98.64.234' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
var_dump($this->secretWord, $this->currency);die();
        }*/
	}
	
	public function getAttribute($name){
		return $this->$name;
	}
	
    public function getSkrillParams($account, $amount, $currency){
		$http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';
		
		$post_data['type'] = $this->type;
		$post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
		$post_data['action'] = $this->action;


        if(wlParams::get('officeCode') == 13){
		    $callbackUrl = 'https://my.bmfn.com.au';
        }else{
		    $callbackUrl = 'https://my.bmfnvt.com';
        }

        /*if($currency == 'EUR'){
            $this->secretWord = 'robinhood01EUR';
            $this->pay_to_email = 'operations_vt1@bmfn.com';
        }*/

        /*if($currency != 'USD' && isset($this->currency_accs[$currency])){
            $this->secretWord = $this->currency_accs[$currency]['secretWord'];
            $this->pay_to_email = $this->currency_accs[$currency]['pay_to_email'];
        }*/
        $this->currency = $currency;
        $this->initCredentials();

        /*if ($_SERVER['REMOTE_ADDR'] == '46.98.64.234' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump($this->secretWord, $this->pay_to_email);die();
        }*/

		$post_data['data']['pay_to_email'] = $this->pay_to_email;
		$post_data['data']['transaction_id'] = $this->transaction_id = Yii::app()->params['type'].'|'.uniqid();
		$post_data['data']['return_url'] = $this->return_url = $callbackUrl.'/payment/userRedirect?isUser&success&account='.$account.'&amount='.$amount.'&crncy='.$currency.'&u='.urlencode($http.'//'.$_SERVER["SERVER_NAME"]);
		$post_data['data']['cancel_url'] = $this->cancel_url = $callbackUrl.'/payment/userRedirect?isUser&cancel&u='.urlencode($http.'//'.$_SERVER["SERVER_NAME"]);
		$post_data['data']['status_url'] = $this->status_url;
		$post_data['data']['status_url2'] = $this->status_url2;
		$post_data['data']['payment_methods'] =  'SFT,PWY,PLI,NPY,ENT,GIR,GCB,SLO,MAE,DIN,AMX,MSC,VSA,ACC,PWY32';
		$post_data['data']['return_url_target'] = $this->return_url_target;
		$post_data['data']['cancel_url_target'] = $this->cancel_url_target;
		$post_data['data']['language'] = $this->language;
		$post_data['data']['logo_url'] = $this->logo_url;
		$post_data['data']['pay_from_email'] = $this->pay_from_email;
		$post_data['data']['firstname'] = $this->firstname;
		$post_data['data']['lastname'] = $this->lastname;
		$post_data['data']['date_of_birth'] = $this->date_of_birth;
		$post_data['data']['address'] = $this->address;
		$post_data['data']['city'] = $this->city;
		$post_data['data']['country'] = $this->country;
		$post_data['data']['amount'] = $this->amount = $amount;
		$post_data['data']['currency'] = $this->currency = $currency;
		$post_data['data']['recipient_description'] = $this->recipient_description;
		$post_data['data']['detail1_text'] = $this->detail1_text;
		$post_data['data']['merchant_fields'] = $this->merchant_fields = 'account='.(int)$account;

        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump($post_data);die();
        }*/
		
		if(!$this->validate()){
			$post_data = array();
			$getErrors = $this->getErrors();
			$errors = current($getErrors);
			$_SESSION['message'][] = array("text" => Yii::t("funds", "555_payment_error", array('{errorText}'=>$errors[0])), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
		}
		
		return $post_data;
	}
	
	public function newTransaction($accountID, $value, $transactionID, $currency = 'USD'){
		//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=4');
		$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=4');
		//var_dump($Info);
        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/skrillResponse.txt',"a");
        fwrite($f, 'SkrillNewTransaction '.Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.$transactionID.'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType=4 |||| '.json_encode($Info).'<br/>\n
					');

		return  $Info;
	}
	
	public function ApplySkrillTransaction($errorCode, $transactionid, $netValue){
		//var_dump(Yii::app()->params['json_server'].'/API/Transactions/ApplySkrillTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue);

        if(strstr($transactionid, 'eforex')){
            $server = Yii::app()->params['json_server_eforex'];
        }else{
            $server = Yii::app()->params['json_server'];
        }


        $Info = Yii::app()->curl->get($server.'/API/Transactions/ApplySkrillTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue);

        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump($Info, $server.'/API/Transactions/ApplySkrillTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue);die();
        }*/
        //var_dump($Info);


        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/skrillResponse.txt',"a");
        fwrite($f, 'ApplySkrillTransaction '.$server.'/API/Transactions/ApplySkrillTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.' |||| '.json_encode($Info).'<br/>\n
					');
        //var_dump($Info, Yii::app()->params['json_server'].'/API/Transactions/ApplySkrillTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue);die();
		
		return  $Info;
	}

    
    
  
    
   
}
