<?php

/**
 * This is the model class for table "{{user}}".
 *
 * The followings are the available columns in table '{{user}}':
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $email
 * @property string $phno
 * @property string $first_name
 * @property string $last_name
 * @property string $company_id
 * @property string $designation
 * @property integer $level
 * @property string $token
 * @property integer $created_by
 * @property string $created_date_time
 * @property integer $updated_by
 * @property string $updated_date_time
 * @property string $isActive
 * @property string $app_verion
 */
class User extends CActiveRecord
{
	/**
	 * @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('username,first_name,last_name,email,user_group_id,password', 'required'),
			array('level, created_by, updated_by', 'numerical', 'integerOnly'=>true),
			array('username, password, email, phno, first_name, last_name', 'length', 'max'=>255),
			array('designation', 'length', 'max'=>100),
			array('isActive', 'length', 'max'=>1),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, username, password, email, phno, first_name, last_name, company_id, designation, level, token, created_by, created_date_time, updated_by, updated_date_time, isActive, app_verion', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @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(
			 'usergroups' => array(self::BELONGS_TO, 'UserGroup', 'user_group_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'username' => 'Username',
			'password' => 'Password',
			'email' => 'Email',
			'phno' => 'Phno',
			'first_name' => 'First Name',
			'last_name' => 'Last Name',
			'company_id' => 'Company',
			'designation' => 'Designation',
			'level' => 'level0 Admin, level1 Member',
			'token' => 'Token',
			'created_by' => 'Created By',
			'created_date_time' => 'Created Date Time',
			'updated_by' => 'Updated By',
			'updated_date_time' => 'Updated Date Time',
			'isActive' => 'Is Active',
            'user_group_id' => 'User Group',
			'app_verion' => 'used in mobile_user',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('username',$this->username,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('phno',$this->phno,true);
		$criteria->compare('first_name',$this->first_name,true);
		$criteria->compare('last_name',$this->last_name,true);
		$criteria->compare('company_id',$this->company_id,true);
		$criteria->compare('designation',$this->designation,true);
		$criteria->compare('level',$this->level);
		$criteria->compare('token',$this->token,true);
		$criteria->compare('created_by',$this->created_by);
		$criteria->compare('created_date_time',$this->created_date_time,true);
		$criteria->compare('updated_by',$this->updated_by);
		$criteria->compare('updated_date_time',$this->updated_date_time,true);
		$criteria->compare('isActive',$this->isActive,true);
		$criteria->compare('app_verion',$this->app_verion,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
	
	public function authenticate($attribute, $params) {
        if (!$this->hasErrors()) {
            $this->_identity = new UserIdentity($this->username, $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->username, $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;
        }
    }

    public function findBytoken($token = NULL) {
        $model = new User;
        if (trim($token) != NULL) {
            $model = User::model()->find(array('condition' => 't.token="' . trim($token) . '" AND t.isActive="Y"'));
        }
        return $model;
    }

    public function getFullname() {
        return $this->first_name . " " . $this->last_name;
    }

    /* bfeore save function for password enecryption
     *
     */

    function beforeSave() {
        if (isset($_POST['User']['password']) && $_POST['User']['password'] != '') {
            //START Code modified on 08-04-2016 for secured password
            $salt = '$2a$10$1qAz2wSx3eDc4rFv5tGb5t';
            $this->password = crypt($_POST['User']['password'], $salt);
            //END Code modified on 08-04-2016 for secured password
            //$this->password = crypt($_POST['User']['password'], $_POST['User']['password']);
        }
        return true;
    }
    
     public static function getUser() {
        $condition = 'employee_id = 0 AND isActive =  "Y" AND company_id=' . Yii::app()->user->master_user_company_id . ' AND level>0';
        $model = self::model()->findAll(array('condition' => $condition, 'order' => 't.first_name,t.username'));
        return CHtml::listData($model, 'id', 'fullname');
    }
    
    public static function getUserbyId($ids) {
        $condition = ' id IN ('.$ids.') AND employee_id = 0 AND isActive =  "Y" AND company_id=' . Yii::app()->user->master_user_company_id . ' AND level>0';
        $model = self::model()->findAll(array('condition' => $condition, 'order' => 't.first_name,t.username'));
        return CHtml::listData($model, 'id', 'fullname');
    }
}
