<?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 $isActive
 *
 * The followings are the available model relations:
 * @property Company[] $companies
 * @property CompanyContact[] $companyContacts
 * @property CreditNote[] $creditNotes
 * @property DeliveryNotes[] $deliveryNotes
 * @property GoodsReturn[] $goodsReturns
 * @property Invoice[] $invoices
 * @property Lead[] $leads
 * @property MasterFile[] $masterFiles
 * @property Order[] $orders
 * @property Quotes[] $quotes
 * @property Store $store
 */
class User extends CActiveRecord
{

    const MainDb = 'dlinkmea_erp_purchase';

    /**
     * @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,user_group_id,first_name,last_name,branch_id,email,phno, password', 'required'),

            array('username,user_group_id,first_name,last_name', 'required'),
            array('username,first_name,last_name', 'required', 'on' => 'passwordreset'),
            array('department_head_id,hr_connected_employee_id,location_id', 'numerical', 'integerOnly' => true),
            array('staff_id', 'unique'),
            array('password', 'required', 'on' => 'add'),
            array('username', 'unique', 'criteria' => array('condition' => 'isActive="Y" AND company_id=' . Yii::app()->user->master_user_company_id)),
            array('username,  first_name, last_name, email, designation,user_group_id, auth_code', 'length', 'max' => 255),
            //            array('email','email','checkMX' => true),
            //            array('email','unique', 'criteria'=>array('condition'=>'isActive="Y"')),
            array('phno,token,staff_id', 'length', 'max' => 255),
            //  array('phno','numerical'),
            array('isActive', 'length', 'max' => 1),
            array('signature', 'length', 'max' => 5000),
            array('username', 'filter', 'filter' => 'trim'),
            array('level', 'checkLevel'),
            // array('outlet_id', 'checkOutlet'),
            array('technician_id', 'technician_validate'),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id,level, username, password,token, isActive,created_by,staff_id,updated_by,created_datetime,updated_datetime', '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(
            'own_company' => array(self::BELONGS_TO, 'MasCompany', 'company_id'),
            'companies' => array(self::HAS_MANY, 'Company', 'crm_user_id'),
            'companyContacts' => array(self::HAS_MANY, 'CompanyContact', 'crm_user_id'),
            'creditNotes' => array(self::HAS_MANY, 'CreditNote', 'crm_user_id'),
            'deliveryNotes' => array(self::HAS_MANY, 'DeliveryNotes', 'crm_user_id'),
            'goodsReturns' => array(self::HAS_MANY, 'GoodsReturn', 'crm_user_id'),
            'invoices' => array(self::HAS_MANY, 'Invoice', 'crm_user_id'),
            'leads' => array(self::HAS_MANY, 'Lead', 'crm_user_id'),
            'masterFiles' => array(self::HAS_MANY, 'MasterFile', 'crm_user_id'),
            'orders' => array(self::HAS_MANY, 'Order', 'crm_user_id'),
            'quotes' => array(self::HAS_MANY, 'Quotes', 'crm_user_id'),
            'store' => array(self::HAS_ONE, 'Store', 'id'),
            //'ownBranch' => array(self::BELONGS_TO, 'MasCompanyBranch', 'branch_id'),
            'userGroup' => array(self::BELONGS_TO, 'MasUserGroup', 'user_group_id'),
            'warehouse' => array(self::BELONGS_TO, 'MasInventoryWarehouse', 'available_warehouses'),
            'technician' => array(self::BELONGS_TO, 'Technician', 'technician_id'),
            'employee_details' => array(self::BELONGS_TO, 'Employee', 'employee_id'),
        );
    }

    /*public function checkOutlet($attribute, $params) {

        $modelCompanySettings = new MasCompanySettings();
        $modelCompanySettings = $modelCompanySettings->find(array('condition'=>'crm_company_id='.(int) Yii::app()->user->master_user_company_id));    


    }*/

