<?php
class FundServices extends CFormModel
{
	public $transferFrom;
	public $transferTo;
	public $currency;	
	
	public $amount;
	public $fundsSourse = ''; // for inatec deposit
	public $ccFullNumber;
	public $cvc_code;
	public $exp_month;
	public $exp_year;
	public $cardId = ''; // for inatec deposit

	public $cards = array('inatec'=>array('Visa'), 'safecharge'=>array('MasterCard', 'American Express', 'Other Cards'));
	public $noorcards = array('myfatoorah'=>array('MyFatoorah'), 'tap'=>array('Tap Payments'), /*'knet'=>array('KNET_1'),*/ 'knet2'=>array('KNET'), 'neonew'=>array('Bank Cards.'),  'upay'=>array('Upay'),  'myfatoorah_acc2'=>array('SADAD/MADA Cards'), 'myfatoorah_acc3'=>array('Swiss Global Deposit'),  'myfatoorah_acc4'=>array('ببطاقات مدى للسعوديه'), 'telr'=>array('Telr'), /*'inatec'=>array('Credit Card Deposit 1'),*/ 'lionpay'=>array('Credit Card Deposit'/* , 'MasterCard', 'American Express', 'Other Cards' */), 'ikajo'=>array('Credit Card Deposit'), 'network'=>array('Bank Cards'), 'ccavenue'=>array('Credit Card Avenue'), 'stripe'=>array('Stripe') );
	public $ips = array('skrill'=>'Skrill', 'cashu'=>'CASHU', 'globepay'=>'GlobePay', 'neteller2'=>'Neteller', 'cryptapi'=>'Crypto', 'finobyte'=>'FinoByte', /* 'lionpay'=>'Lion Pay',  */'neteller'=>'Neteller'/* , 'bfopay'=>'China Union 1' */, 'dinpay'=>'China Union 2', 'dcpay'=>'China Union', 'nowpay'=>'USDT TRC20'/*, 'webmoney'=>'WebMoney'*/, /*'astropay'=>'AstroPay', 'neonew'=>'Bank Cards'*/);
	//China Union 3
	public $trAccount;
	public $bonus;
	public $lotsAmount;

	public $ntlrAccId;
	public $ntlrSecId;

	public $x_cpf;

	public $bank;

	public $categoryID = 0;
	
	public $MinAmmountForIBAccountInternalTransfer;
	
	static $skrill_lang = array('EN', 'DE', 'ES', 'FR', 'IT', 'PL', 'GR', 'RO', 'RU', 'TR', 'CN', 'CZ', 'NL', 'DA', 'SV', 'FI');

	public $deposit_type;


    // gate_to_pay
	public $firstName;
	public $lastName;
	public $email;
	public $phoneNumber;
	public $address;
    public $sex;
    public $middleName;
    public $thirdName;
    public $birthday;
    public $passportNumber;
    public $idNumber;
    public $cardCurrency = 'USD';
    public $cardType = 'Standard';
    public $nationality;
    public $profession;
    public $nameOnTheCard;

	public $creditCardId;
	public $cardExpiryDate;
	public $gate_scenario;
    public $country;
    public $city;

	public function init(){
		if(wlParams::get('CardDepositSystem') == 'neo'){ 
			$this->noorcards = array('neo'=>array('Visa / MasterCard'));
		}

		$Account = new Account();
        $parentInfo = $Account->getParentContacts();
		$info = $Account->getInfo();

            $Registration = new Registration('Individual');
            $Registration->initIndv();

        if(!wlParams::get('knet')){
            unset($this->noorcards['knet']);
        }

       /* $ipx = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ipx == '77.222.143.18' || $ipx == '46.98.252.74') {
            var_dump($this->noorcards, wlParams::get('knet2'));die();
        }*/
        if(!wlParams::get('knet2')){
            unset($this->noorcards['knet2']);
        }

        if(!wlParams::get('stripe')){
            unset($this->noorcards['stripe']);
        }
//
//        if (($info->Login == '1000159258' /*ib 6*/ /* || $info->Login == '1000159317' /*Khaled KNET*/ || $_SERVER['REMOTE_ADDR'] == '71.206.36.216') && !isset($this->noorcards['knet'])) {
//            $this->noorcards['knet'] = array('KNET');
//        }



        if(!wlParams::get('globepay')){
            unset($this->ips['globepay']);
        }/*
        if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74' || $_SERVER['REMOTE_ADDR'] == '195.34.104.222') {
            $this->ips['globepay'] = 'GlobePay';
        }*/


		if(!wlParams::get('dinpay')){
			unset($this->ips['dinpay']);
		}
		if(!wlParams::get('dcpay')){
			unset($this->ips['dcpay']);
		}
		if(!wlParams::get('skrill')){
			unset($this->ips['skrill']);
		}
		if(!wlParams::get('cashu')){
			unset($this->ips['cashu']);
		}
		if(!wlParams::get('neteller')){
			unset($this->ips['neteller']);
		}
		if(!wlParams::get('neteller2')){
			unset($this->ips['neteller2']);
		}
		if(!wlParams::get('nowpay')){
			unset($this->ips['nowpay']);
		}

        if(Yii::app()->params['type'] === 'eforex_global'){
            unset($this->ips['cryptapi']);
//            $this->ips['upi_icici'] = 'UPIicici';
            $this->ips['cryptapi'] = 'Crypto Payment';
//            $this->ips['india_cash_deposit'] = 'IndiaCashDeposit';
        }

        $ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip !== '162.13.154.241') {
            unset($this->ips['finobyte']);
        }

        if(!wlParams::get('cryptapi')){
            unset($this->ips['cryptapi']);
        }

//        if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74' || $_SERVER['REMOTE_ADDR'] == '94.236.105.119' || $_SERVER['REMOTE_ADDR'] == '109.123.74.192' || $_SERVER['REMOTE_ADDR'] == '188.70.8.244' || $_SERVER['REMOTE_ADDR'] == '46.211.43.1') {
//
//        }else{
//            unset($this->ips['astropay']);
//            unset($this->noorcards['neonew']);
//            //unset($this->noorcards['knet2']);
//		}
//
//        if ($info->Login == '1000152489' || $_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74' || $_SERVER['REMOTE_ADDR'] == '94.236.105.119' ) {
//            $this->noorcards['neonew'] = array('Bank Cards');
//        }

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

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') { // for bond
            $this->ips['paytab'] = 'PayTabs';

        }*/

//
//        $ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
//        if ($ip == '162.13.154.241') {


            if(wlParams::get('paytab')){
                //$this->ips['paytab'] = 'PayTabs';
                if(Yii::app()->params['styles_type'] == 'new'){
                    $this->ips['paytab'] = 'PayTabs';
                }else{
                    $this->noorcards['paytab'] = array('PayTabs');
                }

            }
      //  }

        if(!wlParams::get('neo')){
            unset($this->noorcards['neonew']);
        }

        if(!wlParams::get('ikajo')){
            unset($this->noorcards['ikajo']);
        }

        if(!wlParams::get('telr')){
            unset($this->noorcards['telr']);
        }
        if(!wlParams::get('tap')){
            unset($this->noorcards['tap']);
        }
        if(!wlParams::get('fatoorah')){
            unset($this->noorcards['myfatoorah']);
        }
        if(!wlParams::get('fatoorah_acc2')){
            unset($this->noorcards['myfatoorah_acc2']);
        }if(!wlParams::get('fatoorah_acc2')){
            unset($this->noorcards['myfatoorah_acc2']);
        }
        if(!wlParams::get('fatoorah_acc3')){
            unset($this->noorcards['myfatoorah_acc3']);
        }
        if(!wlParams::get('fatoorah_acc4')){
            unset($this->noorcards['myfatoorah_acc4']);
        }
        if(!wlParams::get('network')){
            unset($this->noorcards['network']);
        }
        if(!wlParams::get('upay')){
            unset($this->noorcards['upay']);
        }

		/*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
			var_dump($this->noorcards, wlParams::get('ikajo'));die();
		}*/
		if(!wlParams::get('emerpay')){
			unset($this->noorcards['emerpay']);
		}
		if(!wlParams::get('zotapay')){
			unset($this->noorcards['zotapay']);		
		}else{
			$this->noorcards['zotapay'] = array('Instant Bank Deposit');
		}

