<?php

class Registration extends CFormModel
{
	private $_identity;
/*
 * Registration lvl 1 (user,Ib)
 * Conditions
 * Ib Registration
 * 
 * Get Counrty
 */     

    
    
        
    public $code= -1; //код от кого регистрация - код а не id
    public $role= -1; /*Office = 2,Sales = 3,Broker = 4*/
    public $id= -1; // id для update
	public $Source = 8; // 8 - PC
    //--------------------------------------------------------------
    public $firstName;
    public $lastName;
    public $birthday;
    public $email;
    public $phone;
    public $country;
	public $groupType = '1'; // Corporate/Individual/joint
	public $idNum;
	public $parentId;
	public $additionalInfo;
	public $capchaText;

    public $password;
    

    //--------
    public $city = '';
    public $address = '';
    public $zipcode = '';
    //--------------------------------------------------------------

    //public $Bank = array();
    //public $Corporate = array();

    //--------------------------------------------------------------
    public $userType = -1;
    public $agreementTerms=0;
    public $agreeBonus=false;

	public $leverage;
    public $accountGroup = '';

		
    public function rules(){

		$model=new Registration('registration');
		$Lead = new Lead();
		$sources = $Lead->getStaticArray('Source');

			#Incorrect phone number 	
		return array(	 	
			//array('test', 'required', 'on'=>'registration', 'message' => Yii::t("main","1066_illegal_characters")),


			array('firstName, lastName', 'match','pattern' => '/^[a-z\-\'\.\s]*$/i', 'on'=>'registration', 'message' => Yii::t("main","1066_illegal_characters")),

            //array('firstName', 'compare','compareAttribute' => 'lastName', 'operator' => '!==', 'on'=>'registration', 'message' => Yii::t("main","1071_error_occurred")),

			array('password','whenPassOnRegAllow','on'=>'registration'),

			array('birthday','comparedates','on'=>'Individual, registration'),
			array('birthday','required','on'=>'registration'),
			array('capchaText', 'required', 'on'=>'registration, Individual, registrationCorp', 'message'=> Yii::t("main","36_cannot_be_blank")),
			array('firstName, phone, lastName, email, groupType, birthday', 'required', 'on'=>'registration', 'message'=> Yii::t("main","36_cannot_be_blank")),
			array('firstName, phone, lastName, email, email, birthday, city, address', 'required', 'on'=>'Individual','message'=> Yii::t("main","36_cannot_be_blank")),
			array('country', 'required', 'on'=>'Individual','message'=>Yii::t("main","370_choose_the")),
			array('firstName, lastName, phone, email', 'in', 'range' => array('Admin', 'root', Yii::t("main","27_first_name"), Yii::t("main","28_last_name"),'Administrator',Yii::t("main","130_phone"),Yii::t("main",'560_main_phone'),Yii::t("main","131_email"),Yii::t("main",'559_main_email')),'not'=>true,'message' => Yii::t("main","36_cannot_be_blank"), 'on'=>'Individual, registration'),
            array('firstName, phone, lastName, birthday, email, country, capchaText'  , 'length', 'min'=>1, 'max'=>255,'on'=>'registration', 'tooShort'=> Yii::t("main","36_cannot_be_blank")),
			array('firstName, phone, lastName, birthday, email, address, city, capchaText', 'length', 'min'=>1, 'max'=>255,'allowEmpty'=>true,'on'=>'Individual'),
			array('email' , 'email', 'on'=>'Individual, registration','message' => Yii::t("main","22_this_email_address_is_not_a_valid")),
			//array('', 'match','pattern' => '/^[a-zA-Z\s]*$/i','message' => Yii::t("main","34_only_latin_characters_allowed_for"), 'on'=>'Individual, registration'),
			array('firstName, lastName, city, address, additionalInfo', 'match','pattern' => '/^[a-z0-9`~!"@№%#\$;:\?\/\\&\*\+-_\(\)=\{\}\[\]\'|\s]*$/i','message' => Yii::t("main","34_only_latin_characters_allowed_for"), 'on'=>'Individual, registration'),

            array('password','checkUserInfo','on'=>'registration'),

            array('firstName, lastName', 'length', 'min'=>2, 'max'=>255, 'allowEmpty'=>false, 'tooLong' => Yii::t("main","529_max_length_is"), 'tooShort' => Yii::t("main","528_min_length_is")),
            array('country', 'in', 'range' => $model->GetCountry()), //проверка на страны
			//array('firstName, lastName','match','pattern' => '/^\D*$/','message' => Yii::t("main","33_numbers_are_not_allowed_in")),
			array('phone','match','pattern' => '/^\+?\d+$/', 'message' => Yii::t("main","35_incorrect_phone_number"),'on'=>'registration, Individual'),
			array('birthday', 'type', 'type' => 'date', 'dateFormat' => 'M/d/yyyy', 'on'=>'registration, Individual','message'=>Yii::t("main","370_choose_the")),
			array('zipcode, id', 'numerical', 'integerOnly'=>true, 'on'=>'Individual','message' => Yii::t("main","371_numbers_allowed")),
			
			array('parentId', 'numerical', 'min'=>1, 'integerOnly'=>true, 'allowEmpty'=>true, 'message' => Yii::t("main","371_numbers_allowed"), 'tooBig' => Yii::t("main","921_only_6_digits_allow"), 'tooSmall' => Yii::t("main","922_inavlid_ib_code")),
			array('parentId', 'length', 'min'=>0, 'max'=>6, 'allowEmpty'=>true, 'tooLong' => Yii::t("main","921_only_6_digits_allow"), 'tooShort' => Yii::t("main","922_inavlid_ib_code")), 
			
			array('code', 'numerical', 'integerOnly'=>true, 'on'=>'registration, registrationCorp','message' => Yii::t("main","371_numbers_allowed")),
			array('role', 'in', 'range'=>array('4','3','2','-1'), 'on'=>'registration, registrationCorp', 'message' => Yii::t("main","371_numbers_allowed")),
			array('code, role', 'checkParent', 'on'=>'registration, registrationCorp', 'message' => Yii::t("main","371_numbers_allowed")),
			
			// trader type - corporate
            array('firstName, phone, email', 'in', 'range' => array('Admin', 'root', Yii::t("main","27_first_name"), Yii::t("main","28_last_name"),'Administrator',Yii::t("main","130_phone"),Yii::t("main",'560_main_phone'),Yii::t("main","131_email"),Yii::t("main",'559_main_email')),'not'=>true,'message' => Yii::t("main","36_cannot_be_blank"), 'on'=>'registrationCorp'),
            array('firstName, phone, email, birthday', 'required', 'on'=>'registrationCorp','message'=> Yii::t("main","36_cannot_be_blank")),
			array('groupType', 'in', 'range' => array('1','2','3'),'not'=>false,'on'=>'registrationCorp'),
			array('birthday','dateLessThenNow','on'=>'registrationCorp'),
			array('country', 'required', 'on'=>'registrationCorp','message'=>Yii::t("main","370_choose_the")),
			array('firstName, phone, email', 'in', 'range' => array('Admin', 'root', Yii::t("main","27_first_name"), Yii::t("main","28_last_name"),'Administrator', Yii::t("main","556_company_name"),'Main Phone','Main Email'),'not'=>true,'message' => Yii::t("main","36_cannot_be_blank"), 'on'=>'registrationCorp'),
            array('birthday', 'type', 'type' => 'date', 'dateFormat' => 'M/d/yyyy','on'=>'registrationCorp','message'=>Yii::t("main","370_choose_the")),
			array('phone','match','pattern' => '/^\+?\d+$/','message' => Yii::t("main","35_incorrect_phone_number"),'on'=>'registrationCorp'),
			array('email', 'IsCheckEmail', 'on'=>'registrationCorp'), 
			array('additionalInfo', 'match','pattern' => '/^[a-z0-9`~!"@№%#\$;:\?\/\\&\*\+-_\(\)=\{\}\[\]\'|\s]*$/i','message' => Yii::t("main","34_only_latin_characters_allowed_for"), 'on'=>'registrationCorp'),	
			//array('lastName', 'length', 'min'=>0, 'max'=>255, 'tooShort'=>Yii::t("main","528_min_length_is"), 'tooLong'=>Yii::t("main","529_max_length_is"), 'allowEmpty'=>true, 'on'=>'registrationCorp'),
			array('email' , 'email', 'on'=>'registrationCorp','message' =>Yii::t("main","357_such_email_address_is_not_valid")),
			array('email', 'IsCheckEmail', 'on'=>'registration'), 
			array('agreeBonus', 'boolean'), 
			array('phone', 'length', 'min'=>8, 'max'=>18, 'tooShort'=>Yii::t("main","528_min_length_is"), 'tooLong'=>Yii::t("main","529_max_length_is")),
			array('country', 'required', 'on'=>'registration','message'=>Yii::t("main","370_choose_the")),
			array('Source', 'in', 'range' => array_merge(array_keys($sources), array('-1')), 'message' => Yii::t("sp","120_not_listed")),
			
			array('leverage', 'required', 'on'=>'openTrAcc','message'=>Yii::t("main","370_choose_the")),
		);
    }

