<?php
/**
 * IMPORTANT NOTE
 * The code of this system is closed and a private proprietary of Flex Solutions.
 * A written authorization/license from Flex Solutions is required before using or modifying this code.
 * Email: sales@flexsolution.biz, Phone: +962795342585, Website: http://www.flexsolutions.biz
 */
 

/**
 * This is the model class for table "person".
 *
 * The followings are the available columns in table 'person':
 * @property integer $id
 * @property string $number
 * @property string $name
 * @property string $alias
 * @property integer $type_id
 * @property string $mobile
 * @property string $email
 * @property string $manager
 * @property integer $department_id
 * @property integer $is_manager
 * @property integer $is_food_manager
 * @property integer $receive_emails
 * @property string $status
 * @property integer $created_by
 * @property string $created_date
 * @property integer $last_edited_by
 * @property string $last_edited_date
 *
 * The followings are the available model relations:
 * @property Badge[] $badges
 * @property Department $department
 * @property PersonType $type
 * @property PersonPos[] $personPoses
 * @property Ticket[] $tickets
 */
class Person extends LsmsActiveRecord
{

    public $is_Ldap;
    // Add new attributes to customize the viewing in excel file and show Yes when the value is 1 and No when is 0
    public $is_manager_custome;
    public $is_food_manager_custome;
    public $receive_emails_custome;


    protected function afterFind()
    {
        if ($this->alias == '')
        {
            $this->is_Ldap = yii::t('default', 'No');
        }
        else
        {
            $this->is_Ldap = yii::t('default', 'Yes');
        }
        if ($this->is_manager == 1)
            $this->is_manager_custome = 'Yes';
        else
            $this->is_manager_custome = 'No';

        if ($this->receive_emails == 1)
            $this->receive_emails_custome = 'Yes';
        else
            $this->receive_emails_custome = 'No';

        if ($this->is_food_manager == 1)
            $this->is_food_manager_custome = 'Yes';
        else
            $this->is_food_manager_custome = 'No';
        
        parent::afterFind();
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Person 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 'person';
    }

    /**
     * @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('number, name, type_id, department_id, is_manager, is_food_manager,receive_emails, status', 'required', 'except' => 'search'),
            array('type_id, department_id, is_manager, is_food_manager,receive_emails', 'numerical', 'integerOnly' => true),
            array('number, name, alias, mobile, email', 'length', 'max' => 255),
            array('manager', 'length', 'max' => 45),
            //array('email', 'email'),
            array('number', 'unique'),
            array('status', 'in',
                'range' => array('Active', 'On Leave', 'Terminated', 'Resigned', 'Transferred', 'Inactive'),
                'allowEmpty' => false,
                'message' => Yii::t("default", "The status ({n}) is not recognized, the status should be one of the following (Active, Inactive, On Leave, Terminated, Resigned, Transferred)", $this->status)
            ),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, number, name, alias, type_id, mobile, email, manager, department_id, is_manager, is_food_manager,receive_emails, status', '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(
            'badges' => array(self::HAS_MANY, 'Badge', 'person_id'),
            'department' => array(self::BELONGS_TO, 'Department', 'department_id'),
            'type' => array(self::BELONGS_TO, 'PersonType', 'type_id'),
            'personPoses' => array(self::HAS_MANY, 'PersonPos', 'person_id'),
            'tickets' => array(self::HAS_MANY, 'Ticket', 'person_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'number' => yii::t('default', 'ID Number'),
            'name' => yii::t('default', 'Full Name'),
            'alias' => yii::t('default', 'Alias'),
            'type_id' => yii::t('default', 'Type'),
            'mobile' => yii::t('default', 'Mobile'),
            'email' => yii::t('default', 'Email'),
            'manager' => yii::t('default', 'Manager'),
            'department_id' => yii::t('default', 'Department'),
            'is_manager' => yii::t('default', 'Is Manager'),
            'is_food_manager' => yii::t('default', 'Is Food Manager'),
            'receive_emails' => yii::t('default', 'Receive Emails'),
            'status' => yii::t('default', 'Status'),
            'is_ldap' => yii::t('default', 'LDAP Person'),
        );
    }

    /**
     * @return array customized attribute labels Tooltips (name=>label tooltips)
     */
    public function attributeLabelsPopover()
    {
        return array(
            'number' => yii::t('default', 'ID Number'),
            'name' => yii::t('default', 'Full Name'),
            'alias' => yii::t('default', 'Alias'),
            'type_id' => yii::t('default', 'Type'),
            'mobile' => yii::t('default', 'Mobile'),
            'email' => yii::t('default', 'Email'),
            'manager' => yii::t('default', 'Manager'),
            'department_id' => yii::t('default', 'Department'),
            'is_manager' => yii::t('default', 'Is Manager'),
            'is_food_manager' => yii::t('default', 'Is Food Manager'),
            'receive_emails' => yii::t('default', 'Receive Emails'),
            'status' => yii::t('default', 'Status'),
        );
    }

