<?php

/**
 * This is the model class for table "roles".
 *
 * The followings are the available columns in table 'roles':
 * @property string $id_role
 * @property string $name_role_ru
 * @property string $name_role_ua
 * @property string $value_role
 * @property string $sort
 *
 * The followings are the available model relations:
 * @property RolesInActions[] $rolesInActions
 */
class Roles extends CActiveRecord {

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

    /**
     * @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('id_cat_role, name_role_ru, value_role', 'required'),
            array('name_role_ru, name_role_ua, value_role', 'length', 'max' => 50),
            array('sort', 'length', 'max' => 10),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id_role, id_cat_role, name_role_ru, name_role_ua, value_role, sort', 'safe'),
        );
    }

    /**
     * @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(
            'operations' => array(self::MANY_MANY, 'Operations', 'operations_in_roles(id_role,id_oper)'),
            'users' => array(self::HAS_MANY, 'Users', 'id_role'),
            'idContr' => array(self::BELONGS_TO, 'Controllers', 'id_contr'),
            'idCat' => array(self::BELONGS_TO, 'RoleCategories', 'id_cat_role'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            //'id_role' => 'Роль',
            'name_role_ru' => 'Название',
            'name_role_ua' => 'Название',
            'value_role' => 'Символьный код',
            'sort' => 'Сортировка',
            'id_cat_role' => 'Категория роли'
        );
    }

    /**
     * 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($pagination=true) {
        // @todo Please modify the following code to remove attributes that should not be searched.

        if ($pagination) {
            $pagination = array(
                'pageSize' => (int) Yii::app()->session['pageCount'] ? Yii::app()->session['pageCount'] : 50,
            );
        } else {
            $pagination = array(
                'pageSize' => 1000000, /* мильён! я не жадный! */
            );
        }
        
        $criteria = new CDbCriteria;
        $criteria->condition = "id_cat_role NOT IN (4,5)";

        $criteria->compare('id_role', $this->id_role);
        $criteria->compare('id_cat_role', $this->id_cat_role);
        $criteria->compare('name_role_ru', $this->name_role_ru, true);
        $criteria->compare('name_role_ua', $this->name_role_ua, true);
        $criteria->compare('value_role', $this->value_role, true);
        $criteria->compare('sort', $this->sort);

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

    /**
     * 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 Roles the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }
    
    
    public function afterSave() {
       
            /* Запись в журнал действий информации о манипуляции с данными этой таблицы в БД. Добавление. */
            $event = new Events();
            $event->id_user = Yii::App()->user->id;
            
             if ($this->isNewRecord) {
            $event->message_ru = Yii::App()->user->name . ' добавил роль "' . $this->name_role_ru.'"';
            $event->message_ua = Yii::App()->user->name . ' додав роль "' . $this->name_role_ua . '"';
            }
            else
            {
              $event->message_ru = Yii::App()->user->name . ' отредактировал роль "' . $this->name_role_ru.'"';
            $event->message_ua = Yii::App()->user->name . ' відредагував роль "' . $this->name_role_ua . '"';  
            }
            $event->id_event_cat = 17;
            $event->save(false);
        
        return parent::afterSave();
    }
    
    public function afterDelete() {
        /* Запись в журнал действий информации об удалении записи из таблицы. */
        
        $event = new Events();
        $event->id_user = Yii::App()->user->id;
        $event->message_ru = Yii::App()->user->name . ' удалил роль "' . $this->name_role_ru.'"';
        $event->message_ua = Yii::App()->user->name . ' видалив роль "' . $this->name_role_ua . '"'; 
        $event->id_event_cat = 17;
        $event->save(false);

        return parent::afterDelete();
    }

    public static function findAllByRoleCategoryId($id_cat_role) {
        return self::model()->findAllByAttributes(array('id_cat_role' => $id_cat_role));
    }

    public static function getAccessibleRolesToAdminModule() {
        $criteria = new CDbCriteria();
        $criteria->with = array("operations");
        $criteria->together = true;

        $criteria->compare('operations.id_oper', 1);

        return self::model()->findAll($criteria);
    }

    public static function getAccessibleRoles() {
        $criteria = new CDbCriteria();
        $criteria->with = array("operations");
        $criteria->together = true;

        $criteria->compare('operations.id_oper', 1);

        return self::model()->findAll($criteria);
    }
    
    public static function findAllExceptSuperAdmins()
    {
        $criteria = new CDbCriteria();
        $criteria->addCondition('id_cat_role!=5');
        return self::model()->findAll($criteria);
    }
    
    public static function findAllUsers()
    {
        $criteria = new CDbCriteria();
        $criteria->addCondition('id_cat_role!=5');
        return self::model()->findAll($criteria);
    }
    
    public static function findAllExceptGuestsAndSuperAdmins()
    {
        $criteria = new CDbCriteria();
        $criteria->addCondition('id_cat_role NOT IN(3,5)');
        return self::model()->findAll($criteria);
    }

    public static function findAllByUsers(array $user_ids) {
        $criteria = new CDbCriteria();
        //$criteria->with = array('users');
        //$criteria->addInCondition('users.id_user', $user_ids);
        $criteria->addCondition('id_cat_role!=5');

        return self::model()->findAll($criteria);
    }

    /**
     * Проверка на админа по ид роли
     * @param type $id_role
     * @return boolean
     */
    public static function checkForAdmin($id_role)
    {
        $roles = array(2,3,11);
        if (in_array($id_role, $roles))
            return true;
        else
            return false;
    }
}