    public function whenPassOnRegAllow()
    {

        if(Yii::app()->params['pass_on_reg'] && Yii::app()->request->getQuery('type') === 'registration') {
            if(empty($this->password)){
                $this->addError('password', Yii::t("main","1092_password_cannot_be_blank"));
            }
        }
    }

    public function checkUserInfo()
    {
        if(!Yii::app()->params['pass_on_reg']){
            return;
        }

        if( !empty($this->firstName) &&
            !empty($this->lastName) &&
            !empty($this->birthday) &&
            !empty($this->email) &&
            !empty($this->country) &&
            !empty($this->phone) &&
            !empty($this->capchaText) &&
            isset($_POST['yt0']) // is form submit
        ){



            if($this->birthday!=Yii::t("main","29_birthday")){
                $start_d = isset($this->birthday) ? explode("/",$this->birthday) : explode("/","01/01/0001");
                $birthday=mktime(date("H"),date("i"),date("s"),$start_d[0],$start_d[1],$start_d[2]);
            }else{
                $birthday = $this->birthday;
            }



            $res = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/CheckUserInfo?firstName='.rawurlencode($this->firstName).'&lastName='.rawurlencode($this->lastName).'&birtDay='.rawurlencode($birthday).'&email='.rawurlencode(strtolower($this->email)).'&country='.rawurlencode($this->country).'&phone='.rawurlencode(trim($this->phone)).'&capchaText='.$this->capchaText);

            /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
            if ($ip == '162.13.154.241') {
                // var_dump($res, Yii::app()->params['json_server'].'/API/Registration/CheckUserInfo?firstName='.rawurlencode($this->firstName).'&lastName='.rawurlencode($this->lastName).'&birtDay='.rawurlencode($birthday).'&email='.rawurlencode(strtolower($this->email)).'&country='.rawurlencode($this->country).'&phone='.rawurlencode(trim($this->phone)).'&capchaText='.$this->capchaText);
                // var_dump($res, isset($res->State));
            }*/

            if(isset($res->State) && $res->State == 0){
                // ok
            }elseif($res === 'WrongEmail'){
                $this->addError('email', Yii::t("main","22_this_email_address_is_not_a_valid"));
            }elseif($res === 'WrongCapchaText'){
                $this->addError('capchaText', Yii::t("main","1067_wrong_capcha_code"));
            }elseif($res === 'WrongIpAddress'){
                $this->addError('common', Yii::t("main","1070_wrong_ip"));
            }else{
                $this->addError('common', Yii::t("main","1074_error_occurred"));
            }



        }
        // Registration/CheckUserInfo(string firstName, string lastName, long birtDay, string email, string country, string phone, string capchaText)
    }
				
			public function comparedates(){
                /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
                if ($ip == '46.211.241.112') {
                    var_dump($this->birthday, Yii::t("main","29_birthday"));die();
                }*/

				if($this->birthday!=Yii::t("main","29_birthday")){
				 if(explode("/",$this->birthday)){
				  $_d =explode("/",$this->birthday);
						if(preg_match("#[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}#",$this->birthday) && checkdate($_d[0],$_d[1],$_d[2])){
							$now=mktime(date("H"),date("i"),date("s"),date("m"),date("d"),date("Y"));	
							$now_under=mktime(date("H"),date("i"),date("s"),$_d[0],$_d[1],$_d[2]);	
							if(($now-$now_under)<567993600)
								$this->addError('birthday', Yii::t("main","422_you_are_under_18_years_old"));
						}
					}
				}else{
                    $this->addError('birthday', Yii::t("main","36_cannot_be_blank"));
                }
			}
			
			public function dateLessThenNow(){			
				if(!empty($this->birthday) && $this->birthday != wlTrans::get('reg.birthday_name_placeholder') && $this->birthday != wlTrans::get('reg.birthday_corp_name_placeholder')){
					$_d =explode("/",$this->birthday);
					if(mktime(date("H"),date("i"),date("s"),$_d[0],$_d[1],$_d[2]) > time()){
						$this->addError('birthday', $this->getAttributeLabel('birthday').' '.Yii::t("main","611_is_not_valid"));
					}					
				}
			}


    public function getCapchaLink()
    {
        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            $Info = Yii::app()->curlWithHeaders->get(Yii::app()->params['json_server'].'/API/Registration/GetClientCapcha?width=200&height=61', true, ['IpAddress' => isset($_COOKIE['guest_id']) ? $_COOKIE['guest_id'] : $_SERVER['REMOTE_ADDR']]);

            var_dump($Info, '1111');die();
        }*/

        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump(['IpAddress' => isset($_COOKIE['guest_id']) ? $_COOKIE['guest_id'] : $_SERVER['REMOTE_ADDR']]);die();
        }*/

        if( Yii::app()->params['type'] == 'eforex' || Yii::app()->params['type'] == 't2' ){
            $Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/GetClientCapcha?width=200&height=61');
        }else{
            $Info = Yii::app()->curlWithHeaders->get(Yii::app()->params['json_server'].'/API/Registration/GetClientCapcha?width=200&height=61', true, ['IpAddress' => isset($_COOKIE['guest_id']) ? $_COOKIE['guest_id'] : $_SERVER['REMOTE_ADDR']]);
        }

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            var_dump($Info, Yii::app()->params['json_server'].'/API/Registration/GetClientCapcha?width=200&height=61');die();
        }*/

        return $Info;

        //return Yii::app()->params['json_server'].':'.Yii::app()->params['port'].'/API/Registration/GetClientCapcha?width=200&height=61';
    }

    public static function getCapchaImg()
    {
        if( Yii::app()->params['type'] == 'eforex' || Yii::app()->params['type'] == 't2' ){
          $Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/GetClientCapcha?width=200&height=61');
        }else{
            $Info = Yii::app()->curlWithHeaders->get(Yii::app()->params['json_server'].'/API/Registration/GetClientCapcha?width=200&height=61', true, ['IpAddress' => isset($_COOKIE['guest_id']) ? $_COOKIE['guest_id'] : $_SERVER['REMOTE_ADDR']]);
        }

        return $Info;
    }
			
    public function attributeLabels(){
			if($this->getScenario()=='registrationCorp'){
				return array(
					'agreementTerms'=>'Accept <a href="agreement.html" target="_blank">'.Yii::t("main","37_agreement_terms").'</a>',
					'firstName' => Yii::t("main",'556_company_name'),
					'lastName' => Yii::t("main",'28_last_name'),
					'country' => Yii::t("main",'558_location_of_incorp'),
					'birthday' => Yii::t("main",'557_date_of_incorp'),				
					'phone' => Yii::t("main",'560_main_phone'),
					'email' => Yii::t("main",'559_main_email'),
					'address' => Yii::t("main",'561_address_incorporation'),
					'city' => Yii::t("main",'132_city'),					
					'parentId' => Yii::t("main",'920_ib_code'),					
					'Source' => Yii::t("main",'114_source'),					
					'additionalInfo' => Yii::t("main",'1013_additional_info'),					
					'capchaText' => Yii::t("main",'1058_capcha'),
				);
			}else{
				$array = array(
					'agreementTerms'=>'Accept <a href="agreement.html" target="_blank">'.Yii::t("main","37_agreement_terms").'</a>',
					'firstName' => Yii::t("main",'27_first_name'),
					'lastName' => Yii::t("main",'28_last_name'),
					'country' => Yii::t("main",'129_country'),
					'birthday' => Yii::t("main",'29_birthday'),				
					'phone' => Yii::t("main",'130_phone'),
					'email' => Yii::t("main",'131_email'),
					'address' => Yii::t("main",'133_address'),
					'parentId' => Yii::t("main",'920_ib_code'),
					'Source' => Yii::t("main",'114_source'),
					'additionalInfo' => Yii::t("main",'1013_additional_info'),
                    'capchaText' => Yii::t("main",'1058_capcha'),
                );
				
				$array['leverage'] = Yii::t("main","1035_leverage");
					
				if(wlParams::get('officeCode') == 22 && $this->getScenario() != 'registrationCorp'){
					$array['country'] = Yii::t("main","958_nationaly");
					$array['phone'] = Yii::t("trader","72_mobile_phone");
				}
				
				//var_dump($array);die();
				
				return $array;
			}
    }