    /**
     * 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);
        $criteria->compare('number', $this->number, true);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('alias', $this->alias, true);
        $criteria->compare('type_id', $this->type_id);
        $criteria->compare('mobile', $this->mobile, true);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('manager', $this->manager, true);
        $criteria->compare('department_id', $this->department_id);
        $criteria->compare('is_manager', $this->is_manager);
        $criteria->compare('is_food_manager', $this->is_food_manager);
        $criteria->compare('receive_emails', $this->receive_emails);
        $criteria->compare('status', $this->status);


        $pageSize = $this->yiiparam('pageSize');
        return new CActiveDataProvider($this, array(
            'pagination' => array('pageSize' => $pageSize,),
            'criteria' => $criteria,
        ));
    }

    public function searchWithUserFiltering()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('number', $this->number, true);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('alias', $this->alias, true);
        $criteria->compare('type_id', $this->type_id);
        $criteria->compare('mobile', $this->mobile, true);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('manager', $this->manager, true);
        $criteria->compare('department_id', $this->department_id);
        $criteria->compare('is_manager', $this->is_manager);
        $criteria->compare('is_food_manager', $this->is_food_manager);
        $criteria->compare('receive_emails', $this->receive_emails);
        $criteria->compare('status', $this->status, false);

        if (Yii::app()->user->checkAccess('Facility Admin'))
        {
            $department_array = array_values(User::model()->getDepartmentInGeomarket());
            array_shift($department_array);
            $criteria->addInCondition('department.name', $department_array);
        }


//        $criteria->select = 'id,number,name,alias,type_id,mobile,email,manager,department.name,is_manager,is_food_manager,receive_emails,status';
//        $criteria->select = 'id,number,name,alias,type_id,mobile,email,manager,department.name, IF(`is_manager` > 0 ,\'Yes\',\'No\') as is_manager,if(person.`is_food_manager` > 0 ,\'Yes\',\'No\') AS is_food_manager,receive_emails,status';

        $pageSize = $this->yiiparam('pageSize');
        return new CActiveDataProvider($this, array(
            'pagination' => array('pageSize' => $pageSize,),
            'criteria' => $criteria,
        ));
    }

    public static function getAll($status=null)
    {
        if ($status == "Active")
        {
            return Person::model()->active()->findAll(array('order' => 'name'));
        }
        else
        {
            return Person::model()->findAll(array('order' => 'name'));
        }
    }

    /*
     * The Following function is responsible for return array of person for using as autocomplit source
     */

    public static function getArrayOfPersons($status=null)
    {
        $all_person = Person::getAll($status);

        $result = array();
        foreach ($all_person as $person)
        {
            $result[$person->id] = $person->Identifier;
        }
        return $result;
    }

    /*
     * The Following function is responsible for return array of Manager for using as autocomplit source
     */