//        if (/*$_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74' || */$info->Login == '1000085882') {
//            $this->noorcards['awepay'] = array('Awepay');
//            $this->ips['awepayshp'] = 'Awepay CUP';
//        }


		
		if(!wlParams::get('lionpay')){
			unset($this->noorcards['lionpay']);
		}

		if(!wlParams::get('ccavenue')){
			unset($this->noorcards['ccavenue']);
		}

		if( wlParams::get('officeCode') == 28  || wlParams::get('officeCode') == 5 ){
			if(wlParams::get('zotapay')){
				$this->noorcards['zotapay'] = array('Instant Bank Deposit');
			}
		}


		if(wlParams::get('ewallet')){
			$this->ips['ewallet'] = 'China Union 2';
		}

		if(wlParams::get('homepay')/* && $info->Login == '1000066729'*/){
			$this->ips['homepay'] = 'China Union 3';
		}

		if(wlParams::get('dinpay')){
			$this->ips['dinpay'] = 'China Union 4';
		}

        if(wlParams::get('cryptapi') || $info->Login == '1000148977'){
            $this->ips['cryptapi'] = 'USDT Transfer';
        }

		if(wlParams::get('nganluong')){
            $this->ips['nganluong'] = 'NganLuong';
		}

//        $ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
//        if(wlParams::get('totalpay') || $ip == '162.13.154.241'){
//            $this->noorcards['totalpay'] = array('TotalPay');
//        }



        $ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if(wlParams::get('gate_to_pay') || $ip == '11162.13.154.241'){
            $this->noorcards['gate_to_pay'] = array('Gate To Pay');
            //$this->ips['neteller'] = 'Neteller';
		}

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            var_dump($this->ips);die();
        }*/

		if(Yii::app()->request->cookies['language']->value == 'cn'){
			if(wlParams::get('dcpay')){
				$this->ips['dcpay'] = '银联';
			}
			if(wlParams::get('ewallet')){
				$this->ips['ewallet'] = '银联2';
			}
			if(wlParams::get('homepay')){
				$this->ips['homepay'] = '银联3';
			}
			if(wlParams::get('dinpay')){
				$this->ips['dinpay'] = '银联4';
			}
		}

		//  || (wlParams::get('officeCode') == 13 && ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74'))

		if(wlParams::get('officeCode') == 53 || (wlParams::get('officeCode') == 3 && $info->Login != '1000066729')){
			unset($this->noorcards['inatec']);
		}



		$MinAmmountForIBAccountInternalTransfer = $Account->GetSetting('MinAmmountForIBAccountInternalTransfer');
		$this->MinAmmountForIBAccountInternalTransfer = (is_numeric($MinAmmountForIBAccountInternalTransfer)) ? $MinAmmountForIBAccountInternalTransfer : 100;
		if(wlParams::get('officeCode') == 5){
			$this->ips['neteller'] = 'Neteller';
		}

		unset($this->ips['ewallet']);
		unset($this->ips['homepay']);

		if($info->Login == '1000148802'){
			unset($this->noorcards['zotapay']);
			unset($this->noorcards['emerpay']);
		}

        $ipx = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($info->Login == '1000199511') {
			$this->noorcards['network'] = array('Network');
        }



       /* $ipx = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($info->Login == '1000193124') {
            $this->ips['paytab'] = 'PayTabs';
        }*/



        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            $this->noorcards['network'] = array('Network');
        }*/

        $ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        /*if ($ip !== '162.13.154.241' ) {
            unset($this->noorcards['paymob']);
        }*/


        if ($info->Login == '1000228762'){
            $this->noorcards = [];
            $this->ips = [];
        }

	}
	
	public function rules(){
		$MinInternalTransfer = $this->GetSetting('MinInternalTransfer');
		$MinInternalTransfer = (is_numeric($MinInternalTransfer)) ? $MinInternalTransfer : 50;		
		
		$MinAmmountForDeposit = $this->GetSetting('MinAmmountForDeposit');
		$MinAmmountForDeposit = (is_numeric($MinAmmountForDeposit)) ? $MinAmmountForDeposit : 50;

		$MaxAmmountForDeposit = null;
		
        $Account = new Account();
        $info = $Account->getInfo();
        $parentInfo = $Account->getParentContacts();



		if($parentInfo["Code"] == '16769' || $info->Login == '1000156546'){
			$MinInternalTransfer = 250;
		}

		// Arsen ask to set 50 static 3/26/2021
		//$MinAmountForWithdrawals = $this->GetSetting('MinAmountForWithdrawals');
		//$MinAmountForWithdrawals = (is_numeric($MinAmountForWithdrawals)) ? $MinAmountForWithdrawals : 0;
        if(in_array(wlParams::get('officeCode'), [63])){
            $MinAmountForWithdrawals = 10;
        }else{
            $MinAmountForWithdrawals = 50;
        }



		//var_dump($MinAmountForWithdrawals, $MinInternalTransfer, $MinAmmountForDeposit, $MinAmmountForIbAccountWithdrwal, $MinAmmountForIBAccountInternalTransfer);die(); 
		
		if($this->getScenario()=='IntTrnsfr'){
			$isUserHasTheAccRule[] = array('transferFrom', 'on'=>'IntTrnsfr', 'isUserHasTheAcc', 'sysAccs' => true, 'isDemo' => false);
			$isUserHasTheAccRule[] = array('transferTo', 'on'=>'IntTrnsfr', 'isUserHasTheAcc', 'sysAccs' => false, 'isDemo' => false);
			$isUserHasTheAccRule[] = array('amount', 'numerical', 'integerOnly'=>false, 'min' => $MinInternalTransfer, 'numberPattern'=>'/^\d*[\.|\,]?\d{0,2}$/', 'on'=>'IntTrnsfr', 'allowEmpty' => false, 'message'=>Yii::t("funds","530_numbers_allowed"), 'tooSmall'=>Yii::t("funds","79_amount_cant_be_null"));
			$isUserHasTheAccRule[] = array('amount, transferFrom', 'checkAmount', 'on'=>'IntTrnsfr');	
		}elseif($this->getScenario()=='Fund'){
			$isUserHasTheAccRule[] = array('amount, transferFrom, currency', 'checkDepAmount', 'on'=>'Fund');
			$isUserHasTheAccRule[] = array('transferTo', 'on'=>'Fund', 'isUserHasTheAcc', 'sysAccs' => false, 'isDemo' => false);
		}elseif($this->getScenario()=='cardDeposit'){
			$isUserHasTheAccRule[] = array('transferTo', 'on'=>'cardDeposit', 'isUserHasTheAcc', 'sysAccs' => false, 'isDemo' => false);
			$isUserHasTheAccRule[] = array('amount', 'numerical', 'integerOnly'=>false, 'min' => $MinAmmountForDeposit, 'numberPattern'=>'/^\d*[\.|\,]?\d{0,2}$/', 'on'=>'cardDeposit', 'allowEmpty' => false, 'message'=>Yii::t("funds","530_numbers_allowed"), 'tooSmall'=>Yii::t("funds","79_amount_cant_be_null"));
		}elseif($this->getScenario()=='Withdrawal'){
			$isUserHasTheAccRule[] = array('transferFrom', 'on'=>'Withdrawal', 'isUserHasTheAcc', 'sysAccs' => true, 'isDemo' => false );  
		}elseif($this->getScenario()=='demoDeposit'){
			$isUserHasTheAccRule[] = array('transferTo', 'on'=>'demoDeposit', 'isUserHasTheAcc', 'sysAccs' => false, 'isDemo' => true);  
		}elseif($this->getScenario()=='openDemo'){
		    //if(Yii::app()->params['type'] !== 'efx'){
                $isUserHasTheAccRule[] = array('amount', 'in', 'range' => array_keys($this->GetDemoDepositValues()), 'on'=>'openDemo');
            //}
		}elseif($this->getScenario()=='ccFull'){
			//$isUserHasTheAccRule = array('ccFullNumber', 'match', 'pattern' => '/^\s*\d{4}\s*\d{4}\s*\d{4}\s*\d{4}\s*$/', 'message' => Yii::t("main","738_incorrect_cc_num"), 'on'=>'ccFull');
			$isUserHasTheAccRule[] = array('ccFullNumber', 'numerical', 'integerOnly'=>true, 'message'=>Yii::t("funds","533_ccn_must_be_number"));
		}else{
			$isUserHasTheAccRule = array();
		}
	
	
        return array_merge(array(					
            array('ccFullNumber, cvc_code, exp_year, exp_month', 'required', 'on'=>'ccFull', 'message'=>Yii::t("main","36_cannot_be_blank")), 
            array('ccFullNumber', 'lunaAlgoritm', 'on'=>'ccFull'),

            array('transferTo', 'required', 'on'=>'Fund, cardDeposit, IntTrnsfr', 'message'=>Yii::t("main","1083_choose_the_account")),
            array('transferFrom, currency, amount', 'required', 'on'=>'Fund, cardDeposit, IntTrnsfr', 'message'=>Yii::t("main","36_cannot_be_blank")),
            array('transferFrom, transferTo, firstName, lastName, email, phoneNumber, address, sex, birthday, passportNumber, idNumber, cardCurrency, cardType, nationality, profession, nameOnTheCard, city, country, gate_scenario', 'required', 'on'=>'gate_to_pay, gate_to_pay_create_card, ', 'message'=>Yii::t("main","36_cannot_be_blank")),
            array('middleName, thirdName', 'safe', 'on'=>'gate_to_pay, gate_to_pay_create_card'),
            array('phoneNumber','match','pattern' => '/^(\+?\d+)?\s*(\(\d+\))?[\s-]*([\d-]*)$/', 'message' => Yii::t("main","35_incorrect_phone_number"),'on'=>'gate_to_pay_create_card'),
            //array('passportNumber, idNumber','match','pattern' => '/^[a-z0-9]*$/', 'message' => Yii::t("main","467_icorrect_format"),'on'=>'gate_to_pay_create_card'),
            array('transferFrom, transferTo, currency, amount, creditCardId, cardExpiryDate, gate_scenario', 'required', 'on'=>'gate_to_pay_deposit', 'message'=>Yii::t("main","36_cannot_be_blank")),
            array('cardExpiryDate','match','pattern' => '/^\d{2}\/\d{2}$/', 'message' => Yii::t("main","1115_incorrect_phone_number"),'on'=>'gate_to_pay_deposit'),
            array('transferFrom, transferTo, currency, amount, ntlrAccId, ntlrSecId', 'required', 'on'=>'neteller', 'message'=>Yii::t("main","36_cannot_be_blank")),
            array('transferFrom, transferTo, currency, amount, ntlrAccId', 'required', 'on'=>'neteller2', 'message'=>Yii::t("main","36_cannot_be_blank")),
            array('transferFrom, transferTo, currency, amount, x_cpf', 'required', 'on'=>'astropay', 'message'=>Yii::t("main","36_cannot_be_blank")),
            array('amount', 'checkDepAmount', 'on'=>'neteller, neteller2'),
            array('transferFrom, transferTo, currency, amount, bank', 'required', 'on'=>'sovvipay', 'message'=>Yii::t("main","36_cannot_be_blank")),
			//ceil($MinAmmountForDeposit+($MinAmmountForDeposit*0.039)+0.29)
        /*, gate_to_pay_deposit*/
			array('amount', 'numerical', 'integerOnly'=>true, 'min' => $MinAmmountForDeposit, 'numberPattern'=>'/^\d*[\.|\,]?\d{0,2}$/', 'on'=>'neteller, neteller2', 'allowEmpty' => false, 'message'=>Yii::t("funds","530_numbers_allowed"), 'tooSmall'=>Yii::t("funds","79_amount_cant_be_null")),
			// todo uncomment minAmount next line
            array('amount', 'numerical', 'integerOnly'=>false, 'min' => $MinAmmountForDeposit, 'max' => $MaxAmmountForDeposit, 'numberPattern'=>'/^\d*[\.|\,]?\d{0,2}$/', 'on'=>'Fund, sovvipay', 'allowEmpty' => false, 'message'=>Yii::t("funds","530_numbers_allowed"), 'tooSmall'=>Yii::t("funds","79_amount_cant_be_null")),
			array('amount', 'numerical', 'integerOnly'=>false, 'min' => 50, 'numberPattern'=>'/^\d*[\.|\,]?\d{0,2}$/', 'on'=>'cardDeposit, IntTrnsfr', 'allowEmpty' => false, 'message'=>Yii::t("funds","530_numbers_allowed"), 'tooSmall'=>Yii::t("funds","79_amount_cant_be_null")),
			
			array('transferFrom, currency', 'required', 'on'=>'Withdrawal', 'message'=>Yii::t("main","36_cannot_be_blank")), 
			array('amount', 'numerical', 'integerOnly'=>false, 'min' => $MinAmountForWithdrawals, 'numberPattern'=>'/^\d*[\.|\,]?\d*$/', 'on'=>'Withdrawal', 'allowEmpty' => false, 'message'=>Yii::t("funds","530_numbers_allowed"), 'tooSmall'=>Yii::t("funds","79_amount_cant_be_null")), 
			
            array('fundsSourse, currency', 'required', 'message'=>Yii::t("main","36_cannot_be_blank"), 'on'=>'cardDeposit'), 
            array('cardId', 'required', 'message'=>Yii::t("funds","529_choose_cc"), 'on'=>'cardDeposit'), 
			array('fundsSourse', 'in', 'range' => array_keys($this->getFundsSourse()), 'message'=>Yii::t("funds","509_source_of_funds_is"), 'on'=>'cardDeposit'),
			
			array('transferTo', 'required', 'on'=>'demoDeposit', 'message'=>Yii::t("main","1083_choose_the_account")),
			array('amount', 'required', 'on'=>'demoDeposit', 'message'=>Yii::t("main","36_cannot_be_blank")),
			//array('amount', 'in', 'range' => array_keys($this->GetDemoDepositValues()), 'on'=>'demoDeposit'),
			
			array('trAccount, bonus, lotsAmount', 'required', 'on'=>'setBonus', 'message'=>Yii::t("main","36_cannot_be_blank")), 
			array('trAccount, bonus, lotsAmount', 'numerical', 'integerOnly'=>false, 'on'=>'setBonus', 'message'=>Yii::t("main","371_numbers_allowed")), 
			array('trAccount', 'length', 'min'=>1, 'max'=>12, 'tooShort'=>Yii::t("main","528_min_length_is"), 'tooLong'=>Yii::t("main","529_max_length_is"),'on'=>'setBonus', 'allowEmpty' => false),
			
			array('amount', 'required', 'on'=>'openDemo', 'message'=>Yii::t("main","36_cannot_be_blank")), 

			array('ccFullNumber', 'length', 'is'=>16, 'message'=>Yii::t("funds","534_ccn_16_length")),
			array('cvc_code', 'length', 'min'=>3, 'max'=>4, 'message'=>Yii::t("funds","504_cvc_min_max")),
			array('exp_year', 'length', 'is'=>2, 'message'=>Yii::t("funds","534_ccn_16_length")),
			array('exp_month', 'length', 'is'=>2, 'message'=>Yii::t("funds","534_ccn_16_length")),
			array('exp_month', 'numerical', 'max'=>12, 'integerOnly'=>true, 'tooBig'=>Yii::t("funds","506_month_validate")),
			array('cvc_code, exp_year', 'numerical', 'integerOnly'=>true, 'message'=>Yii::t("funds","533_ccn_must_be_number")),

			// array('transferTo', 'required', 'on'=>'recalcAmount', 'message'=>Yii::t("main","1083_choose_the_account")),
			array('amount, currency, transferTo', 'required', 'on'=>'recalcAmount', 'message'=>Yii::t("main","36_cannot_be_blank")),
        ), $isUserHasTheAccRule);
    }
	
	public function attributeLabels()
	{
		if($this->getScenario()=='IntTrnsfr'){
			return array(
			'transferFrom'=>Yii::t("funds","7_transfer_from"),
			'transferTo'=>Yii::t("funds","8_transfer_to"),
			'currency'=>Yii::t("main","146_currency"),
			'amount'=>Yii::t("funds","9_amount"),
			);
		}elseif($this->getScenario()=='Withdrawal'){
			return array(
			'transferFrom'=>Yii::t("funds","17_account_"),
			'amount'=>Yii::t("funds","9_amount"),
			);
		}elseif($this->getScenario()=='openDemo'){
			return array(
			'amount'=>Yii::t("funds","520_deposit"),
			);
		}elseif($this->getScenario()=='setBonus'){
			return array(
			'trAccount'=>Yii::t("sp","186_acccount"),
			'bonus'=>Yii::t("sp","187_bonus_amount"),
			'lotsAmount'=>Yii::t("sp","185_lots_amount"),
			);
		}else{
			return array(
			'transferFrom'=>Yii::t("funds","529_payment_method"),
			'transferTo'=>Yii::t("funds","17_account_"),
			'currency'=>Yii::t("main","146_currency"),
			'amount'=>Yii::t("funds","9_amount"),
			'fundsSourse' => Yii::t("funds",'463_funds_source'), //for deposit
			'ccFullNumber' => Yii::t("funds",'532_credit_card_number'),
			'cvc_code' => Yii::t("funds",'499_cvc'),
			'exp_month' => Yii::t("funds",'500_month'),
			'exp_year' => Yii::t("funds",'501_year'),
			'ntlrAccId' => Yii::t("funds",'603_ntlrAccId'),
			'ntlrSecId' => Yii::t("funds",'604_ntlrSecId'),
			'bank' => Yii::t("main",'387_bank'),
			'x_cpf' => Yii::t("funds",'632_cpf_etc'),
			);
		}	
		
	}

	public function lunaAlgoritm()
	{
		$s = strrev(preg_replace('/[^\d]/','',$this->ccFullNumber));

		// вычисление контрольной суммы
		$sum = 0;
		for ($i = 0, $j = strlen($s); $i < $j; $i++) {
			// использовать четные цифры как есть
			if (($i % 2) == 0) {
				$val = $s[$i];
			} else {
				// удвоить нечетные цифры и вычесть 9, если они больше 9
				$val = $s[$i] * 2;
				if ($val > 9)  $val -= 9;
			}
			$sum += $val;
		}

		// число корректно, если сумма равна 10
		if(($sum % 10) == 0){
			return true;
		}else{
			$this->addError('ccFullNumber', Yii::t("main","1045_incorrect_ccnum"));
			return false;
		}
	}
	
	public function getFundsSourse($lang = '') {
		if($lang != ''){
			$tmp_lang = Yii::app()->language;
			Yii::app()->language = 'en';
			$res = array('1'=>Yii::t("funds","458_fundsSourse1"),'2'=>Yii::t("funds","459_fundsSourse2"),'3'=>Yii::t("funds","460_fundsSourse3"),'4'=>Yii::t("funds","461_fundsSourse4"),'5'=>Yii::t("funds","462_fundsSourse5")); 
			Yii::app()->language = $tmp_lang;
		}else{
			$res = array('1'=>Yii::t("funds","458_fundsSourse1"),'2'=>Yii::t("funds","459_fundsSourse2"),'3'=>Yii::t("funds","460_fundsSourse3"),'4'=>Yii::t("funds","461_fundsSourse4"),'5'=>Yii::t("funds","462_fundsSourse5")); 
		}
		
		return $res;
    }
	
	public function getCardCurrencies(){
		$Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/getCardCurrencies');

		/*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
			var_dump($Info, Yii::app()->params['json_server'].'/API/Transactions/getCardCurrencies');die();
		}*/

		$rez = array();
		foreach($Info as $i){
			$rez[$i] = $i;
		}
		/* 
		unset($rez["USD"]);
		$e1["USD"] = "USD" ;
		$rez = array_merge($e1, $rez); */
		//if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
			$rez = array('USD'=>'USD', 'EUR'=>'EUR');
		//}

		return $rez;
	}
	
	public function bonus($amount = -1){
		$bonuses = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Accounts/GetBonuses?guid='.Yii::app()->user->id);
		if($amount==-1){return $bonuses;}
		if(count($bonuses)==1 && $bonuses->State==0){}else{
		foreach($bonuses as $bonus){
			if($amount >= $bonus->min && $amount <= $bonus->max){
				return $bonus->bonus.'='.$bonus->lots;
			}
		}
		}
		return 0;
	}
	
	public function fromAccToAcc($fromAcc, $toAcc, $ammount, $accType = 'tradingAcc', $debitedAccountType = 1){
		/* 
			debitedAccountType:	1 - from BMFN account
								2 - from Trading account
		*/
		
		$tmp_fromAcc = explode(' ',$fromAcc);
		$tmp_toAcc = explode(' ',$toAcc);
		$fromAcc = $tmp_fromAcc[0];
		$toAcc = $tmp_toAcc[0];

		
		if($accType == 'tradingAcc' || $accType==''){
			//var_dump('111', Yii::app()->params['json_server'].'/API/Transactions/UserInternalTransfer?guid='.Yii::app()->user->id.'&account='.$fromAcc.'&creditedAccount='.$toAcc.'&ammount='.$ammount);die();
			$rezult = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/UserInternalTransfer?guid='.Yii::app()->user->id.'&account='.$fromAcc.'&creditedAccount='.$toAcc.'&ammount='.$ammount);

			/*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
				var_dump($rezult , Yii::app()->params['json_server'].'/API/Transactions/UserInternalTransfer?guid='.Yii::app()->user->id.'&account='.$fromAcc.'&creditedAccount='.$toAcc.'&ammount='.$ammount);die();
			}*/

			/* if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
				var_dump('111', $rezult, Yii::app()->params['json_server'].'/API/Transactions/UserInternalTransfer?guid='.Yii::app()->user->id.'&account='.$fromAcc.'&creditedAccount='.$toAcc.'&ammount='.$ammount);die();
			}  */
        }else{
			$Account = new Account();
			$isSysAcc = $Account->isSysAccount('7932');
			if(!$Account->isSysAccount($fromAcc)){
				$tmp = $fromAcc;
				$fromAcc = $toAcc;
				$toAcc = $tmp;
			}
		
			$rezult = Yii::app()->curl->get(htmlspecialchars_decode(Yii::app()->params['json_server'].'/API/Transactions/MakeIBAccountInternalTransfer?guid='.Yii::app()->user->id.'&ibAccountId='.$fromAcc.'&tradingAccountId='.$toAcc.'&amount='.$ammount.'&debitedAccountType='.$debitedAccountType));
			/* if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
				var_dump('222', $rezult, htmlspecialchars_decode(Yii::app()->params['json_server'].'/API/Transactions/MakeIBAccountInternalTransfer?guid='.Yii::app()->user->id.'&ibAccountId='.$fromAcc.'&tradingAccountId='.$toAcc.'&amount='.$ammount.'&debitedAccountType='.$debitedAccountType));die();
			} */
			//var_dump(htmlspecialchars_decode(Yii::app()->params['json_server'].'/API/Transactions/MakeIBAccountInternalTransfer?guid='.Yii::app()->user->id.'&ibAccountId='.$fromAcc.'&tradingAccountId='.$toAcc.'&amount='.$ammount.'&debitedAccountType='.$debitedAccountType), $rezult);die();
		}
		//var_dump($rezult);die();

		if($rezult == 'NotEnoughMoneyForThisOperation'){
			$_SESSION['message'][] = array("text"=>Yii::t("funds","58_you_dont_have_enough_funds_for_transfer"),"action"=>Yii::app()->controller->id."/".Yii::app()->controller->action->id,"type"=>"error");			
		}elseif($rezult == 'TransactionAlreadyExists'){//duble transaction
            $_SESSION['message'][] = array("text"=>Yii::t("funds","563_duble_transaction"),"action"=>Yii::app()->controller->id."/".Yii::app()->controller->action->id,"type"=>"error");
        }elseif($rezult == 'AmountMustBeGreaterThanZero'){
			$_SESSION['message'][] = array("text"=>Yii::t("funds","567_AmountMustBeGreaterThanZero"),"action"=>Yii::app()->controller->id."/".Yii::app()->controller->action->id,"type"=>"error");
		}elseif($rezult == 'AccountDoesntExist'){
			$_SESSION['message'][] = array("text"=>Yii::t("funds","568_AccountDoesntExist"),"action"=>Yii::app()->controller->id."/".Yii::app()->controller->action->id,"type"=>"error");
		}elseif($rezult == 'WrongAccountsPlatformRoles'){
			$_SESSION['message'][] = array("text"=>Yii::t("funds","569_WrongAccountsPlatformRoles"),"action"=>Yii::app()->controller->id."/".Yii::app()->controller->action->id,"type"=>"error");
		}elseif($rezult == 'NoNeedPendingTransaction'){
			$_SESSION['message'][] = array("text"=>Yii::t("funds","575_internal_transfer_success", array('{from}'=>$fromAcc, '{to}'=>$toAcc)),"action"=>Yii::app()->controller->id."/".Yii::app()->controller->action->id,"type"=>"success");
		}elseif($rezult == 'AccountHasOpenPositionsNotEnoughMoney'){
			$_SESSION['message'][] = array("text"=>Yii::t("funds","617_AccountHasOpenPositionsNotEnoughMoney"),"action"=>Yii::app()->controller->id."/".Yii::app()->controller->action->id,"type"=>"error");
		}elseif(($accType == 'tradingAcc' && ((isset($rezult->State) && $rezult->State==0) || $rezult == 'NeedPendingTransaction')) || ($accType != 'tradingAcc' && (is_string($rezult) || $rezult->State==0 || $rezult == 'NeedPendingTransaction'))){
			$_SESSION['message'][] = array("text"=>Yii::t("funds","78_request_for_transfer"),"action"=>Yii::app()->controller->id."/".Yii::app()->controller->action->id,"type"=>"success");
		}else{
			$_SESSION['message'][] = array("text"=>Yii::t("funds","54_transaction_from_account_").$fromAcc." ".Yii::t("funds","55_to_account")." ".$toAcc." ".Yii::t("funds","56_was_failed"),"action"=>Yii::app()->controller->id."/".Yii::app()->controller->action->id,"type"=>"error");
		}
		return $rezult;
	}
	
	public function getBanksInfo(){
		$rezult = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Accounts/GetBanksCompanyInfo?guid='.Yii::app()->user->id);
		//var_dump(Yii::app()->params['json_server'].'/API/Accounts/GetBanksCompanyInfo?guid='.Yii::app()->user->id, $rezult);die();

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            var_dump($rezult, Yii::app()->params['json_server'].'/API/Accounts/GetBanksCompanyInfo?guid='.Yii::app()->user->id);die();
        }*/

        // arsen 8/10/20
        /*if($_SERVER['SERVER_NAME'] === 'my.swissfs.com'){
            $rezult = [];
        }*/




		return $rezult;
	}
	
	public function getAvaliablesBanksForUser(){
		$rezult = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Accounts/GetAvaliablesBanksForUser?guid='.Yii::app()->user->id);
		/* if($_SERVER['REMOTE_ADDR']=='77.222.143.18'){
		var_dump(Yii::app()->params['json_server'].'/API/Accounts/GetAvaliablesBanksForUser?guid='.Yii::app()->user->id, $rezult);die();
			
		} */
		return $rezult;
	}
	public function getBankInfo($name, $curency){
		$rezult = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Accounts/GetBankInfo?guid='.Yii::app()->user->id.'&curency='.$curency.'&name='.$name);
		return $rezult;
	}
	
	
	public function GetAddressForWithdrawal(){
		$rezult = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/GetAddressForWithdrawal?guid='.Yii::app()->user->id);
	//	var_dump($rezult);die();
		return $rezult;
	}

	public function ChangeUserAgreeBonusState($state = 'true', $login = -1){
		if($login == -1){
			$user = new Registration();
			$user->initIndv();	
			$id = $user->id;			
		}else{		
			$id = -1;
		}
		//var_dump(Yii::app()->params['json_server'].'/API/Registration/ChangeUserAgreeBonusState?guid='.Yii::app()->user->id.'&id='.$id.'&agree='.$state.'&userLogin='.$login);
		$rezult = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/ChangeUserAgreeBonusState?guid='.Yii::app()->user->id.'&id='.$id.'&agree='.$state.'&userLogin='.$login);
		//var_dump($rezult);
		return $rezult;
	}
	public function GetBonusSetting(){
		$rezult = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Accounts/GetBonusGroupLevel?guid='.Yii::app()->user->id);
		//var_dump(Yii::app()->params['json_server'].'/API/Accounts/GetBonusGroupLevel?guid='.Yii::app()->user->id, $rezult);die();
		return $rezult;
	}
	public function GetSetting($key){ 
		# key = (WebMoneyKey)
		//var_dump(Yii::app()->params['json_server'].'/API/Accounts/GetSetting?guid='.Yii::app()->user->id.'&key='.$key);
		$rezult = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Accounts/GetSetting?guid='.Yii::app()->user->id.'&key='.$key);
		//var_dump($rezult);die();
		return $rezult;
	}
	public function makeDemoDeposit($accountID = '0', $amount = '100000'){

        $rezult = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Accounts/DemoAccountDeposit?guid='.Yii::app()->user->id.'&accountID='.$accountID.'&value='.$amount);
        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            var_dump($rezult, Yii::app()->params['json_server'].'/API/Accounts/DemoAccountDeposit?guid='.Yii::app()->user->id.'&accountID='.$accountID.'&value='.$amount);die();
        }*/

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            var_dump($rezult, Yii::app()->params['json_server'].'/API/Accounts/DemoAccountDeposit?guid='.Yii::app()->user->id.'&accountID='.$accountID.'&value='.$amount);
        }*/

        return $rezult;
	}
	
	public function paymentSkrill($transferTo, $amount, $currency = 'USD'){
		$Registration = new Registration('Individual');
		$Registration->initIndv();	
		$_d =explode("/",$Registration->birthday);
		$birth = $_d[1].$_d[0].$_d[2];
		$countries_code_three = $Registration->GetCountry('three');
		$lang = (in_array(strtoupper(Yii::app()->language), self::$skrill_lang)) ? Yii::app()->language : 'EN';
	
		$post_data['type'] = 'skrill';
		$post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
		$post_data['action'] = 'https://www.moneybookers.com/app/payment.pl';
		$post_data['data']['pay_to_email'] = 'ips@bmfn-solutions.com';
		$post_data['data']['transaction_id'] = uniqid();
		$post_data['data']['return_url'] = 'http://'.$_SERVER["SERVER_NAME"].'/skrillTrans.html?isUser&success';
		$post_data['data']['return_url_target'] = '3';
		$post_data['data']['cancel_url'] = 'http://'.$_SERVER["SERVER_NAME"].'/skrillTrans.html?isUser&cancel';
		$post_data['data']['cancel_url_target'] = '3';
		$post_data['data']['status_url'] = 'http://'.$_SERVER["SERVER_NAME"].'/skrillTrans.html'; 
		$post_data['data']['status_url2'] = Yii::app()->params['paymentsEmail']; 
		$post_data['data']['language'] = $lang;
		$post_data['data']['logo_url'] = 'https://my.bmfn-solutions.com/assets/img/'.str_replace(' ', '_', Yii::app()->params['name_company']).'.png';
		//$post_data['data']['logo_url'] = Yii::app()->params['mail_logo'];
		// prepare_only ????????
		// rid 			????????
		
		$post_data['data']['pay_from_email'] = $Registration->email;
		$post_data['data']['firstname'] = $Registration->firstName;
		$post_data['data']['lastname'] = $Registration->lastName;
		$post_data['data']['date_of_birth'] = $birth;
		$post_data['data']['address'] = $Registration->address;
		$post_data['data']['address2'] = $Registration->city;
		
		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';
			}
		}
		
		$post_data['data']['country'] = $country_code;
		$post_data['data']['amount'] = $amount;
		$post_data['data']['currency'] = $currency;	
		$post_data['data']['payment_methods'] = 'SFT,PWY,PLI,NPY,ENT,GIR,GCB,SLO,MAE,DIN,AMX,MSC,VSA,ACC,PWY32,';

		
		
		
		$post_data['data']['recipient_description'] = Yii::app()->params['name_company'];
		$post_data['data']['detail1_text'] = Yii::t("funds","433_payment_through_skrill");
		$post_data['data']['pm'] = 'PWY36';
		preg_match('/\((.*)\)/', $transferTo, $currency);
		$post_data['data']['detail1_description'] = $transferTo;
		
		return $post_data;
	}
	
	/* public function paymentCashu($transferTo, $amount){
		$Registration = new Registration('Individual');
		$Registration->initIndv();	
		
		$post_data['type'] = 'cashu';
		$post_data['enc_key'] = '956ee5ffc2119e49c56bc5d33bf'; 										
		$post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");	
		$post_data['action'] = 'https://www.cashu.com/cgi-bin/pcashu.cgi';
		$post_data['data']['merchant_id'] = 'BMFNARAB'; 								
		$post_data['data']['amount'] = $amount;
		preg_match('/(\d+).*\((.*)\)/', $transferTo, $account_currency);
		$post_data['data']['currency'] = $account_currency[2];									
		$post_data['data']['language'] = Yii::app()->request->cookies['language']->value;
		$post_data['data']['display_text'] = Yii::app()->params['name_company']; 
		$post_data['data']['servicesName'] = 'Deposit_Funds_bmfn.com'; 
		$post_data['data']['text1'] = $account_currency[1]; 
		$post_data['data']['text2'] = $Registration->email; 
		$post_data['data']['text3'] = $Registration->firstName.' '.$Registration->lastName; 
		$post_data['data']['text4'] = $Registration->address.'-'.$Registration->city.'-'.$Registration->country; 
		$post_data['data']['text5'] = $account_currency[2].'-'.$amount;
		$post_data['data']['session_id'] = sha1(date('Y-m-d H:i:s').$Registration->email.$account_currency[1].$account_currency[2].$amount);	
		$post_data['data']['display_text'] = Yii::t("funds","447_thank_u_for_deposit");			
		$post_data['data']['txt1'] = $transferTo;
		$post_data['data']['token'] = md5(strtolower($post_data['data']['merchant_id'].':'.$post_data['data']['amount'].':'.$post_data['data']['currency'].':'.$post_data['enc_key']));
		$post_data['data']['test_mode'] = '0';	
	
		return $post_data;
	} */
	
	/* public function paymentDcpay($transferTo, $amount){
		$Registration = new Registration('Individual');
		$Registration->initIndv();	
		$countries_code_two = $Registration->GetCountry('two');
		$partner_control = 'aac9fe064ba3c8ac1a6d4b2f3bd8b632';
	
		$post_data['type'] = 'dcpay';
		$post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
		$post_data['action'] = 'https://payment.ccp.dcpay.biz/ChinaDebitCard';
		$post_data['data']['apiversion'] = '3'; 	  
		$post_data['data']['version'] = '11';	 
		$tstring = $post_data['data']['merchant_account'] = '567654543';  //567654368	//567654543
		$tstring .= $post_data['data']['amount'] = (int)$amount*100; 
		preg_match('/\((.*)\)/', $transferTo, $currency);
		$tstring .= $post_data['data']['currency'] = 'CNY';//$currency[1];              #illya ask
		$tstring .= $post_data['data']['first_name'] = $Registration->firstName.' '.$Registration->lastName; 
		$tstring .= $post_data['data']['last_name'] = (int)$transferTo; 
		$tstring .= $post_data['data']['address1'] = $Registration->address; 
		$tstring .= $post_data['data']['city'] = $Registration->city; 
		$tstring .= $post_data['data']['zip_code'] = (!empty($Registration->zipcode)) ? $Registration->zipcode : '1000'; 
		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';
			}
		}
		$tstring .= $post_data['data']['country'] = $country_code;//$countries_code[$Registration->country];  						 # function from sonin
		$tstring .= $post_data['data']['phone'] = $Registration->phone; 
		$tstring .= $post_data['data']['email'] = $Registration->email; 
		$tstring .= $post_data['data']['merchant_order'] = mt_rand(10000,99999); 
		$tstring .= $post_data['data']['merchant_product_desc'] = $transferTo; 
		$tstring .= $post_data['data']['return_url'] = 'http://'.$_SERVER["SERVER_NAME"].'/funds/deposit.html?response'; 
		$post_data['data']['ipaddress'] = $_SERVER["REMOTE_ADDR"];	
		//$post_data['data']['partner_control'] = 'aac9fe064ba3c8ac1a6d4b2f3bd8b632';	
		$post_data['data']['server_return_url'] = 'http://'.$_SERVER["SERVER_NAME"].'/dcpayTrans.html'; 
		$post_data['data']['control'] = hash_hmac('SHA1', $tstring ,$partner_control); 	
		//var_dump($post_data);die();
	
		return $post_data;
	} */
	
	/* public function paymentDinpay($transferTo, $amount){
		//{"@type":"java.util.HashMap","bank_seq_no":"1697703007","extra_return_param":"Qinjun Zhang,77335271,kewang2787023@163.com,15121036930,6013820800074277474,BOC","interface_version":"V3.0","merchant_code":"2060000203","notify_id":"3f74e51287ac4dc2bc85b0e846c805cb","notify_type":"offline_notify","order_amount":"16000","order_no":"E417636580745688","order_time":"2015-04-17 17:40:58","sign":"17cf0fa4caea5a65714bae5d8a6dc802","sign_type":"MD5","trade_no":"1038089181","trade_status":"SUCCESS","trade_time":"2015-04-17 17:47:18"}
		
		
		$post_data['type'] = 'dinpay';
		$post_data['key'] = '123456789a123456789_';  //cae32b278bced934a54f27545 //123456789a123456789_
		$post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
		$post_data['action'] = 'https://pay.dinpay.com//gateway?input_charset=UTF-8'; 			//https://pay.dinpay.com//gateway?input_charset=UTF-8	 
		$post_data['data']['merchant_code'] = '1111110166';	//1111110166	//2060000203						
		$post_data['data']['service_type'] = 'direct_pay';										
		$post_data['data']['input_charset'] = 'UTF-8';												
		$post_data['data']['notify_url'] = 'http://'.$_SERVER["SERVER_NAME"].'/dinpayTrans.html'; //http://www.bmfn.cn/dinpay/DinpayToMer_notify.php
		$post_data['data']['interface_version'] = 'V3.0';											
		$post_data['data']['sign_type'] = 'MD5';											
		$post_data['data']['order_no'] = mt_rand();	
		$post_data['data']['order_time'] = date("Y-m-d H:i:s");	
		preg_match('/(\d+).*\((.*)\)/', $transferTo, $account_currency);								
		$post_data['data']['product_name'] = $account_currency[1];	
		$post_data['data']['order_amount'] = $amount;	

		$post_data['data']['client_ip'] = '';											 
		$post_data['data']['extend_param'] = '';											 
		$post_data['data']['extra_return_param'] = '';											 
		$post_data['data']['product_code'] = '';											 
		$post_data['data']['product_desc'] = '';											 
		$post_data['data']['product_num'] = '';		
		$post_data['data']['return_url'] = '';											 
		$post_data['data']['show_url'] = '';	
		

		ksort($post_data['data']);
		reset($post_data['data']);
		$string = '';
		foreach($post_data['data'] as $key=>$elem){
			if($elem == end($post_data['data']) && ($key=='sign' ||$key=='sign_type' || $elem=='')){$string .= 'key='.$post_data['key'];	}
			if($key=='sign' ||$key=='sign_type' || $elem=='') continue;
			$string .= $key.'='.mb_convert_encoding($elem, "UTF-8", "UTF-8").'&';	
			if($elem == end($post_data['data'])){
				$string .= 'key='.$post_data['key'];	
			}									
		}
		
		$post_data['data']['sign'] = md5($string);
		
		return $post_data;
	} */
	
	public function paymentWebmoney(){
		if(wlParams::get('webmoney_allow')){
			if(wlParams::get('webmoney_acc') == ''){
				$WebMobeyAcc = $this->GetSetting('WebMoneyKey');
			}else{
				$WebMobeyAcc = wlParams::get('webmoney_acc');
			}
		}
		$post_data['type'] = 'webmoney';
		$post_data['message'] = Yii::t("funds","451_you_will_redir_secure_payment_webmoney", array('{purseNumber}'=>'(<span style="color:red;">'.$WebMobeyAcc.'</span>)'));
		$post_data['action'] = 'http://www.wmtransfer.com/'; 	
	
		return $post_data;
	}
	
	/*public function paymentChinaUnion($transferTo, $amount){
		$Registration = new Registration('Individual');
		$Registration->initIndv();	
	
		$ipsno = 'chinaunion';
		$gets["payment_method"] = 'apmgw_UnionPay';
		$gets["transferTo"] = $transferTo;
		$gets["amount"] = (isset($amount) && !empty($amount)) ? $amount : '';
		$gets["country"] = $Registration->country;
		$gets = array($ipsno, 'http://bmfnuk.com/mainpages/deposit/ccform.html?'.http_build_query($gets));
		//var_dump($gets);die();
		return $gets;
	}*/
	
	public function paymentInatec($transferTo, $amount, $cardno, $postRegistration, $trCode, $ccFullNumber, $cvc_code, $exp_month, $exp_year){
		$Account= new Account();
        $getInfo = $Account->GetInfo();




		$Registration = new Registration('Individual');
		$Registration->initIndv();	
		if($getInfo->Type==6 && $getInfo->GroupType==2){
			$Trader = new RegistrationTrader('Corporate');
			$Trader->initTrader();
			$Registration->firstName = $Trader->representativeFirstName;
			$Registration->lastName = $Trader->representativeLastName;
			
		}elseif($getInfo->Type==6 && $getInfo->GroupType==3){
			$Trader = new RegistrationTrader('Join');
			$Partners = $Trader->initPartner();
			$Part = array_shift($Partners);
			$Registration->attributes = (array)$Part;

			/* $Registration->firstName = $Trader->representativeFirstName;
			$Registration->lastName = $Trader->representativeLastName; */		
		}



		$countries_code_three = $Registration->GetCountry('three');


		$pay_type = ($postRegistration["ipsno"] == '') ? $postRegistration["cardno"] : $postRegistration["ipsno"];

		if($ccFullNumber == 'frame'){
			$inatec = new InatecForm($ccFullNumber);
		}elseif($pay_type == 'inatec'){
			$inatec = new InatecForm('card');
		}else{
			$inatec = new InatecForm();
		}


		$customer = explode(' ', $transferTo);
		$arrInatec = array();

		$arrInatec['email'] = $Registration->email;



		if(isset($postRegistration["userName"])){
			$name = explode(' ', $postRegistration["userName"]);
		}
		if(isset($name[0]) && isset($name[1])){
			$arrInatec['firstname'] = $postRegistration["userName"]; //$name[0];
			$arrInatec['surname'] = $postRegistration["userName"]; //$name[1]; 
		}else{
			$arrInatec['firstname'] = $Registration->firstName;
			$arrInatec['surname'] = $Registration->lastName; 
		}



		$arrInatec['total_amount'] = $amount;
		$arrInatec['currency'] = $postRegistration['currency'];//substr($customer[1], 1, 3);

		$arrInatec['customerid'] = $customer[0]; //Transfer To

		$arrInatec['B_addresst'] = (isset($postRegistration['address'])) ? str_replace('+', ' ', $postRegistration['address']) :  str_replace('+', ' ', $Registration->address);
		$arrInatec['B_city'] = (isset($postRegistration['city'])) ? $postRegistration['city'] : $Registration->city;
		$countryTmp = (isset($postRegistration['country'])) ? $postRegistration['country'] : $Registration->country;
		//$arrInatec['B_postCode'] = $postRegistration['zipCode'];



		if(isset($countries_code_three[$countryTmp])){
			$country_code = $countries_code_three[$countryTmp];
		}else{
			if($countryTmp==''){
				$country_code = 'CHN';
			}else{
				preg_match('/(.*)\(/', $countryTmp, $matches);
				if(isset($countries_code_three[$matches[1]])){
					$country_code = $countries_code_three[$matches[1]];
				}else{
					$country_code = 'CHN';
				}
			}
		}
		
		$arrInatec['B_country'] = $country_code; 
		$arrInatec['order_id'] = $trCode;
		$arrInatec['cvc_code'] = $cvc_code;
		$arrInatec['exp_month'] = $exp_month;
		$arrInatec['exp_year'] = $exp_year;
		$arrInatec['ccFullNumber'] = $ccFullNumber;
		

		$inatec->attributes = $arrInatec;
		//var_dump($inatec->attributes, $inatec->validate(), $inatec->getScenario(), $inatec->getErrors());die();


		/*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
			var_dump($inatec->attributes, $inatec->validate());die();
		}*/


		if ($inatec->validate()) {

			if($inatec->getScenario() == 'frame'){
				return $inatec->frameDeposit();
			}else{
				$res = $inatec->getInatecParams($pay_type);
			}

			/* if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
				var_dump('222',$arrInatec, $res);die();
			} */
			
			
			if ($res['isError']=='') {
				if($pay_type == 'inatec'){
					$gets=array($cardno, 'inatec_params'=>$res);
					/*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
						var_dump($gets);die();
					}*/
				}else{
					$res1["action"] = $res["redirect_url"]; 
					$res1["type"] = $res["type"]; 
					$res1["message"] = $res["message"]; 
					$res1["amount"] = $arrInatec['total_amount'];
					$res1["data"] = $res;
					$res1["data"]["currency"] = $arrInatec['currency'];
					$res1["data"]["currency"] = $arrInatec['currency'];
					$res1["data"]["transferTo"] = $arrInatec['customerid'];
					$gets = $res1;
				}
			} else { 
				$_SESSION['message'][] = array("text" => $res['isError'].', '.Yii::t("main", "961_inatec_error"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
				$gets = '';
			}
		}else{
			$inErrors = $inatec->getErrors();
			$firstError = current($inErrors);
			$_SESSION['message'][] = array("text" => Yii::t("funds", "457_deposit_error").' '.Yii::t("funds", "535_error_message").': "'.$firstError[0].'"', "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
			$gets = '';			
		}		
		return $gets;
	}
	
	/*public function paymentSafecharge($transferTo, $amount, $cardno, $country, $trCode){
		$gets["payment_method"] = 'cc_card';
		$gets["transferTo"] = $transferTo;
		$gets["amount"] = (isset($amount) && !empty($amount)) ? $amount : '';
		$gets["country"] = $country;
		$gets["merchant_unique_id"] = $trCode;
		$gets = array($cardno, 'http://bmfnuk.com/mainpages/deposit/ccform.html?'.http_build_query($gets));
	
		return $gets;
	}*/
	
	public function sendPdfLink($fileLink, $useDockUrl = 'false', $FileName = '123.pdf', $fileType, $additionalInfo=''){
		//var_dump($fileLink);die();
		//var_dump(Yii::app()->params['json_server'].'/API/Registration/saveFile?guid='.Yii::app()->user->id.'&fileName='.$FileName.'&useDockURL='.$useDockUrl.'&fileLink='.rawurlencode($fileLink).'&fileType='.$fileType.'&additionalInfo='.$additionalInfo);
		$Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/saveFile?guid='.Yii::app()->user->id.'&fileName='.$FileName.'&useDockURL='.$useDockUrl.'&fileLink='.rawurlencode($fileLink).'&fileType='.$fileType.'&additionalInfo='.$additionalInfo);
		//var_dump($Info);die();
		return $Info;
	}
	
	public function IBWithdrawalRequest($account, $amount, $currency, $accType = 'tradingAcc'){
		if($accType == 'tradingAcc'){
			//var_dump(Yii::app()->params['json_server'].'/API/Transactions/IBWithdrawalRequest?guid='.Yii::app()->user->id.'&accountID='.$account.'&ammount='.$amount.'&currency='.$currency);
			$Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/IBWithdrawalRequest?guid='.Yii::app()->user->id.'&accountID='.$account.'&ammount='.str_replace(',', '',$amount).'&currency='.$currency.'&categoryID='.$this->categoryID);
			//var_dump(Yii::app()->params['json_server'].'/API/Transactions/IBWithdrawalRequest?guid='.Yii::app()->user->id.'&accountID='.$account.'&ammount='.$amount.'&currency='.$currency, $Info);
			//var_dump($Info);die();



		}else{
			//var_dump(Yii::app()->params['json_server'].'/API/Transactions/MakeIBAccountWithdrawal?guid='.Yii::app()->user->id.'&accountId='.$account.'&amount='.$amount);
			$Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/MakeIBAccountWithdrawal?guid='.Yii::app()->user->id.'&accountId='.$account.'&amount='.str_replace(',', '',$amount));
			//var_dump($Info);die(); 
			//var_dump(Yii::app()->params['json_server'].'/API/Transactions/MakeIBAccountWithdrawal?guid='.Yii::app()->user->id.'&accountId='.$account.'&amount='.$amount, $Info);
		}
		
		return $Info;
	}
	
	public function isUserHasTheAcc($attribute,$params){
		$Account = new Account();
		$accs = $Account->GetAccount();
		$isWL = $Account->IsWhiteLabel();
		
			foreach($accs as $platform){
				foreach($platform as $acc){
					// (!$isWL || ($isWL && $this->getScenario() != 'IntTrnsfr'))
					if((int)$acc->AccountNum == (int)$this->$attribute){
						if($isWL && $this->getScenario() == 'IntTrnsfr' && (int)$acc->PlatformType==5){
							$this->addError($attribute, $this->getAttributeLabel($attribute).' '.Yii::t("funds","580_only_live_accs_allowed"));
						}elseif($params['isDemo'] && ((int)$acc->PlatformType!=5 && (int)$acc->PlatformType!=6 && (int)$acc->PlatformType!=8)){
							$this->addError($attribute, $this->getAttributeLabel($attribute).' '.Yii::t("funds","527_is_not_demo"));
						}elseif(!$params['isDemo'] && (int)$acc->PlatformType==5 && (int)$acc->PlatformType!=1 && (int)$acc->PlatformType!=7){
							$this->addError($attribute, $this->getAttributeLabel($attribute).' '.Yii::t("funds","528_is_not_live"));
						}

						return;
					}		
				}
			}
			
			if($attribute == 'transferTo' && $isWL && wlParams::get('officeCode')!=22){
				$sysAccs = $Account->GetSysAccount();
				foreach($sysAccs as $acc){
					if((int)$acc->AccountNum == (int)$this->$attribute){
						$this->addError('transferTo', 'Transfers to '.Yii::app()->params['name_company'].' accounts are temporarily disabled');
						return;
					}		
				}
			}
			
			if($params['sysAccs'] || $isWL){
				$sysAccs = $Account->GetSysAccount();
				foreach($sysAccs as $acc){
					if((int)$acc->AccountNum == (int)$this->$attribute){
						return;
					}		
				}
			}
			
			if($isWL && $this->getScenario() == 'IntTrnsfr'){
				$Report = new Report(3);
				$Report->filter = (int)$this->$attribute;
				$Report->SendRequest();	
				if(count($Report->listReport) == 1){
					return;
				}	
				/* if(is_array($Report->listReport) && count($Report->listReport)>0){
					foreach($Report->listReport as $trAcc){
						if((int)$this->$attribute == (int)$trAcc->Login){
							return;
						}
					}
				} */
			}
		//var_dump('111313112312', $isWL, $this->getScenario() == 'IntTrnsfr', $acc->AccountNum, $Report->listReport);die();
		$this->addError($attribute, Yii::t("funds","526_such_acc_dnt_exist"));
	}
	
	public function GetDemoDepositValues(){
		$values = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Accounts/GetDemoDepositValues?guid='.Yii::app()->user->id);


        $tmp = array();
		if(is_array($values) || is_object($values)){ 
			foreach($values as $value){
				$tmp[$value] = '$'.$value;
			}
		}
		
		return $tmp;
	}	
	
	public function checkDepAmount($attribute,$params){
		//$this->ips

        if(wlParams::get('officeCode')==13){
            if(in_array(array_search($this->transferFrom, $this->ips), array('skrill', 'neteller'))){
                if($this->amount < 1000 && $_SERVER['REMOTE_ADDR'] != '95.34.104.222' && $_SERVER['REMOTE_ADDR'] != '77.222.143.18'){
                    $this->addError('amount', Yii::t("funds","79_amount_cant_be_null", array('{min}'=>1000)));
                }
            }
        }

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            var_dump($this->transferFrom);die();
        }*/


        if($this->transferFrom === 'USDT Transfer' && $this->amount < 100) {
            $this->clearErrors();
            $this->addError('amount', Yii::t("funds","79_amount_cant_be_null", array('{min}'=>100)));
            return false;
        }

        if(wlParams::get('officeCode')==80 || wlParams::get('officeCode')==60) {


            if($this->transferFrom == 'TotalPay' ){
                if($this->currency == 'AED' && $this->amount > 25000){
                    $this->addError('amount', Yii::t("funds","584_max_sum_allowed", array('{max}'=>25000)));
                    return false;
                }elseif($this->currency == 'USD' && $this->amount > 6500){
                    $this->addError('amount', Yii::t("funds","584_max_sum_allowed", array('{max}'=>6500)));
                    return false;
                }
            }elseif($this->transferFrom == 'PayMob'){
                if($this->currency == 'AED' && $this->amount > 15000){
                    $this->addError('amount', Yii::t("funds","584_max_sum_allowed", array('{max}'=>15000)));
                    return false;
                }elseif($this->currency == 'USD' && $this->amount > 3800){
                    $this->addError('amount', Yii::t("funds","584_max_sum_allowed", array('{max}'=>3800)));
                    return false;
                }
            }elseif(isset($this->noorcards['network'][0]) && $this->noorcards['network'][0] == $this->transferFrom){
                if($this->currency == 'AED' && $this->amount > 40000){
                    $this->addError('amount', Yii::t("funds","584_max_sum_allowed", array('{max}'=>40000)));
                    return false;
                }elseif($this->currency == 'USD' && $this->amount > 10000){
                    $this->addError('amount', Yii::t("funds","584_max_sum_allowed", array('{max}'=>10000)));
                    return false;
                }
            }
        }


		
		if(!empty($this->transferFrom) && !empty($this->amount)){
			if(array_search($this->transferFrom, $this->ips) == 'dcpay'){
				if($this->currency == 'USD' && $this->amount > 7000){
					$this->addError('amount', Yii::t("funds","584_max_sum_allowed", array('{max}'=>7000)));
					return false;
				}elseif(($this->currency == 'CNY' || $this->currency == 'CNH') && $this->amount > 50000){
					$this->addError('amount', Yii::t("funds","584_max_sum_allowed", array('{max}'=>50000)));
					return false;
				}
			}

            $ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
            if ($ip !== '162.13.154.241') {
                if($this->currency == 'VND' && $this->amount < 1200000){
                    $this->addError('amount', Yii::t("funds","79_amount_cant_be_null", array('{min}'=>1200000)));
                    return false;
                }elseif($this->transferFrom == 'IndiaCashDeposit' && $this->currency == 'INR' && $this->amount < 500000){
                    $this->addError('amount', Yii::t("funds","79_amount_cant_be_null", array('{min}'=>500000)));
                    return false;
                }elseif($this->transferFrom == 'UPIicici' && $this->currency == 'INR' && $this->amount < 1000){
                    $this->addError('amount', Yii::t("funds","79_amount_cant_be_null", array('{min}'=>1000)));
                    return false;
                }elseif($this->currency == 'INR' && $this->amount < 3500){
                    $this->addError('amount', Yii::t("funds","79_amount_cant_be_null", array('{min}'=>3500)));
                    return false;
                }elseif($this->currency == 'SAR' && $this->amount < 100){
                    $this->addError('amount', Yii::t("funds","79_amount_cant_be_null", array('{min}'=>100)));
                    return false;
                }elseif($this->currency == 'AED' && $this->amount < 200){
                    $this->addError('amount', Yii::t("funds","79_amount_cant_be_null", array('{min}'=>200)));
                    return false;
                }elseif($this->currency == 'TRC20_USDT' && $this->amount < 100){
                    $this->addError('amount', Yii::t("funds","79_amount_cant_be_null", array('{min}'=>100)));
                    return false;
//                }elseif($this->currency == 'KWD' && $this->amount < 150){
//                    $this->addError('amount', Yii::t("funds","79_amount_cant_be_null", array('{min}'=>150)));
//                    return false;
                }
                // todo uncomment minAmount
            }

		}


	}
	
	
	public function checkAmount($attribute,$params){
	
		if(!empty($this->transferFrom) && !empty($this->amount)){
			$Account = new Account();
			$info = $Account->getInfo();
			if($info->Code == 6722){
				if($this->amount > 1000){
					$this->addError('amount', Yii::t("funds","584_max_sum_allowed", array('{max}'=>1000)));
				}
			}elseif(wlParams::get('officeCode') == 80){
                $ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
                if ($ip == '46.211.108.157') {
                    var_dump($attribute,$params);die();
                }
            }else{
				if($info->Type == 4){					
					$sysAccounts = $Account->GetSysAccount();
					$isSys = false;
					foreach($sysAccounts as $sys){
						if($sys->AccountNum == abs($this->transferFrom)){
							$isSys = true;
							break;
						}
					}

					if($this->amount < $this->MinAmmountForIBAccountInternalTransfer && $isSys){
						$this->addError('amount', Yii::t("funds","79_amount_cant_be_null", array('{min}'=>$this->MinAmmountForIBAccountInternalTransfer)));
					}					
				}
			}
		}
	}
	
	public function GetClientTransactions(){
		$result = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/GetClientTransactions?guid='.Yii::app()->user->id);
		
		
		return $result;
	}

	public function RecalculateAmount(){
		$result = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/RecalculateAmount?guid='.Yii::app()->user->id.'&accountId='.$this->transferTo.'&depositCurrency='.$this->currency.'&ammount='.$this->amount);

		return $result;
	}
	
}