/*    public function rulesCorporate(){
        $corporate = new RegistrationCorporate();
        $corporate->attributes = $_REQUEST['Corporate'];
        if($corporate->validate()){
            // print_r(array('Bank'=>$bank->getErrors()));exit();
            //$this->addError('Bank[beneficiary]','Country слишком короткий (Минимум: 3 симв.)');
            // $this->addErrors(array('Bank'=>$bank->getErrors()));
        }
    }
     public function rulesBank(){
        $bank = new RegistrationBank();
        $bank->attributes = $_REQUEST['Bank'];
        if($bank->validate()){
            // print_r(array('Bank'=>$bank->getErrors()));exit();
            $this->addError('Bank[beneficiary]','Country слишком короткий (Минимум: 3 симв.)');
            // $this->addErrors(array('Bank'=>$bank->getErrors()));
        }
    } */
    public function GetCompanyInfo(){    
        $Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/GetCompanyInfo?guid='.Yii::app()->user->id);
        //$this->Corporate = $Info->Data;
		//print_r($Info); exit();
    }
    //----------------------------------------
    //----------------------------------------
    //----------------------------------------
    
    public function IsTerms(){
        if($this->agreementTerms != 1){$this->addError('agreementTerms',Yii::t("main","38_you_didnt_take_an_agreement"));}
    }
    public function IsCheckEmail(){
        if($this->email == 'Email') return true;
        if(Yii::app()->params['login_by_email'] || Yii::app()->params['reg_with_letter_code']){
            $isBroker =   Yii::app()->request->getQuery('type') == 'registrationIb'? 'true' : 'false';
            $mail = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/CheckEmailWithCode?isBroker='.$isBroker.'&email='.strtolower($this->email).'&officeCode='.wlParams::get('officeLetterCode'));
            /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
            if ($ip == '78.46.17.32') {
                var_dump($mail, Yii::app()->params['json_server'].'/API/Registration/CheckEmailWithCode?email='.strtolower($this->email).'&officeCode='.wlParams::get('officeLetterCode'));die();
            }*/

        }else{
            $mail = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/CheckEmail?email='.strtolower($this->email));
        }

        if($mail == 'UserAlreadyExists'){$this->addError('email',Yii::t("main","39_this_email_has_already_registered"));}
    }
	public function GetOfficeCode($code, $role){
        $info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/GetOfficeCode?code='.$code.'&role='.$role);
		
		return $info;
    }
    //--------------
    public function initDate($date){	
        $_d =explode("/",$date);
        return mktime(date("H"),date("i"),date("s"),$_d[0],$_d[1],$_d[2]);									
    }
	public function initIndv(){

		//var_dump(Yii::app()->params['json_server'].'/API/Registration/GetUserInfo?guid='.Yii::app()->user->id.'&userLogin=-1');
        $Info = (array)Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/GetUserInfo?guid='.Yii::app()->user->id.'&userLogin=-1',true);	
		//var_dump($Info);die();



		//var_dump(count($Info));die();
		

		if((isset($Info["State"]) && $Info["State"]!=1) || !isset($Info["State"])){
			if(count($Info) > 1){
				$Info = array(array_shift($Info));
			}
			foreach($Info as $key=>$infdate){
				if(!empty($infdate->birthday)){
					$datetmp = date_create($infdate->birthday);
					$infdate->birthday = date_format($datetmp, 'm/d/Y');
					//var_dump($infdate->birthday);die();
					if(date_format($datetmp, 'm/d/Y')=="01/01/0001" /*|| date_format($datetmp, 'm/d/Y')=="01/01/2001"*/){$infdate->birthday="";}else{$infdate->birthday=date_format($datetmp, 'm/d/Y');} // || date_format($datetmp, 'm/d/Y')=="01/01/1970" был чувак с такой датой
				}
				if(is_array($infdate)){
					foreach($infdate as &$infdt){ 
						//$infdt = str_replace(array('{p}','{}'),array('+','/'),$infdt);
						if($infdt==" "){$attr="";}
						$infdt = stripcslashes(rawurldecode($infdt));
					}	
				}
				$this->attributes = (array)$infdate;	
			
				if(isset($infdate->birthday)){
					$this->birthday = $infdate->birthday;
				}
				if(isset($infdate->email)){
					$this->email = $infdate->email;
				}
				if(isset($infdate->id)){
					$this->id = $infdate->id;
				}
				if(isset($infdate->phone)){
					$this->phone = $infdate->phone;
				}
			}
		}

	}
	
	 public function isFull(){
		$fields = array('firstName','lastName','birthday','email','phone','country', 'city', 'address');

		foreach($fields as $field){
			if(trim($this[$field])==""){
                /*$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($field, $this->attributes);die();
                }*/
				return false;
			}
		}

		return true;
	} 
	 public function sendApprove(){
		$AccModel= new Account();
		$account = $AccModel->GetInfo();
		if($account->Type==4){
			$rez = (array)Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/SendIBRequestToOperations?guid='.Yii::app()->user->id);
		}else{
			$rez = (array)Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/SendUserRequestToOperations?guid='.Yii::app()->user->id);
		}
		return $rez;
	 }
	 
	  public function IsApprove(){
		/*
		NotStarted = 0;  - не прислал запрос и не сапрувлен
		InProgress=1;    - прислал запрос проходит процедуру
		Reject = 2;      - в процедуре какая-то ошибка
		Approved=3;      - чувак сапрувлен
		 */
			$AccModel = new Account();
			$account = $AccModel->GetInfo();                      
				switch(isset($account->Type) ? $account->Type : 0){
					case "4":
					 //var_dump(Yii::app()->params['json_server'].'/API/Registration/GetIBRequestState?guid='.Yii::app()->user->id);
					  $status = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/GetIBRequestState?guid='.Yii::app()->user->id);
					  //var_dump($status);die();
					break;
					
					default:
					  $status = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/GetUserRequestState?guid='.Yii::app()->user->id.'&userLogin=-1');
					break;
				}        
			if($status==2){
				if($account->Type==4){
					Yii::app()->params['operator_warning'] = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/GetIBRequestRejectMessage?guid='.Yii::app()->user->id);
				}else{
					Yii::app()->params['operator_warning'] = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/GetUserRequestComment?guid='.Yii::app()->user->id);
				}

			}
			/* if(($status==2 || $status==3) && isset($_SESSION['ibAgreement']) && $_SESSION['ibAgreement']==1){
				unset($_SESSION['ibAgreement']);
			} */
            if(isset($_GET['a'])){ return $_GET['a'];}
            return $status;
        }
		
		
		
	public function update(){	
		$attrs = $this->attributes;
		$id = ($attrs['id']) ? $attrs['id'] : -1;
		if(isset($attrs["birthday"]) && $attrs["birthday"]!=""){
			$attrs["birthday"] = $this->initDate($attrs["birthday"]);
		}
		foreach($attrs as $key=>$attr){
			//$attr = str_replace(array('+', '/'),array('{p}', '{}'),$attr);
			if($attr==""){$attr=" ";}
			$attrs[$key] = rawurlencode($attr);
		}
		//var_dump(Yii::app()->params['json_server'].'/API/Registration/ChangeBrokerInfo?guid='.Yii::app()->user->id.'&id='.$id.'&FirstName='.$attrs["firstName"].'&LastName='.$attrs["lastName"].'&MiddleName=empty&Sex=false&DateOfBirth='.$attrs["birthday"].'&Citizenship=empty&Passport=empty&Nationality=empty&Email='.$attrs["email"].'&PhoneNumber='.$attrs["phone"].'&Website=empty&Country='.$attrs["country"].'&City='.$attrs["city"].'&Address='.$attrs["address"].'&ZipCode=empty&additionalInfo='.$attrs["additionalInfo"]);
		$Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/ChangeBrokerInfo?guid='.Yii::app()->user->id.'&id='.$id.'&FirstName='.$attrs["firstName"].'&LastName='.$attrs["lastName"].'&MiddleName=empty&Sex=false&DateOfBirth='.$attrs["birthday"].'&Citizenship=empty&Passport=empty&Nationality=empty&Email='.$attrs["email"].'&PhoneNumber='.$attrs["phone"].'&Website=empty&Country='.$attrs["country"].'&City='.$attrs["city"].'&Address='.$attrs["address"].'&ZipCode=empty&additionalInfo='.$attrs["additionalInfo"]);
		//var_dump($Info);die();

		return $Info;
	}
    
    public function NewUser($login = true){


		if(isset($this->birthday)){
			$start_d =explode("/",$this->birthday);
		}else{
			$start_d =explode("/","01/01/0001");
		}
		$birthday=mktime(date("H"),date("i"),date("s"),$start_d[0],$start_d[1],$start_d[2]);
        $md5 =  md5($this->firstName.'/'.md5($this->lastName).'/'.$birthday.'/'.md5($this->email).'BMFNcorp');  
		
        if($this->groupType == 2){ $this->lastName = ''; }// хак для корпорейта нужен если валидация сраб

		if($_SERVER['HTTP_HOST'] == 'my.noorcap.ae'){
			$this->code = $this->checkNoorCodes($this->role, $this->code);			
		}


		
		$this->role = ($this->role == -1) ? wlParams::get('officeRole') : $this->role;
		$this->code = ($this->code == -1) ? wlParams::get('officeCode') : $this->code;



            if(in_array(wlParams::get('officeCode'), array(56, 56, 58, 59))){
                if(in_array($this->country, Account::$euCountries)){
                    $this->code = 57;
                }elseif(in_array($this->country, Account::$auCountries)){
                    $this->code = 56;
                }else{
                    $this->code = 58;
                }
            }

        $password = $this->password ? '&password='.rawurlencode($this->password) : '';

        if( Yii::app()->params['type'] == 'eforex' || Yii::app()->params['type'] == 't2' ){
		    $list_account = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/RegNewUserInSystem?guid=null&code='.rawurlencode($this->code).'&role='.rawurlencode($this->role).'&firstName='.rawurlencode(trim($this->firstName)).'&lastName='.rawurlencode(trim($this->lastName)).'&birtDay='.rawurlencode($birthday).'&email='.rawurlencode(strtolower($this->email)).'&country='.rawurlencode($this->country).'&phone='.rawurlencode(trim($this->phone)).'&userType=1&groupType='.rawurlencode($this->groupType).'&defaultLanguage='.Yii::app()->language.'&source='.$this->Source.'&capchaText='.$this->capchaText.$password); // .'&capchaText='.$this->capchaText
        }else{
            $list_account = Yii::app()->curlWithHeaders->get(Yii::app()->params['json_server'].'/API/Registration/RegNewUserInSystem?guid=null&code='.rawurlencode($this->code).'&role='.rawurlencode($this->role).'&firstName='.rawurlencode(trim($this->firstName)).'&lastName='.rawurlencode(trim($this->lastName)).'&birtDay='.rawurlencode($birthday).'&email='.rawurlencode(strtolower($this->email)).'&country='.rawurlencode($this->country).'&phone='.rawurlencode(trim($this->phone)).'&userType=1&groupType='.rawurlencode($this->groupType).'&defaultLanguage='.Yii::app()->language.'&source='.$this->Source.'&capchaText='.$this->capchaText.$password, false, ['IpAddress' => isset($_COOKIE['guest_id']) ? $_COOKIE['guest_id'] : $_SERVER['REMOTE_ADDR']]); // .'&capchaText='.$this->capchaText
            //var_dump($list_account, Yii::app()->params['json_server'].'/API/Registration/RegNewUserInSystem?guid=null&code='.rawurlencode($this->code).'&role='.rawurlencode($this->role).'&firstName='.rawurlencode($this->firstName).'&lastName='.rawurlencode($this->lastName).'&birtDay='.rawurlencode($birthday).'&email='.rawurlencode(strtolower($this->email)).'&country='.rawurlencode($this->country).'&phone='.rawurlencode(trim($this->phone)).'&userType=1&groupType='.rawurlencode($this->groupType).'&defaultLanguage='.Yii::app()->language.'&source='.$this->Source.'&capchaText='.$this->capchaText);die();
        }

		if($login){
		    if($list_account == 'WrongCapchaText') {
                return $list_account;
            }elseif(!is_string($list_account) && $list_account != 'BrokerDoesntExist') {
                $scenario = Yii::app()->params['login_by_email'] ? 'email' : 'login';

		        $loginFrom = new LoginForm($scenario);

                if(Yii::app()->params['login_by_email']){
                    $loginFrom->username = $this->email;
                }else{
                    $loginFrom->username = $list_account->Id;
                }

                $loginFrom->password = $list_account->Password;
				$loginFrom->rememberMe = 0;

                if(wlParams::get('officeCode') == 73) {
                    if(isset($_GET['click_id']) && $_GET['click_id'] !== '' && isset($list_account->Login) ){
                        $params = [
                            'transaction_id'=> $list_account->Login,
                            'token'=>'e81da81feb0a55aaca638161cc10af99',
                            'campaign_id'=> 64,
                            'click_id'=>$_GET['click_id'],
                            'price'=>'0',
                            'quantity'=>'1',
                            'product_id'=>'cpl',
                            'category_id'=>'cpl'
                        ];
                        $url = 'https://service-api.ifinance.asia/api/v1/tracking-tag';
                        $res = Yii::app()->curl->post($url, $params, 443);
                        /*$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( $url, $params, $list_account);die();
                        }*/
                    }
                }


				if ($loginFrom->validate() && $loginFrom->login()){

                    //if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {

                        $view = new Account();
                        $rez=$view->GetDocumentsID();

                        if(isset($rez) && $rez>0){
                            if(($rez!=Yii::app()->params['office_number'] && $rez!=5 && $rez!=19) /*&& ($rez!=5 && $_SERVER["HTTP_HOST"] == 'my.bmfn.com')*/){
                                $guid = Yii::app()->user->id;
                                Yii::app()->user->logout();
                                Yii::app()->getController()->redirect(LoginForm::getUrlForLoginRedirect($rez, $guid));
                            }
                        }
                    //}

					return array('Login'=>$loginFrom->username,'Pass'=>$loginFrom->password);
				}			
			}
		}		

        return $list_account;
    }
    public function NewUserIB(){



		if(isset($this->birthday)){
			$start_d =explode("/",$this->birthday);
			$birthday=mktime(date("H"),date("i"),date("s"),$start_d[0],$start_d[1],$start_d[2]);
		}else{
			//$start_d =explode("/","01/01/0001");
			$birthday = 0;
		}
        $md5 =  md5($this->firstName.'/'.md5($this->lastName).'/'.$birthday.'/'.md5($this->email).'BMFNcorp');
   
		//var_dump(Yii::app()->params['json_server'].'/API/Registration/RegNewIBInSystem?guid=null&firstName='.rawurlencode($this->firstName).'&lastName='.rawurlencode($this->lastName).'&birtDay='.rawurlencode($birthday).'&email='.rawurlencode($this->email).'&country='.rawurlencode($this->country).'&phone='.rawurlencode($this->phone).'&code=-1&role=4&parentCode='.rawurlencode($this->code).'&parentRole='.$this->role.'&defaultLanguage='.Yii::app()->language);
		if($_SERVER['HTTP_HOST'] == 'my.noorcap.ae'){
			$this->code = $this->checkNoorCodes($this->role, $this->code);			
		}

        /*if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
            var_dump(Yii::app()->params['json_server'].'/API/Registration/RegNewIBInSystem?guid=null&firstName='.rawurlencode($this->firstName).'&lastName='.rawurlencode($this->lastName).'&birtDay='.rawurlencode($birthday).'&email='.rawurlencode($this->email).'&country='.rawurlencode($this->country).'&phone='.rawurlencode($this->phone).'&code=-1&role=4&parentCode='.rawurlencode($this->code).'&parentRole='.$this->role.'&defaultLanguage='.Yii::app()->language);die();
        }*/

        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump(Yii::app()->params['json_server'].'/API/Registration/RegNewIBInSystem?guid=null&firstName='.rawurlencode($this->firstName).'&lastName='.rawurlencode($this->lastName).'&birtDay='.rawurlencode($birthday).'&email='.rawurlencode($this->email).'&country='.rawurlencode($this->country).'&phone='.rawurlencode($this->phone).'&code=-1&role=4&parentCode='.rawurlencode($this->code).'&parentRole='.$this->role.'&defaultLanguage='.Yii::app()->language);die();
        }*/

        if(in_array(wlParams::get('officeCode'), array(56, 56, 58, 59))){
            if(in_array($this->country, Account::$euCountries)){
                $this->code = 57;
            }elseif(in_array($this->country, Account::$auCountries)){
                $this->code = 56;
            }else{
                $this->code = 58;
            }
            $this->role = 2;
        }

        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump($this->code);die();
        }*/
        //if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
        if( Yii::app()->params['type'] == 'eforex' || Yii::app()->params['type'] == 't2' ){
		    $list_account = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/RegNewIBInSystem?guid=null&firstName='.rawurlencode($this->firstName).'&lastName='.rawurlencode($this->lastName).'&birtDay='.rawurlencode($birthday).'&email='.rawurlencode($this->email).'&country='.rawurlencode($this->country).'&phone='.rawurlencode(trim($this->phone)).'&code=-1&role=4&parentCode='.rawurlencode($this->code).'&parentRole='.$this->role.'&defaultLanguage='.Yii::app()->language.'&capchaText='.$this->capchaText); // .'&capchaText='.$this->capchaText

            /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
            if ($ip == '162.13.154.241') {
                var_dump('11', $list_account, Yii::app()->params['json_server'].'/API/Registration/RegNewIBInSystem?guid=null&firstName='.rawurlencode($this->firstName).'&lastName='.rawurlencode($this->lastName).'&birtDay='.rawurlencode($birthday).'&email='.rawurlencode($this->email).'&country='.rawurlencode($this->country).'&phone='.rawurlencode(trim($this->phone)).'&code=-1&role=4&parentCode='.rawurlencode($this->code).'&parentRole='.$this->role.'&defaultLanguage='.Yii::app()->language.'&capchaText='.$this->capchaText);die();
            }*/
        }else{
            /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
            if ($ip == '78.46.17.32') {
                var_dump($this->code, wlParams::get('officeCode'), wlParams::get('otherMainOffice'), Yii::app()->params['json_server'].'/API/Registration/RegNewIBInSystem?guid=null&firstName='.rawurlencode($this->firstName).'&lastName='.rawurlencode($this->lastName).'&birtDay='.rawurlencode($birthday).'&email='.rawurlencode($this->email).'&country='.rawurlencode($this->country).'&phone='.rawurlencode(trim($this->phone)).'&code=-1&role=4&parentCode='.rawurlencode($this->code).'&parentRole='.$this->role.'&defaultLanguage='.Yii::app()->language.'&capchaText='.$this->capchaText);die();
            }*/

		    $list_account = Yii::app()->curlWithHeaders->get(Yii::app()->params['json_server'].'/API/Registration/RegNewIBInSystem?guid=null&firstName='.rawurlencode($this->firstName).'&lastName='.rawurlencode($this->lastName).'&birtDay='.rawurlencode($birthday).'&email='.rawurlencode($this->email).'&country='.rawurlencode($this->country).'&phone='.rawurlencode(trim($this->phone)).'&code=-1&role=4&parentCode='.rawurlencode($this->code).'&parentRole='.$this->role.'&defaultLanguage='.Yii::app()->language.'&capchaText='.$this->capchaText, false, ['IpAddress' => isset($_COOKIE['guest_id']) ? $_COOKIE['guest_id'] : $_SERVER['REMOTE_ADDR']]); // .'&capchaText='.$this->capchaText

            /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
            if ($ip == '162.13.154.241') {
                var_dump($list_account, Yii::app()->params['json_server'].'/API/Registration/RegNewIBInSystem?guid=null&firstName='.rawurlencode($this->firstName).'&lastName='.rawurlencode($this->lastName).'&birtDay='.rawurlencode($birthday).'&email='.rawurlencode($this->email).'&country='.rawurlencode($this->country).'&phone='.rawurlencode(trim($this->phone)).'&code=-1&role=4&parentCode='.rawurlencode($this->code).'&parentRole='.$this->role.'&defaultLanguage='.Yii::app()->language.'&capchaText='.$this->capchaText);die();
            }*/
        }
        /*}else{
		    $list_account = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/RegNewIBInSystem?guid=null&firstName='.rawurlencode($this->firstName).'&lastName='.rawurlencode($this->lastName).'&birtDay='.rawurlencode($birthday).'&email='.rawurlencode($this->email).'&country='.rawurlencode($this->country).'&phone='.rawurlencode(trim($this->phone)).'&code=-1&role=4&parentCode='.rawurlencode($this->code).'&parentRole='.$this->role.'&defaultLanguage='.Yii::app()->language.'&capchaText='.$this->capchaText); // .'&capchaText='.$this->capchaText
        }*/

        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump($list_account, Yii::app()->params['json_server'].'/API/Registration/RegNewIBInSystem?guid=null&firstName='.rawurlencode($this->firstName).'&lastName='.rawurlencode($this->lastName).'&birtDay='.rawurlencode($birthday).'&email='.rawurlencode($this->email).'&country='.rawurlencode($this->country).'&phone='.rawurlencode($this->phone).'&code=-1&role=4&parentCode='.rawurlencode($this->code).'&parentRole='.$this->role.'&defaultLanguage='.Yii::app()->language.'&capchaText='.$this->capchaText);die();
        }*/

        if($list_account == 'WrongCapchaText'){

            return $list_account;
        }elseif(!is_string($list_account) && $list_account != 'BrokerDoesntExist'){
            $scenario = Yii::app()->params['login_by_email'] ? 'email' : 'login';
			$loginFrom = new LoginForm($scenario);
			$loginFrom->username = Yii::app()->params['login_by_email'] ? $this->email : $list_account->Login;
			$loginFrom->password = $list_account->Password;
			$loginFrom->rememberMe = 0;

            /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
            if ($ip == '78.46.17.32') {
                var_dump($loginFrom->validate(), $loginFrom->login(), Yii::app()->params['login_by_email'], $loginFrom->getScenario(), $loginFrom->getErrors(), $loginFrom->attributes, $this->attributes);die();
            }*/

			//var_dump($loginFrom->attributes, $loginFrom->validate(), $loginFrom->login());die();
			if ($loginFrom->validate() && $loginFrom->login()){

                //if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {

                    $view = new Account();
                    $rez=$view->GetDocumentsID();

                /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                    var_dump($rez, Yii::app()->params['office_number']);die();
                }*/

                    if(isset($rez) && $rez>0){
                        if(($rez!=Yii::app()->params['office_number'] && $rez!=5 && $rez!=19) /*&& ($rez!=5 && $_SERVER["HTTP_HOST"] == 'my.bmfn.com')*/){
                            $guid = Yii::app()->user->id;
                            Yii::app()->user->logout();
                            Yii::app()->getController()->redirect(LoginForm::getUrlForLoginRedirect($rez, $guid));
                        }
                    }
                //}

				return array('Login'=>$loginFrom->username,'Pass'=>$loginFrom->password);
			}
		}
  
        return $list_account;
    }
    
    

    /* -----------------------------
    * -----------------------------
    * -----------------------------
    */
    public function GetCountry($code = 'none', $isRegist = false){
        
				//var_dump(Yii::app()->params['json_server'].'/API/Registration/GetCountries');die();
			
				if($isRegist){
					$guid = '';
					if (Yii::app()->user->isGuest){
						$rrole = (wlParams::get('officeRole') == '') ? -1 : wlParams::get('officeRole');
						$rcode = (wlParams::get('officeCode') == '') ? -1 : wlParams::get('officeCode');
						if(isset($_GET['sv']) && !empty($_GET['sv'])){
							$rrole = 2;
							$rcode = $_GET['sv'];
						}elseif(isset($_GET['sp']) && !empty($_GET['sp'])){
							$rrole = 3;
							$rcode = $_GET['sp'];
						}elseif(isset($_GET['ib']) && !empty($_GET['ib'])){
							$rrole = 4;
							$rcode = $_GET['ib'];
						}
						
						if($_SERVER['HTTP_HOST'] == 'my.noorcap.ae'){
							$rcode = $this->checkNoorCodes($rrole, $rcode);			
						}
					}else{
						$guid = Yii::app()->user->id;
						$rrole = -1;
						$rcode = -1;
					}
					//var_dump(Yii::app()->params['json_server'].'/API/Registration/GetCompanyCountries?guid='.$guid.'&role='.$rrole.'&code='.$rcode);die();
					$list_country = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/GetCompanyCountries?guid='.$guid.'&role='.$rrole.'&code='.$rcode);

                    /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                        var_dump($list_country, Yii::app()->params['json_server'].'/API/Registration/GetCompanyCountries?guid='.$guid.'&role='.$rrole.'&code='.$rcode);die();
                    }*/
					/* if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
						var_dump(!is_array($list_country), $list_country, Yii::app()->params['json_server'].'/API/Registration/GetCompanyCountries?guid='.$guid.'&role='.$rrole.'&code='.$rcode);die();
					} */
					//var_dump(Yii::app()->params['json_server'].'/API/Registration/GetCompanyCountries?guid='.$guid.'&role='.$rrole.'&code='.$rcode, $list_country);die();
					 /* if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
						var_dump('111', Yii::app()->params['json_server'].'/API/Registration/GetCompanyCountries?guid='.$guid.'&role='.$rrole.'&code='.$rcode, $list_country);die();
					} */
					if(!is_array($list_country)){
                        throw new CHttpException(404,$list_country);
                    }
				}else{
					$list_country = Yii::app()->params['cacheCountries'] = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/GetCountries'); 						
				}
				//var_dump($list_country);die();				

				
				
				
                if($code == 'none'){
						if(wlParams::get('officeCode') == 22 && $this->getScenario() == 'registration' ){
							$country[''] = Yii::t("main","958_nationaly");
						}else{
							$country[''] = Yii::t("main","363_select_country");
						}
				}
				
				if(wlParams::get('officeCode') == 30){
					foreach ($list_country as $key=>$value) {
						if($value->Code == 'GBR'){
							unset($list_country[$key]);
						}
					}
				}

        /*$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('22222', $list_country);die();
        }*/

               /* if(in_array(wlParams::get('officeCode'), [19,30,32,53,54])){
                    foreach ($list_country as $key=>$value) {
                        if($value->Code == 'RUS'){
                            unset($list_country[$key]);
                        }
                    }
                }*/



                foreach ($list_country as $value) {
                       if($code=='none'){
                       //var_dump($value);die();
                               $country[$value->Name]=$value->Name;
                       }elseif($code=='three'){
                               //if(!empty($value->Code)){
                                       $country[$value->Name]=$value->Code;
                               //}
                       }elseif($code=='two'){
                               //if(!empty($value->ISOCode)){
                                       $country[$value->Name]=$value->ISOCode;
                               //}
                       }else{
                               $country[$value->Name]=$value->Name;
                       }
                }

            return $country;
    }
	
	public function GetAssocGeoIpCountry($code = ''){
		$list_country = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/GetCountries'); 
		$assoc = array();
		foreach($list_country as $country){
			$assoc[$country->ISOCode] = $country->Name;
		}
		
		if($code == ''){
			$result = $assoc;			
		}else{
			if(isset($assoc[$code])){
				$result = $assoc[$code];
			}else{
				$result = '';
			}
		}
		
		return $result;
		
	}
    /* -----------------------------
    * -----------------------------
    * -----------------------------
    */
        
        public function GetSchedule($Pltype='-1',$isSet='true',$demoLive='1',$userLogin='-1'){
			/* 
				platformType::  0 - All; 1 - Live; 2 - Demo; Other num - nothing
				needWithSchedules:: true - ScheduleIs; false - All 
			*/
			$tmp = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/GetAvaliablePlatformsSchedules?guid='.Yii::app()->user->id.'&platform='.$Pltype.'&needWithSchedules='.$isSet.'&platformType='.$demoLive.'&userLogin='.$userLogin.'&language='.Yii::app()->language, true);



			$Schedule = array();
			if(!is_string($tmp)){
				if(is_array((array)$tmp)){
					
					$acc = new Account();
					$parentInfo = $acc->getParentContacts();

                    /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
                    if ($ip == '162.13.154.241') {
                        var_dump(wlParams::get('officeCode'), $parentInfo['Code'], $tmp, Yii::app()->params['json_server'].'/API/Registration/GetAvaliablePlatformsSchedules?guid='.Yii::app()->user->id.'&platform='.$Pltype.'&needWithSchedules='.$isSet.'&platformType='.$demoLive.'&userLogin='.$userLogin.'&language='.Yii::app()->language);die();
                    }*/

					foreach($tmp as $key=>$value){
                        if(wlParams::get('officeCode') == 63){
                            $value->Name .= ' Standard';
                            $value->info = Yii::t("main", "533_cfd_paramount_std");
                        }

						if($parentInfo['Code'] == 6){
                            if(in_array($value->PlatformID, array(7, 2, 5, 9))){
                                continue;
                            }
                        }

                        if(wlParams::get('officeCode') == 53){
                            if(in_array($value->PlatformID, array(5))){
                                continue;
                            }
                        }

                        if(wlParams::get('officeCode') == 80){
                            if(in_array($value->PlatformID, array(15))){
                                continue;
                            }
                        }







                        /* Show MT FX in these offices and under IB 6*/
                        if(!in_array(wlParams::get('officeCode'), [12,44,60,62,65,69,70,78,79,83,84,86,88,91]) && $parentInfo['Code'] != 6 && !in_array(Yii::app()->params['type'], ['eforex'])){
                            if(in_array($value->PlatformID, array(3, 8))){
                                continue;
                            }
                        }

                        /* Hide MT DMA from these offices */
                        if(in_array(wlParams::get('officeCode'), [5,19,32])){
                            if(in_array($value->PlatformID, array(2, 10))){
                                continue;
                            }
                        }

                        if(wlParams::get('officeCode') == 13 || wlParams::get('officeCode') == 56){
                            if(in_array($value->PlatformID, array(3, 5))){
                                continue;
                            }
                        }



                        if(
                            Yii::app()->params['type'] != 'eforex' &&
                            !in_array(wlParams::get('officeCode'), array(61, 64, 65, 66, 67, 74, 76, 78, 79, 86, 88)) &&
                            in_array($value->PlatformID, array(2, 7))
                        ){
                            continue;
                        }



						if(($isSet == 'true' && (wlParams::get('officeCode') == 3 && Yii::app()->params['type'] != 'ftt'))){
							if(in_array($value->PlatformID, array(3, 8))){
								continue;
							}
						}



						//if($value->PlatformID != 7){
							$Schedule[$key] = $value;
						//}


					}
				}
			}else{
				$Schedule['error'] = $tmp;
			}







             if(wlParams::get('officeCode') == 3 && Yii::app()->params['type'] != 'ftt'/* && Yii::app()->params['type'] != 'paramount'*/){
                unset($Schedule[5], $Schedule[9]);
             }

			if(wlParams::get('officeRole') == 4 && wlParams::get('officeCode') == 6){
				rsort($Schedule);
                $tmpSch = array();
                foreach($Schedule as $sh){
                    $tmpSch[$sh->Schedule->platformID] = $sh;
                }

                $Schedule = $tmpSch;
			}





           /* if (Yii::app()->params['type'] == 'bmfn' && $demoLive === '1') {
                $Schedule[] =
                    (object)[
                        'Name' => 'BMFN-RealCFD-Stocks', //remove from Demo!!!
                        'PlatformType' => 2,
                        'PlatformID' => 5,
                        'accountGroup' => 'Stocks_only',
                        'info' => Yii::t("main", "533_cfd_info_stocks")
                    ];
            }*/ // commented by Arsen on 08.06.2022, the group is not used!




            if($demoLive == 1){ // only for live accounts
                if(wlParams::get('officeCode') == 63){
                    $Schedule[] = (object)['Name'=> 'FXParamount-RealCFD Classic', 'accountGroup'=> 'IB6145_Classic', 'PlatformType'=> 2, 'PlatformID'=> '5|IB6145_Classic', 'info'=>Yii::t("main", "533_cfd_paramount_classic")];
                    $Schedule[] = (object)['Name'=> 'FXParamount-RealCFD Pro', 'accountGroup'=> 'IB6145_Pro', 'PlatformType'=> 2, 'PlatformID'=> '5|IB6145_Pro', 'info'=>Yii::t("main", "533_cfd_paramount_pro")];
                }
            }else{
                if(wlParams::get('officeCode') == 63){
                    $Schedule[] = (object)['Name'=> 'FXParamount-DemoCFD Classic', 'accountGroup'=> 'IB6145_Classic', 'PlatformType'=> 2, 'PlatformID'=> '9|demo6145_Class', 'info'=>Yii::t("main", "533_cfd_paramount_classic")];
                    $Schedule[] = (object)['Name'=> 'FXParamount-DemoCFD Pro', 'accountGroup'=> 'IB6145_Pro', 'PlatformType'=> 2, 'PlatformID'=> '9|demo6145_Pro', 'info'=>Yii::t("main", "533_cfd_paramount_pro")];
                }
            }

            return $Schedule;
        }
        
        public function ApplySchedule($commission,$schedId,$platformId) {
            $info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/ApplyCommissions?guid='.Yii::app()->user->id.'&commission='.$commission.'&schedID='.$schedId.'&platformID='.$platformId);

            /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
            if ($ip == '162.13.154.241') {
                var_dump($info, Yii::app()->params['json_server'].'/API/Registration/ApplyCommissions?guid='.Yii::app()->user->id.'&commission='.$commission.'&schedID='.$schedId.'&platformID='.$platformId);
            }*/
        }
   /* -----------------------------
    * -----------------------------
    * -----------------------------
    */
        public function GetAgreement(){
        
            return 1;
        }
         public function SetAgreement($Pltype){
        
            return 1;
        }
		
		public function GetDemoDepositValues(){
            $info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Accounts/GetDemoDepositValues?guid='.Yii::app()->user->id);
			
			return $info;
        }
		public function GetDemoLeverageValues(){
            $info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Accounts/GetDemoLeverageValues?guid='.Yii::app()->user->id);
			//var_dump($info, Yii::app()->params['json_server'].'/API/Accounts/GetDemoLeverageValues?guid='.Yii::app()->user->id);die();

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

            return $info;
        }
		
		
		public function regNewAccount($platform, $userLogin=-1, $balance = 0, $leverage = ''){
			$account = new Account();
			$info = $account->GetInfo();
			if($userLogin == -1){
				if(($info->Type==6 && $info->GroupType==3) || ($info->Type==4 && $info->GroupType==2)){
					$tmpRegist = new RegistrationTrader;
					$partners = $tmpRegist->initPartner();
					$attrs = (array)current($partners);
					$attrs["name"] = $attrs["firstName"].' '.$attrs["lastName"];
					if($info->GroupType==3){
						$attrs["name"] = '';
						foreach($partners as $k=>$partner){
							$attrs["name"] .= $partner->firstName.' '.$partner->lastName.'/';							
						}
						substr($attrs["name"], 0, -1);
					}
				}else{
					$regist = new Registration('Individual');
					$regist->initIndv();			
					$attrs = (array)$regist->attributes;
					$attrs["name"] = $attrs["firstName"].' '.$attrs["lastName"];
				}
			}else{
				$attrs = (array)$this->attributes;
				$attrs["name"] = $attrs["firstName"].' '.$attrs["lastName"];
			}

			foreach($attrs as $key=>$attr){
				$attrs[$key] = rawurlencode($attr);
			}
			
			$this->parentId = empty($this->parentId) ? -1 : $this->parentId;


            /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
            if ($ip == '162.13.154.241') {
                $start = microtime(true);
            }*/

            $result = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/RegNewAccountInSystem?guid='.Yii::app()->user->id.'&platformID='.$platform.'&address='.$attrs["address"].'&city='.$attrs["city"].'&country='.$attrs["country"].'&email='.$attrs["email"].'&phone='.$attrs["phone"].'&name='.$attrs["name"].'&accountID=-1&userLogin='.$userLogin.'&parentId='.$this->parentId.'&balance='.$balance.'&leverage='.$leverage.'&accountGroup='.$this->accountGroup);

            /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
            if ($ip == '162.13.154.241') {
                var_dump(round(microtime(true) - $start, 4), $result, Yii::app()->params['json_server'].'/API/Registration/RegNewAccountInSystem?guid='.Yii::app()->user->id.'&platformID='.$platform.'&address='.$attrs["address"].'&city='.$attrs["city"].'&country='.$attrs["country"].'&email='.$attrs["email"].'&phone='.$attrs["phone"].'&name='.$attrs["name"].'&accountID=-1&userLogin='.$userLogin.'&parentId='.$this->parentId.'&balance='.$balance.'&leverage='.$leverage.'&accountGroup='.$this->accountGroup);die();
            }*/

            /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
            if ($ip == '162.13.154.241') {
                var_dump($result, Yii::app()->params['json_server'].'/API/Registration/RegNewAccountInSystem?guid='.Yii::app()->user->id.'&platformID='.$platform.'&address='.$attrs["address"].'&city='.$attrs["city"].'&country='.$attrs["country"].'&email='.$attrs["email"].'&phone='.$attrs["phone"].'&name='.$attrs["name"].'&accountID=-1&userLogin='.$userLogin.'&parentId='.$this->parentId.'&balance='.$balance.'&leverage='.$leverage.'&accountGroup='.$this->accountGroup);die();
            }*/

            return $result;
	 	}	

		public function getCurOfficeCode(){
			$countryCode = Yii::app()->geoip->lookupCountryCode(Yii::app()->request->getUserHostAddress());
		
			$countryArray = array(
				'BG'=>array("BG","EU","AD","AL","AM","AT","AZ","BA","BE","BY","CH","DE","DK","EE","ES","FI","FR","GR","HR","HU","IE","IS","IT","LI","LT","LU","LV","MC","MD","MK","MT","NL","NO","PT","RO","SE","SI","SK","SL","TR","VA","RS"),
				'AU'=>array("AP","AF","AM","AZ","BD","BH","BN","BT","GD","HU","IL","IN","IQ","IR","JM","JP","KH","KP","KR","KZ","MM","MN","MV","MY","NP","OM","PK","TJ","TM","UZ","VN"),
				'AE'=>array("AE"),
				'NZ'=>array("NZ"),
				/*'US'=>array("US"),*/
				'EG'=>array("US"),
				'CN'=>array("CN"),
				'UA'=>array("UA"),
				'KW'=>array("KW"),
				'GB'=>array("GB"),
				'MX'=>array("MX"),
				'RU'=>array("RU"),
				'IN'=>array("IN"),
				'CZ'=>array("CZ"),
				'PL'=>array("PL"),
			);
			
			$curGeoIp ='';
			if(!empty($countryCode)){
				foreach($countryArray as $key=>$value){
					if(in_array($countryCode, $value)){
						$curGeoIp = $key;
						break;
					}
				}
			}
			$curGeoIp = ($curGeoIp == '') ? wlParams::get('defaultOfficeCode') : $curGeoIp;
			
			return $curGeoIp;
		}
		
		public function checkParent($attribute,$params){
			if(wlParams::get('officeCode') == 3){
				$this->code = ($this->code == Yii::t("main","756_parent_code")) ? -1 : $this->code;
				
				if($this->role != -1 || $this->code != -1){
					if($this->role != -1 && $this->code == -1){
						$this->addError('code', Yii::t("main","36_cannot_be_blank", array('{attribute}'=>$this->getAttributeLabel('code'))));
						$this->clearErrors('role');
					}
					if($this->role == -1 && $this->code != -1){
						$this->addError('role', Yii::t("main","36_cannot_be_blank", array('{attribute}'=>$this->getAttributeLabel('role'))));
						$this->clearErrors('code');				
					}
				}else{
					$this->clearErrors('role');
					$this->clearErrors('code');				
				}

			}
		}
		
	public function checkNoorCodes($role, $code){
		if($_SERVER['HTTP_HOST'] == 'my.noorcap.ae'){
			$codes = array(
				'3'=>array('415'=>'457','414'=>'458','413'=>'459','412'=>'460','402'=>'461','405'=>'462','401'=>'463','400'=>'464','411'=>'465','356'=>'469','373'=>'470','374'=>'471','375'=>'472','376'=>'473','377'=>'474','378'=>'475','381'=>'476','390'=>'477','391'=>'478','392'=>'479','393'=>'480','394'=>'481','395'=>'482','396'=>'483','397'=>'484','398'=>'485','410'=>'486','431'=>'487','435'=>'488','436'=>'489','438'=>'490','439'=>'491','440'=>'492','448'=>'493','450'=>'494','451'=>'495','452'=>'496','453'=>'497','454'=>'498','455'=>'499','456'=>'500','457'=>'501','458'=>'502','459'=>'467','460'=>'503','461'=>'466','462'=>'468','7002'=>'504','399'=>'505'),
				'4'=>array('7156'=>'7505','7166'=>'7506','7167'=>'7507','7168'=>'7508','7169'=>'7509','7170'=>'7510','7155'=>'7511','7157'=>'7512','7158'=>'7513','7159'=>'7514','7160'=>'7515','7161'=>'7516','7162'=>'7517','7163'=>'7518','7164'=>'7519','7165'=>'7520','7145'=>'7521','7142'=>'7522','7141'=>'7523','7123'=>'7525','7127'=>'7526','7129'=>'7527','7154'=>'7528','7108'=>'7529','7149'=>'7530','7128'=>'7531','4982'=>'7536','7031'=>'7537','7035'=>'7538','7055'=>'7539','7092'=>'7540','7046'=>'7541','6133'=>'7543','4980'=>'7544','7024'=>'7545','7036'=>'7546','7050'=>'7547','5110'=>'7548','5111'=>'7549','5112'=>'7550','5113'=>'7551','5114'=>'7552','5115'=>'7553','5116'=>'7554','5117'=>'7555','5118'=>'7556','5119'=>'7557','5105'=>'7558','5106'=>'7559','5107'=>'7560','5108'=>'7561','5109'=>'7562','5100'=>'7563','5101'=>'7564','5102'=>'7565','5103'=>'7566','5104'=>'7567','5145'=>'7568','5146'=>'7569','5147'=>'7570','5148'=>'7571','5149'=>'7572','333'=>'7573','4402'=>'7574','4530'=>'7575','4844'=>'7576','4845'=>'7577','4846'=>'7578','4847'=>'7579','4848'=>'7580','4870'=>'7581','4914'=>'7582','4915'=>'7583','4929'=>'7585','4947'=>'7586','4960'=>'7587','4976'=>'7588','4981'=>'7589','6097'=>'7590','6117'=>'7591','7005'=>'7593','7012'=>'7594','6118'=>'7595','6119'=>'7596','4823'=>'7597','4849'=>'7598','4987'=>'7599','4988'=>'7600','6095'=>'7601','6096'=>'7602','6120'=>'7603','7022'=>'7604','7025'=>'7605','7059'=>'7606','7060'=>'7607','7061'=>'7608','7075'=>'7609','7089'=>'7610','7094'=>'7611','7105'=>'7612','7106'=>'7613','7117'=>'7614','7120'=>'7615','7133'=>'7616','7139'=>'7617','6121'=>'7618','6122'=>'7619','6123'=>'7620','4918'=>'7621','6124'=>'7622','7028'=>'7623','7030'=>'7624','4916'=>'4916','4919'=>'4919','4979'=>'7625','6125'=>'7626','7026'=>'7627','7033'=>'7628','7057'=>'7629','7058'=>'7630','7067'=>'7631','7116'=>'7632','6126'=>'7633','4962'=>'7634','6127'=>'7635','6128'=>'7636','7077'=>'7637','7082'=>'7638','7088'=>'7639','7137'=>'7640','6129'=>'7641','6130'=>'7642','6131'=>'7643','6132'=>'7644','7032'=>'7645','7043'=>'7646','7045'=>'7647','7062'=>'7648','7096'=>'7649','7102'=>'7650','7118'=>'7651','7126'=>'7652','7135'=>'7653','7532'=>'7654','7063'=>'7655','7064'=>'7656','7065'=>'7657','7068'=>'7658','7069'=>'7659','7074'=>'7660','7078'=>'7661','7079'=>'7662','7081'=>'7663','7147'=>'7664','7153'=>'7665','7531'=>'7666','7171'=>'7667','7533'=>'7668')
			);
			if(isset($codes[$role][$code])){
				return $codes[$role][$code];
			}else{
				return $code;
			}
		}else{
			return $code;
		}
	}

        
}