    public static function getArrayOfManagers($status=null)
    {
        $managers = Person::model()->findAllByAttributes(array('is_manager' => 1));
        $result = array();
        if ($managers != null)
        {
            foreach ($managers as $manager)
            {
                $result[$manager->id] = $manager->Identifier;
            }
        }
        return $result;
    }

    //This function Routing View Url based on type person LDAP or Non-LDAP
    // output is array value
    public function getViewUrl()
    {
        if (isset($this->type->is_ldap))
        {
            if ($this->type->is_ldap == 1)
            {
                return array('/lDAPPerson/view', 'id' => $this->id);
            }
            if ($this->type->is_ldap == 0)
            {
                return array('/nonLDAPPerson/view', 'id' => $this->id);
            }
        }
        else
        {
            return array('/person/index');
        }
    }

    //This function Routing Update Url based on type person LDAP or Non-LDAP
    // output is array value
    public function getUpdateUrl()
    {
        if (isset($this->type->is_ldap))
        {
            if ($this->type->is_ldap == 1)
            {
                return array('/lDAPperson/update', 'id' => $this->id);
            }
            if ($this->type->is_ldap == 0)
            {
                return array('/nonLDAPPerson/update', 'id' => $this->id);
            }
        }
        else
        {
            return array('/person/index');
        }
    }

    /*
     *  return all POS's wich assigned with this Person and return it in specific format for viewing
     */

    public function getAllPOSs($POSs=null)
    {
        if (isset($POSs) && (count($POSs) > 0))
        {
            $retruvalue = "<br>";
            foreach ($POSs as $value)
            {
                $retruvalue .= $value->pos->name;
                $retruvalue .= "<br>";
            }
        }
        else
        {
            // there is zero assigned POSs
            $retruvalue = "";
        }
        return $retruvalue;
    }

    //the following function is responsible for return list of person as array (person_id => person_name-personnumber ) to set as autocomplete source
    public static function getListNameNumber($status=null)
    {
        $result = null;
        if ($status == "Active")
        {
            $list = Person::model()->active()->findAll(array('order' => 'name'));
            $result = array();
            foreach ($list as $key => $value)
            {
                $result[$value->id] = $value->name . "-" . $value->number;
            }
        }
        else
        {
            $list = Person::model()->findAll(array('order' => 'name'));
            $result = array();
            foreach ($list as $key => $value)
            {
                $result[$value->id] = $value->name . "-" . $value->number;
            }
        }
        return $result;
    }

    function getIdentifier()
    {
        return $this->name . '-' . $this->number;
    }

    //The following function is responsible for update status for badges based on the new status
    public static function updateBadgesStatus($badges=null, $old_person_status=null, $new_person_status=null)
    {
        if ($badges != null)
        {
            if ((count($badges) > 0) && ($old_person_status != $new_person_status))
            {
                //Activate the badges
                if (($old_person_status != 'Active') && ($new_person_status == 'Active'))
                {
                    foreach ($badges as $badge)
                    {
                        if (($badge->status == 'Inactive') && (!$badge->isExpired()))
                        {
                            $badge->status = 'Active';
                            $badge->save();
                        }
                    }
                }
                else
                //Deactivate the badges
                if (($old_person_status == 'Active') && ($new_person_status != 'Active'))
                {
                    foreach ($badges as $badge)
                    {

                        if (($badge->status == 'Active') && (!$badge->isExpired()))
                        {
                            $badge->status = 'Inactive';
                            $badge->save();
                        }
                    }
                }
            }
        }
    }

    public static function getLDAPPersons($status=null)
    {
        if ($status == "Active")
        {
            return Person::model()->active()->findAllByAttributes(
                    array(),
                    $condition = 'alias != "" ');
        }
        else
        {
            return Person::model()->findAllByAttributes(
                    array(),
                    $condition = 'alias != "" ');
        }
    }

}