    public function checkLevel($attribute, $params)
    {
        if ($this->level == 3 && (int) $this->available_warehouses > 0) { //level
            $level = 3;
            $condition = 't.isActive="Y"';
            $condition .= " AND t.level=" . $level;
            $condition .= " AND t.available_warehouses=" . $this->available_warehouses;

            $model_list = self::model()->findAll(array('condition' => $condition, 'order' => 'first_name'));

            /* $condition .= " AND t.id=" . $this->available_warehouses;
              $model_list = self::model()->findAll(array('condition' => $condition, 'order' => 'first_name')); */

            $modelwarehouse = MasInventoryWarehouse::model()->find(array('condition' => 't.id="' . $this->available_warehouses . '" '));

            if ($model_list[0]['id'] !== $this->id) {

                if (count($model_list) > 0) {
                    $this->addError('id', 'Company Login level allows only ONE user in ' . $modelwarehouse->warehouse_name);
                }
            }
        }
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'username' => 'User Name',
            'available_warehouses' => 'Warehouse',
            'password' => 'Password',
            'isActive' => 'Is Active',
            'user_group_id' => 'User Group ID',
            'phno' => 'Phone No.',
            'email' => 'E-mail',
            'first_name' => 'First Name',
            'last_name' => 'Last Name',
            'designation' => 'Designation',
            'auth_code' => 'Auth Code',
            'signature' => 'Signature',
            'created_date_time' => 'Created Date',
            'created_by' => 'Created By',
            'updated_date_time' => 'Last Updated Date',
            'updated_by' => 'Last Updated By',
            'connected_employee_id' => 'Connected Employee',
            'outlet_id' => 'Outlet'
        );
    }

    /**
     * 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->addCondition('isActive="Y" AND id<>' . Yii::app()->user->id . ' AND  t.company_id=' . Yii::app()->user->master_user_company_id);
        /* if(Yii::app()->user->authorised_user==1)
          {
          $criteria->addCondition('isActive="Y" AND id<>' . Yii::app()->user->id . ' AND  t.company_id=' . Yii::app()->user->master_user_company_id);
          }
          else
          {
          $criteria->addCondition('isActive="Y" AND id<>' . Yii::app()->user->id . ' AND  t.company_id=' . Yii::app()->user->master_user_company_id.' AND  t.branch_id=' . Yii::app()->user->master_user_branch_id);
          } */

        return new CActiveDataProvider($this, array(
            'pagination' => array(
                'pageSize' => 5,
            ),
            'criteria' => $criteria,
            'sort' => array(
                'defaultOrder' => 't.user_group_id ,t.username ASC',
            ),
        ));
    }

    /**
     * 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);
    }

    /**
     * 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->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 getLeadOwners($lead_owner_id = 0)
    {
        $condition = 'level > 0 AND is_lead_owner = "Y" AND isActive= "Y" AND company_id=' . Yii::app()->user->master_user_company_id;
        if ($lead_owner_id > 0) {
            $condition .= " AND id=" . $lead_owner_id;
        }
        $model = self::model()->findAll(array('condition' => $condition, 'order' => 'first_name'));
        return CHtml::listData($model, 'id', 'fullname');
    }

    public static function getLeadOwnersForIncentiveCalc1()
    {
        if ((int) Yii::app()->user->havePermissionOn['other_reports_incentives_show_all']) {
            //$condition = 'branch_id=' . Yii::app()->user->master_user_branch_id . ' AND isActive =  "Y"';
            $condition = 'isActive =  "Y" AND company_id=' . Yii::app()->user->master_user_company_id;
            $model = self::model()->findAll(array('select' => array('id', 'first_name', 'last_name'), 'condition' => $condition, 'order' => 't.first_name,t.username'));
            return CHtml::dropDownList('incentive_lead_lead_owner', '', CHtml::listData($model, 'id', 'fullname'), array(
                'prompt' => 'All',
                'class' => 'sales-group-search tooltipster',
                'title' => 'Please select Lead Owner'
            ));
        } else
            return self::model()->findByPK(Yii::app()->user->id)->fullname;
    }

    public function getLeadOwnersForIncentiveCalc()
    {
        if ((int) Yii::app()->user->havePermissionOn['other_reports_incentives_show_all']) {
            //$condition = 'branch_id=' . Yii::app()->user->master_user_branch_id . ' AND isActive =  "Y"';
            $condition = 'isActive =  "Y" AND company_id=' . Yii::app()->user->master_user_company_id;
            $model = self::model()->findAll(array('condition' => $condition, 'order' => 't.first_name,t.username'));
            return CHtml::dropDownList('incentive_lead_lead_owner', '', CHtml::listData($model, 'id', 'fullname'), array(
                'prompt' => 'All',
                'ajax' => array(
                    'type' => 'POST',
                    'dataType' => 'json',
                    'url' => CController::createUrl('site/FetchFilesByLeadowner'),
                    'success' => 'function(data){
                              $("#incentive_file_id").html(data.files);
                             }',
                    'data' => array('leadowner' => 'js:this.value'),
                ),
                'class' => 'sales-group-search tooltipster',
                'title' => 'Please select Lead Owner'
            ));
        } else
            return self::model()->findByPK(Yii::app()->user->id)->fullname;
    }

    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');
    }



    public static function getUser1($id, $level)
    {
        $condition = 'isActive =  "Y" AND company_id=' . Yii::app()->user->master_user_company_id . ' AND NOT designation="Super Admin"';
        $model = self::model()->findAll(array('condition' => $condition, 'order' => 't.first_name,t.username'));
        return CHtml::listData($model, 'id', 'fullname');
    }

    public function getUserApprovalLevel($id, $level)
    {

        if ($level == 'level1_user_id') {
            $level = "level1_user_id";
        } else if ($level == 'level2_user_id') {
            $level = "level2_user_id";
        } else if ($level == 'level3_user_id') {
            $level = "level3_user_id";
        }

        $model_ApprovalLevelDetail = ApprovalLevelDetails::model()->findAll(array('condition' => 'approval_level_id="' . $id . '"'));
        $level1_array = "";
        foreach ($model_ApprovalLevelDetail as $i => $value) {
            $level1_array .= $value->$level . ",";
        }
        $level1_array_str = substr($level1_array, 0, -1);

        //$level1_array   = "5,3";
        $condition = 'isActive =  "Y" AND company_id=' . Yii::app()->user->master_user_company_id . ' AND NOT designation="Super Admin" AND id NOT IN ( ' . $level1_array_str . ' )';
        $model = self::model()->findAll(array('condition' => $condition, 'order' => 't.first_name,t.username'));
        return CHtml::listData($model, 'id', 'fullname');
    }

    public function getUserApprovalLevelEmp($id, $level)
    {

        if ($level == 'level1_user_id') {
            $level = "level1_user_id";
        } else if ($level == 'level2_user_id') {
            $level = "level2_user_id";
        } else if ($level == 'level3_user_id') {
            $level = "level3_user_id";
        }

        if ($id > 0) {
            $model_ApprovalLevelDetail = ApprovalLevelDetails::model()->findAll(array('condition' => 'approval_level_id="' . $id . '"'));
            $level1_array = "";
            foreach ($model_ApprovalLevelDetail as $i => $value) {
                $level1_array .= $value->$level . ",";
            }
            $level1_array_str = substr($level1_array, 0, -1);
            $condition = 'isActive =  "Y" AND company_id=' . Yii::app()->user->master_user_company_id . ' AND NOT designation="Super Admin" AND id IN ( ' . $level1_array_str . ' )';
            $model = self::model()->findAll(array('condition' => $condition, 'order' => 't.first_name,t.username'));
            return CHtml::listData($model, 'id', 'fullname');
        } else {
            $condition = 'isActive =  "Y" AND company_id=' . Yii::app()->user->master_user_company_id . ' AND id="0"';
            $model = self::model()->findAll(array('condition' => $condition, 'order' => 't.first_name,t.username'));
            return CHtml::listData($model, 'id', 'fullname');
        }
    }

    public function renderUseGroup($data, $row)
    {
        $ugroups = MasUserGroup::model()->findAll('id in (' . $data->user_group_id . ')');
        foreach ($ugroups as $eachGp) {
            $ug[] = $eachGp->group_name;
        }
        return implode(',', $ug);
    }

    public function getSuperios()
    {
        $userGropups = MasUserGroup::model()->findAll('id in (' . $this->user_group_id . ')'); //parentGroup
        foreach ($userGropups as $eachUserGroup) {
            $users = User::model()->findAll('user_group_id in (' . $eachUserGroup->parent_id . ')');
            foreach ($users as $i => $eachUser) {
                $u[] = $eachUser;
            }
        }
        return $u;
    }

    public function getSubordinates()
    {
        $userGropups = MasUserGroup::subGroups($this->user_group_id); //parentGroup
        $u = array(Yii::app()->user->id);
        if (is_array($userGropups) && count($userGropups) > 0) {
            $users = User::model()->findAll('user_group_id in (' . (implode(',', $userGropups)) . ')');
            foreach ($users as $i => $eachUser) {
                $u[] = $eachUser->id;
            }
        }
        return $u;
    }

    public function getName($id)
    {
        $model = User::model()->findByPk($id);
        return ($model->employee_id > 0) ? Yii::app()->controller->ciphertext($model->first_name, "d") . ' ' . Yii::app()->controller->ciphertext($model->last_name, "d") : $model->first_name . " " . $model->last_name;
    }

    public static function getSalesPersionList()
    {

        $condition = 't.isActive="Y" AND user_group_id="15"';

        $model = self::model()->findAll(array('select' => array('id', 'first_name'), 'condition' => $condition));

        return CHtml::listData($model, 'id', 'first_name');
    }

    public static function getSalesman()
    {
        $condition = 't.isActive= "Y" AND t.company_id=' . Yii::app()->user->master_user_company_id . ' AND level=4';
        $model = self::model()->findAll(array('condition' => $condition, 'order' => 'first_name'));
        return CHtml::listData($model, 'id', 'fullname');
    }

    public static function getSalesmanWarehouse()
    {
        $condition = 't.isActive= "Y" AND t.company_id=' . Yii::app()->user->master_user_company_id . ' ';
        $warehouse_id = (int) Yii::app()->user->getState('user_warehouse_id');
        if ($warehouse_id > 0) {
            $condition .= ' AND t.available_warehouses=' . $warehouse_id;
        }
        $model = self::model()->findAll(array('condition' => $condition, 'order' => 'first_name'));
        return CHtml::listData($model, 'id', 'fullname');
    }

    public static function isSalesman()
    {
        $user_id = Yii::app()->user->id;
        $model = self::model()->findByPK($user_id);
        return $model->userGroup->is_salesman;
    }

    public static function getUserModels()
    {
        $condition = 'employee_id = 0 AND isActive =  "Y" AND company_id=' . Yii::app()->user->master_user_company_id;
        $model = self::model()->findAll(array('condition' => $condition, 'order' => 't.first_name,t.username'));
        return $model;
    }

    public function getAvatar()
    {
        return substr($this->first_name, 0, 1) . substr($this->last_name, 0, 1);
    }

    public function get_generate_token()
    {
        $this->token = $this->id . '-' . time();
        $this->update();
    }

    public static function getActiveUsers()
    {
        $condition = 'level > 0 AND isActive= "Y" AND company_id=' . Yii::app()->user->master_user_company_id;
        $model = self::model()->findAll(array('condition' => $condition, 'order' => 'first_name'));
        return CHtml::listData($model, 'id', 'fullname');
    }
    public static function getAllUsers()
    {
        $condition = ' t.level > 0 AND t.level!=2 AND isActive= "Y" AND company_id=' . Yii::app()->user->master_user_company_id;
        $model = self::model()->findAll(array('condition' => $condition, 'order' => 'first_name'));
        return CHtml::listData($model, 'id', 'fullname');
    }

    public function technician_validate($param, $attribute)
    {
        if (!empty($this->technician_id)) {
            $condition = "t.technician_id = " . $this->technician_id;
            if (!empty($this->id)) {
                $condition .= " AND t.id != " . $this->id;
            }
            $model = self::model()->find(['condition' => $condition]);
            if (!empty($model)) {
                $this->addError("technician_id", "Already connected with other user " . $model->getFullname());
            }
        }
    }

    public static function getWarehouses()
    {

        $userId = Yii::app()->user->id;
        $model = self::model()->findByPk($userId);

        if (!$model || empty($model->available_warehouses)) {
            return [];
        }

        $warehouseIds = array_filter(array_map('trim', explode(',', $model->available_warehouses)));

        if (empty($warehouseIds)) {
            return [];
        }
        $criteria = new CDbCriteria();
        $criteria->addInCondition('id', $warehouseIds);
        $criteria->addCondition('isActive = "Y"');
        $criteria->addCondition('warehouse_code != "DAM"');
        $criteria->addCondition('warehouse_code != "TRAN"');
        $criteria->addCondition('warehouse_code != "MIS"');
        $criteria->order = 'warehouse_name ASC';
        $warehouses = MasInventoryWarehouse::model()->findAll($criteria);

        // Return as list: [id => warehouse_name]
        return CHtml::listData($warehouses, 'id', 'warehouse_name');
    }

    public static function getAdmin()
    {
        $criteria = new CDbCriteria();
        $criteria->condition = 'user_group_id = :group AND designation != :designation';
        $criteria->params = [
            ':group' => 1,
            ':designation' => 'Super Admin',
        ];

        $admins = self::model()->findAll($criteria);
        return array_values(CHtml::listData($admins, 'id', 'id'));
    }

    public static function getWarehouseUser($warehouseId)
    {
        $criteria = new CDbCriteria();
        $criteria->addCondition('FIND_IN_SET(:wid, available_warehouses) > 0');
        $criteria->addCondition('user_group_id != :group');
        $criteria->addCondition('designation != :designation');
        $criteria->params[':group'] = 1;
        $criteria->params[':wid'] = $warehouseId;
        $criteria->params[':designation'] = 'Super Admin';
        $users = self::model()->findAll($criteria);
        return array_values(CHtml::listData($users, 'id', 'id'));
    }




}
