<?php

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class LoginForm extends CFormModel
{
 
	public $username = '';
	public $password = '';
	public $rememberMe;
//	public $forgotPass;
	public $forgotEmail;

	public $password_old;
	public $password_new;
    public $capchaText;

    private $_identity;


	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules(){
		return array(				
			array('username, password, forgotEmail', 'filter', 'filter'=>'trim'),	
			
			array('username, password', 'required', 'on'=>'login, email', 'message'=> Yii::t("main","36_cannot_be_blank")),

            array('username', 'length', 'is'=>10, 'on'=>'login'),
            array('username', 'email', 'on'=>'email', 'message' => Yii::t("main","22_this_email_address_is_not_a_valid")),

			array('password', 'length', 'min'=>3, 'max'=>50, 'on'=>'login, email'),
			array('rememberMe', 'boolean', 'on'=>'login, email'),
			array('password', 'authenticate', 'on'=>'login, email'),
                    
			array('username', 'match', 'pattern' => '/^guid$/', 'on'=>'loginByGuid'),	
			array('password', 'match', 'pattern' => '/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/', 'on'=>'loginByGuid'),	

			//--------------------------------------------------					
			array('forgotEmail', 'length', 'min'=>6, 'max'=>50, 'allowEmpty'=>false, 'tooLong'=>Yii::t("main","526_max_pass_length"), 'tooShort'=>Yii::t("main","527_min_pass_length"), 'on'=>'forgot'),	
			array('forgotEmail', 'myforgot', 'on'=>'forgot', 'message'=>Yii::t("main","21_this_email_or_login_is_not_a_valid")),
            array('capchaText', 'required', 'on'=>'forgot', 'message'=> Yii::t("main","36_cannot_be_blank")),

			array('password_new, password_old', 'required','message'=> Yii::t("main","36_cannot_be_blank"), 'on'=>'passchange'),                        
			array('password_new, password_old', 'length', 'min'=>6, 'max'=>50, 'allowEmpty'=>false, 'on'=>'passchange', 'tooLong'=>Yii::t("main","526_max_pass_length"), 'tooShort'=>Yii::t("main","527_min_pass_length")),
			array('password_new, password_old', 'match','pattern' => '/^[a-z0-9`~!"@№%#\$;:\?\/\\&\*\+-_\(\)=\{\}\[\]\'|\<\>\s]*$/i','message' => Yii::t("main","34_only_latin_characters_allowed_for"), 'on'=>'passchange'),	
			
			array('password', 'length', 'min'=>3, 'max'=>50, 'allowEmpty'=>true, 'on'=>'password_set'),
			array('password', 'match','pattern' => '/^[a-z0-9`~!"@№%#\$;:\?\/\\&\*\+-_\(\)=\{\}\[\]\'|\<\>\s]*$/i','message' => Yii::t("main","34_only_latin_characters_allowed_for"), 'on'=>'password_set, login'),	
		);
	}
	
	public function myforgot($attribute, $params){
		/*if(preg_match('~^[0-9]*$~i',$this->forgotEmail)){
			$ev = new CNumberValidator();
			$ev->attributes = explode(',', $attribute);
			foreach ($params as $key=>$value)
			$ev->$key = $value;
			$ev->validate($this);	
		}else{*/
			$ev = new CEmailValidator();
			$ev->attributes = explode(',', $attribute);
			foreach ($params as $key=>$value)
			$ev->$key = $value;
			$ev->validate($this);	
		//}
	}
	
	
	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
	    $labels = array(
            'username'=>Yii::t("main","20_Login"),
            'password'=>Yii::t("main","327_password"),
            'rememberMe'=>wlTrans::get('login.remember_me'),
            'forgotEmail'=>Yii::t("main","24_this_email_address"),
            'capchaText'=>Yii::t("main","1058_capcha"),
            'password_new' => Yii::t("main",'506_new_password'),
            'password_old' => Yii::t("main",'505_old_password'),
        );

	    if(Yii::app()->params['login_by_email']) {
            $labels['username'] = Yii::t("main","44_email");
        }

		return $labels;
	}

	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function authenticate($attribute,$params)
	{
        $errorText = (Yii::app()->params['login_by_email']) ? '25_incorrect_email_or_password' : '25_incorrect_username_or_password';

        if($this->getErrors()==NULL){
			$this->_identity=new UserIdentity($this->username,$this->password);
			if(!$this->_identity->authenticate() && (!Yii::app()->request->isAjaxRequest || isset($_POST['submitButton']))){
				//var_dump(!Yii::app()->request->isAjaxRequest, isset($_POST['submitButton']));die();
				$this->clearErrors();

				$this->addError('password',Yii::t("main",$errorText));
				$this->addError('username',Yii::t("main",$errorText));
			}
		}else{
			if(!empty($this->username) && !empty($this->password)){
				$this->clearErrors();
				$this->addError('password',Yii::t("main",$errorText));
				$this->addError('username',Yii::t("main",$errorText));
			}
		}
	}

	/**
	 * Logs in the user using the given username and password in the model.
	 * @return boolean whether login is successful                                                                                                  
	 */
	public function login(){

		if($this->_identity===null)
		{
			$this->_identity=new UserIdentity(trim($this->username),$this->password);
			$this->_identity->authenticate();
		}
		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
		{
			$duration=$this->rememberMe ? 3600*24*5 : 1500; // 5 days / 25 minutes
			
			Yii::app()->user->login($this->_identity,$duration);
                        
			$token = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Accounts/SetDefaultLanguage?guid=' . Yii::app()->user->id.'&defaultLanguage='.Yii::app()->language);

			return true;
		}
		else
			return false;
	}
        
	public function checkEmail() {
        if( Yii::app()->params['type'] == 'eforex' || Yii::app()->params['type'] == 't2' ){
            if(Yii::app()->params['login_by_email']){
                $rez = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/GetPasswordForLogin?login='.$this->forgotEmail.'&capchaText='.$this->capchaText.'&groupCode='.wlParams::get('officeLetterCode'));
            }else{
                $rez = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/GetPasswordForLogin?login='.$this->forgotEmail.'&capchaText='.$this->capchaText);
            }
        }else{
            if(Yii::app()->params['login_by_email']){
                $rez = Yii::app()->curlWithHeaders->get(Yii::app()->params['json_server'].'/API/Registration/GetPasswordForLogin?login='.$this->forgotEmail.'&capchaText='.$this->capchaText.'&groupCode='.wlParams::get('officeLetterCode'), false, ['IpAddress' => isset($_COOKIE['guest_id']) ? $_COOKIE['guest_id'] : $_SERVER['REMOTE_ADDR']]);


            }else{
                $rez = Yii::app()->curlWithHeaders->get(Yii::app()->params['json_server'].'/API/Registration/GetPasswordForLogin?login='.$this->forgotEmail.'&capchaText='.$this->capchaText, false, ['IpAddress' => isset($_COOKIE['guest_id']) ? $_COOKIE['guest_id'] : $_SERVER['REMOTE_ADDR']]);
            }
        }

		if($rez == 'UserIsDisabled'){
			return $rez;
		}

		if( isset($rez->State) && $rez->State==0) return true; 
		else return false;
	}

		
	public function changePassword($login, $password){
		//var_dump(Yii::app()->params['json_server'].'/API/Accounts/ChangePassword?guid='.Yii::app()->user->id.'&login='.$login.'&password='.rawurlencode($password));
		$rez = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Accounts/ChangePassword?guid='.Yii::app()->user->id.'&login='.$login.'&password='.rawurlencode($password));   
		//var_dump($rez);
		return $rez;
	}
	
	public function checkOldPassword(){
		$account = new Account();
        $info = $account->GetInfo();
		$UserLogin=$account->GetLogin();
		if($info->Type==6){
			$User = new RegistrationTrader();
			$User->initTrader();
		}else{
			$User = new Registration();
			$User->initIndv();	
		}

		if(!empty($this->password_old)){
			$token = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Accounts/Login?login='.$UserLogin.'&password='.rawurlencode($this->password_old));

            if($token!='IncorrectLoginOrPassword'){
				return 'success';
            }else{
                $this->addError('password_old', $this->getAttributeLabel('password_old').' '.Yii::t("main","509_incorrect"));
				return 'error';
			}
		}else{
			return 'old password empty';
		}
	}

    public static function getUrlForLoginRedirect($officeCode, $guid)
    {
        $urlsArray = array(
            3 => 'https://my.ebmfn.com',
            13 => 'https://my.bmfn.com.au',
            14 => 'http://my.bmfn.eu',
            28 => 'https://my.eforex.cn',
            29 => 'https://my.eforex.com',
            30 => 'http://my.upfx.com',
            44 => 'https://my.sifxmarkets.sa.com',
            45 => 'https://my.uktkfx.com',
            47 => 'https://my.goldenbridgefx.com',
            48 => 'https://my.eforex.com',
            50 => 'https://mycabinet.gntcapital.com',
            52 => 'https://my.emiratesmf.com',
            55 => 'https://my.fttmarkets.com',
            56 => 'https://au.bmfnprime.com',
            57 => 'https://eu.bmfnprime.com',
            58 => 'https://global.bmfnprime.com',
            61 => 'https://lat.bmfn.com',
            64 => 'https://portal.t2trade.com',
            67 => 'https://cabinet.tradingmarket.live',
            74 => 'https://acceso.globaltrading.capital',
            76 => 'https://gabinete.goworldtrading.com',
            78 => 'https://my.efxcpi.com',
            79 => 'https://my.tradeonline.market',
            87 => 'https://futuresolutions.bostonunisoft.com',
            88 => 'https://my.limitlessfx.me',
            89 => 'https://my.marketis.me',



        );
        

        if(in_array($officeCode, array_keys($urlsArray))){
            return $urlsArray[$officeCode].'/login.html?guid='.$guid;
        }else{
            return 'https://my.bmfn-solutions.com/login.html?guid='.$guid;
        }


	}


}
