<?php

/**
 * This is the model class for table "{{_user}}".
 *
 * The followings are the available columns in table '{{_user}}':
 * @property string $id
 * @property string $username
 * @property string $password
 * @property string $fullname
 * @property string $company_email_address
 * @property string $designation
 * @property string $company_name
 * @property string $mobile_number
 * @property string $country_id
 * @property string $city
 * @property integer $industry_id
 * @property integer $user_type_id
 * @property string $postal_address
 * @property string $zip
 * @property string $created
 * @property string $isActive
 * @property string $isConfirmed
 * @property string $isRequestedNewPassword
 * @property string $authCode
 *
 * The followings are the available model relations:
 * @property UserType $userType
 * @property Country $country
 * @property Industry $industry
 */
class User extends CActiveRecord
{
	public $repeat_password;
	public $old_password;
	public $verifyCode;
	public $rememberMe;
	private $_identity;
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{_user}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('fullname,password, company_email_address, designation, company_name, mobile_number, country_id, industry_id, user_type_id, postal_address, telephone', 'required','on'=>array('user_signup','signup','update')),
			array('password','required','on'=>array('login','change_password','change_my_password')),
			array('repeat_password','required','on'=>array('user_signup','change_password','change_my_password')),
			array('old_password','required','on'=>array('change_my_password')),
			
			array('company_email_address','required','on'=>array('login','recover')),
			array('repeat_password', 'compare', 'compareAttribute'=>'password','on'=>array('user_signup','change_password','change_my_password')),
			
			array('mobile_number, industry_id, user_type_id', 'numerical', 'integerOnly'=>true),
			array('password', 'length', 'max'=>50,'min'=>6),
			array('mobile_number', 'length', 'max'=>15,'min'=>10),
			
			array('personal_email,company_email_address', 'email'),
			array('password', 'authenticate', 'on'=>'login'),
			
			array('company_email_address','unique','on'=>array('user_signup','signup','update')),
			
			array('wallet_password','required','on'=>'wallet'),
			
			
			
			
			array('fullname, company_email_address,sales_man, designation, company_name, city, authCode, wallet_password', 'length', 'max'=>255),
			array('mobile_number, zip, telephone', 'length', 'max'=>15),
			array('country_id', 'length', 'max'=>5),
			array('isActive, isConfirmed, isRequestedNewPassword,isNewUser,isWalletPaswdRequested', 'length', 'max'=>1),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, password, fullname, company_email_address, designation, company_name, mobile_number, country_id, city, industry_id, user_type_id, postal_address, zip, created, isWalletPaswdRequested', 'safe', 'on'=>'search'),
			
			array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>'user_signup'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'userType' => array(self::BELONGS_TO, 'UserType', 'user_type_id'),
			'country' => array(self::BELONGS_TO, 'Country', 'country_id'),
			'industry' => array(self::BELONGS_TO, 'Industry', 'industry_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'password' => 'Password',
			'wallet_password'=>'Wallet Password',
			'repeat_password'=>'Repeat password',
			'old_password'=>'Old password',
			'fullname' => 'Full Name',
			'company_email_address' => 'Email Address (User Name)',
			'designation' => 'Designation',
			'company_name' => 'Company Name',
                        'telephone' => 'Telephone',
                        'sales_man'=>'Sales Man',
			'mobile_number' => 'Mobile Number',
			'country_id' => 'Country',
			'city' => 'City',
			'industry_id' => 'Industry',
			'user_type_id' => 'Type of user',
			'postal_address' => 'Postal Address',
			'zip' => 'Zip',
			'created' => 'Created',
			'isActive' => 'Is Active',
			'isConfirmed' => 'Is Confirmed',
			'isRequestedNewPassword' => 'Is Requested New Password',
			'authCode' => 'Auth Code',
			'verifyCode'=>'Verification Code',
			
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		//$criteria->compare('username',$this->username,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('fullname',$this->fullname,true);
		$criteria->compare('company_email_address',$this->company_email_address,true);
		$criteria->compare('designation',$this->designation,true);
		$criteria->compare('company_name',$this->company_name,true);
		$criteria->compare('mobile_number',$this->mobile_number,true);
		$criteria->compare('country_id',$this->country_id,true);
		$criteria->compare('city',$this->city,true);
		$criteria->compare('industry_id',$this->industry_id);
		$criteria->compare('user_type_id',$this->user_type_id);
		$criteria->compare('postal_address',$this->postal_address,true);
		$criteria->compare('zip',$this->zip,true);
		$criteria->compare('created',$this->created,true);
		$criteria->compare('isActive',$this->isActive,true);
		$criteria->compare('isConfirmed',$this->isConfirmed,true); 	
		$criteria->compare('isNewUser',$this->isNewUser,true);
		$criteria->compare('isWalletPaswdRequested',$this->isWalletPaswdRequested);
		$criteria->compare('authCode',$this->authCode,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'sort'=>array(
			'defaultOrder'=>'t.id DESC',
			),
			'pagination'=>array('pageSize'=>Yii::app()->params['defaultPageSize'])
		));
	}
	
	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function authenticate($attribute,$params)
	{
		if(!$this->hasErrors())
		{
			$this->_identity=new UserIdentity($this->company_email_address,$this->password);
			if(!$this->_identity->authenticate())
				$this->addError('password','Incorrect username or password.');
		}
	}

	/**
	 * 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($this->company_email_address,$this->password);
			$this->_identity->authenticate();
		}
		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
		{
			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
			Yii::app()->user->login($this->_identity,$duration);
			return true;
		}
		else
		{
			return false;
		}
	}
	
	/* bfeore save function for password enecryption 
	* 
	*/
	function beforeSave()
	{
		if(isset($_POST['User']['password']) && $_POST['User']['password']!='')
			$this->password	=	md5($_POST['User']['password']);
		return true;
	}
	
	public function getAllusers($type_id=null,$isActive='Y',$needList=false)
	{
		$condition	=	'isActive =  "'.$isActive.'"';
		if($type_id!=null)
			$condition	.=	' AND user_type_id =  '.$type_id;
		$model	=	User::model()->findAll(array('condition'=>$condition,'order'=>'id desc'));
		if($needList)
			return CHtml::listData($model, 'id', 'fullname');
		else
			return ($model);
	}
}
