<?php

/**
 * This is the model class for table "{{mas_user_group}}".
 *
 * The followings are the available columns in table '{{mas_user_group}}':
 * @property integer $id
 * @property integer $company_id
 * @property string $group_name
 * @property string $isActive
 *
 * The followings are the available model relations:
 * @property MasUser[] $masUsers
 * @property MasCompany $company
 */
class MasUserGroup extends CActiveRecord {

    public $permissions;
    public $checkall;

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

    /**
     * @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('group_name', 'required'),
            array('parent_id ', 'numerical', 'integerOnly' => true),
            array('group_name', 'length', 'max' => 255),
            array('group_name', 'unique'),
            array('permissions', 'length', 'max' => 65535),
            array('isActive,is_salesman', 'length', 'max' => 1),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id,group_name, isActive,created_by,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(
            'masUsers' => array(self::HAS_MANY, 'MasUser', 'user_group_id'),
            'company' => array(self::BELONGS_TO, 'MasCompany', 'company_id'),
            'parentGroup' => array(self::BELONGS_TO, 'MasUserGroup', 'parent_id'),
            'children' => array(self::HAS_MANY, 'MasUserGroup', 'parent_id'),
            'permission' => array(self::HAS_ONE, 'UsergroupPermission', 'user_group_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'company_id' => 'Company',
            'group_name' => 'Group Name',
            'isActive' => 'Is Active',
        );
    }

    /**
     * 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('company_id', $this->company_id);
        $criteria->compare('group_name', $this->group_name, true);
        $criteria->compare('isActive', $this->isActive, true);

        return new CActiveDataProvider($this, array(
            'pagination' => array(
                'pageSize' => 2,
            ),
            'criteria' => $criteria,
            'sort' => array(
                'defaultOrder' => 't.parent_id ASC,t.group_name 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 MasUserGroup the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public static function getUserGroup($id = null) {
        //$condition = 'isActive =  "Y" AND company_branch_id<>0';
        $condition = 'isActive =  "Y"';
        if ($id != null)
            $condition .= 'id<>' . $id;
        $model = self::model()->findAll(array('condition' => $condition, 'order' => 'group_name'));
        return CHtml::listData($model, 'id', 'group_name');
    }

    public static function subGroups1($id) {
        $condition = 'parent_id =  ' . $id;
        $subgroups = array();
        $model = self::model()->findAll(array('condition' => $condition));
        if (count($model) > 0) {
            foreach ($model as $eachModel) {
                $subgroups[] = $eachModel->id;
            }
        }
        return (implode(',', $subgroups));
    }

    public function getOneLevel($id) {

        $condition = 'parent_id =  ' . $id;
        $subgroups = array();
        $model = self::model()->findAll(array('condition' => $condition));
        if (count($model) > 0) {
            foreach ($model as $eachModel) {
                $subgroups[] = $eachModel->id;
            }
        }
        return $subgroups;
    }

    public function subGroups($parent_id) {
        $tree = Array();
        if (!empty($parent_id)) {
            $tree = self::getOneLevel($parent_id);
            foreach ($tree as $key => $val) {
                $ids = self::subGroups($val);
                $tree = array_merge($tree, $ids);
            }
        }
        return $tree;
    }

    public function renderCountOfUsers($data, $row) {
        return User::model()->count('user_group_id in (' . $data->id . ')');
    }

}
