<?php

/**
 * This is the model class for table "events".
 *
 * The followings are the available columns in table 'events':
 * @property string $id_event
 * @property string $id_event_cat
 * @property string $created
 * @property string $message_ru
 * @property string $message_ua
 * @property string $id_user
 */
class Events extends CActiveRecord {

    public $surname_user;
    public $name_user;
    public $middlename_user;
    public $created_from;
    public $created_to;

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

    /**
     * @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_event_cat, message_ru, id_user', 'required'),
            array('id_event_cat, id_user', 'length', 'max' => 10),
            array('message_ru, message_ua', 'length', 'max' => 255),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id_event, id_event_cat, created, message_ru, message_ua, id_user, created_from, created_to', '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(
            'idEventCat' => array(self::BELONGS_TO, 'EventCategories', 'id_event_cat'),
            'idUser' => array(self::BELONGS_TO, 'Users', 'id_user'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id_event' => Yii::t('admin_events', 'Номер'),
            'id_event_cat' => Yii::t('admin_events', 'Категория'),
            'created' => Yii::t('admin_events', 'Дата'),
            'created_from' => Yii::t('admin_events', 'От:'),
            'created_to' => Yii::t('admin_events', 'До:'),
            'message_ru' => Yii::t('admin_events', 'Описание'),
            'message_ua' => Yii::t('admin_events', 'Описание'),
            'id_user' => Yii::t('admin_events', 'Пользователь'),
        );
    }

    protected function afterFind() {
        // convert to display format
        if ($this->created != "0000-00-00 00:00:00") {
            $this->created = strtotime($this->created);
            $this->created = date('d.m.Y H:i:s', $this->created);
        } else {
            $this->created = "";
        }
        
        if ($this->created_from != "0000-00-00 00:00:00") {
            $this->created_from = strtotime($this->created_from);
            $this->created_from = date('d.m.Y H:i:s', $this->created_from);
        } else {
            $this->created_from = "";
        }
        
        if ($this->created_to != "0000-00-00 00:00:00") {
            $this->created_to = strtotime($this->created_to);
            $this->created_to = date('d.m.Y H:i:s', $this->created_to);
        } else {
            $this->created_to = "";
        }
        
    }

    protected function beforeValidate() {
        // convert to storage format
        if ($this->created != "") {
            $this->created = strtotime($this->created);
            $this->created = date('Y-m-d', $this->created);
        }
    }
    
    public static function addAdminScheduleEdit($user)
    {
        $event = new Events();
        $event->id_user = Yii::App()->user->id;
        $event->message_ru = 'Пользователь ' . Yii::App()->user->name . ' отредактировал даты прохождения тестирования в расписании для пользователя "' . $user->surname_user . ' ' . $user->name_user . ' ' . $user->middlename_user . '"';
        $event->message_ua = 'Користувач ' . Yii::App()->user->name . ' відредагував дати проходження тестування у розкладі для користувача "' . $user->surname_user . ' ' . $user->name_user . ' ' . $user->middlename_user . '"';
        $event->id_event_cat = 7;
        $event->save(false);
    }
    
    public static function addAdminTestsInUsersEdit($testsInUsers)
    {
        $test = $testsInUsers->idTest;
        $user = $testsInUsers->idUser;
        $event = new Events();
        $event->id_user = Yii::App()->user->id;
        $event->message_ru = Yii::App()->user->name . ' отредактировал количество попыток пользователю "' . $user->surname_user . " " . $user->name_user . " " . $user->middlename_user . '" к тесту "' . $test->name_test_ru . '"';
        $event->message_ua = Yii::App()->user->name . ' відредагував кількість спроб користувачеві "' . $user->surname_user . " " . $user->name_user . " " . $user->middlename_user . '" до тесту "' . $test->name_test_ua . '"';
        $event->id_event_cat = 16;
        $event->save(false);
    }
    
    public static function addAdminScheduleTestsEdit($scheduleTests)
    {
        $test = $scheduleTests->idTest;
        $user = $scheduleTests->idUser;
        $event = new Events();
        $event->id_user = Yii::App()->user->id;
        $event->message_ru = Yii::App()->user->name . ' отредактировал количество попыток пользователю "' . $user->surname_user . " " . $user->name_user . " " . $user->middlename_user . '" к тесту "' . $test->name_test_ru . '"';
        $event->message_ua = Yii::App()->user->name . ' відредагував кількість спроб користувачеві "' . $user->surname_user . " " . $user->name_user . " " . $user->middlename_user . '" до тесту "' . $test->name_test_ua . '"';
        $event->id_event_cat = 19;
        $event->save(false);
    }

    public static function addAdminUsersAdd($user) {
        $event = new Events();
        $event->id_user = Yii::App()->user->id;
        $event->message_ru = 'Пользователь ' . Yii::App()->user->name . ' добавил пользователя "' . $user->surname_user . ' ' . $user->name_user . ' ' . $user->middlename_user . '"';
        $event->message_ua = 'Користувач ' . Yii::App()->user->name . ' додав користувача "' . $user->surname_user . ' ' . $user->name_user . ' ' . $user->middlename_user . '"';
        $event->id_event_cat = 7;
        $event->save(false);
    }

    public static function addAdminUsersEdit($user) {
        $event = new Events();
        $event->id_user = Yii::App()->user->id;
        $event->message_ru = 'Пользователь ' . Yii::App()->user->name . ' отредактировал пользователя "' . $user->surname_user . ' ' . $user->name_user . ' ' . $user->middlename_user . '"';
        $event->message_ua = 'Користувач ' . Yii::App()->user->name . ' відредагував користувача "' . $user->surname_user . ' ' . $user->name_user . ' ' . $user->middlename_user . '"';
        $event->id_event_cat = 7;
        $event->save(false);
    }

    public static function addAdminUsersDelete($user) {
        $event = new Events();
        $event->id_user = Yii::App()->user->id;
        $event->message_ru = 'Пользователь ' . Yii::App()->user->name . ' удалил пользователя "' . $user->surname_user . ' ' . $user->name_user . ' ' . $user->middlename_user . '"';
        $event->message_ua = 'Користувач ' . Yii::App()->user->name . ' видалив користувача "' . $user->surname_user . ' ' . $user->name_user . ' ' . $user->middlename_user . '"';
        $event->id_event_cat = 7;
        $event->save(false);
    }

    public static function addAdminTestsAdd($test) {
        $event = new Events();
        $event->id_user = Yii::App()->user->id;
        $event->message_ru = 'Пользователь ' . Yii::App()->user->name . ' добавил тест "' . $test->name_test_ru . '"';
        $event->message_ua = 'Користувач ' . Yii::App()->user->name . ' додав тест "' . $test->name_test_ua . '"';
        $event->id_event_cat = 14;
        $event->save(false);
    }

    public static function addAdminTestsEdit($test) {
        $event = new Events();
        $event->id_user = Yii::App()->user->id;
        $event->message_ru = 'Пользователь ' . Yii::App()->user->name . ' отредактировал тест "' . $test->name_test_ru . '"';
        $event->message_ua = 'Користувач ' . Yii::App()->user->name . ' відредагував тест "' . $test->name_test_ua . '"';
        $event->id_event_cat = 14;
        $event->save(false);
    }

    public static function addAdminTestsDelete($test) {
        $event = new Events();
        $event->id_user = Yii::App()->user->id;
        $event->message_ru = 'Пользователь ' . Yii::App()->user->name . ' удалил тест "' . $test->name_test_ru . '"';
        $event->message_ua = 'Користувач ' . Yii::App()->user->name . ' видалив тест "' . $test->name_test_ua . '"';
        $event->id_event_cat = 14;
        $event->save(false);
    }

    public static function addClientLogin() {
        $event = new Events();
        $event->id_user = Yii::App()->user->id;
        $event->message_ru = "Пользователь " . Yii::App()->user->name . " вошёл в клиентскую часть приложения";
        $event->message_ua = "Користувач " . Yii::App()->user->name . " увійшов до клієнської частини додатку";
        $event->id_event_cat = 1;

        $event->save(false);
    }

    public static function addAdminLogin() {
        $event = new Events();
        $event->id_user = Yii::App()->user->id;
        $event->message_ru = "Пользователь " . Yii::App()->user->name . " вошёл в панель управления";
        $event->message_ua = "Користувач " . Yii::App()->user->name . " увійшов до панелі керування";
        $event->id_event_cat = 3;

        $event->save(false);
    }

    public static function addClientBeginTest($test) {
        $event = new Events();
        $event->id_user = Yii::App()->user->id;
        $event->message_ru = 'Пользователь ' . Yii::App()->user->name . ' начал прохождение теста "' . $test->name_test_ru . '"';
        $event->message_ua = 'Користувач ' . Yii::App()->user->name . ' почав прохождення тесту "' . $test->name_test_ua . '"';
        $event->id_event_cat = 2;

        $event->save(false);
    }

    public static function addClientFinishedTest($test, $success, $error = false) {
        $event = new Events();
        $event->id_user = Yii::App()->user->id;
        if ($success) {
            $event->message_ru = 'Пользователь ' . Yii::App()->user->name . ' успешно прошёл тест "' . $test->name_test_ru . '"';
            $event->message_ua = 'Користувач ' . Yii::App()->user->name . ' успішно пройшов теста "' . $test->name_test_ua . '"';
        } else {
            if ($error) {
                $event->message_ru = 'Произошла ошибка при прохождении теста "' . $test->name_test_ru . '" пользователем "' . Yii::App()->user->name . '"';
                $event->message_ua = 'Виникла помилка підчас прохождення тесту "' . $test->name_test_ru . '" користувачем "' . Yii::App()->user->name . '"';
            } else {
                $event->message_ru = 'Пользователь ' . Yii::App()->user->name . ' провалил тест "' . $test->name_test_ru . '"';
                $event->message_ua = 'Користувач ' . Yii::App()->user->name . ' провалив теста "' . $test->name_test_ua . '"';
            }
        }
        $event->id_event_cat = 2;
        $event->save(false);
    }
    
   

    public static function getUsers() {
        $criteria = new CDbCriteria();
        $criteria->with = array("idUser");
        $criteria->group = "t.id_user";
        $criteria->select = array('*', 'idUser.surname_user AS surname_user', 'idUser.name_user AS name_user', 'idUser.middlename_user AS middlename_user');
        return self::model()->findAll($criteria);
    }

    /**
     * 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->compare('id_event', $this->id_event);
        $criteria->compare('id_event_cat', $this->id_event_cat);
        $criteria->compare('DATE_FORMAT(created, "%d.%m.%Y")', $this->created, true);
        $criteria->compare('message_ru', $this->message_ru, true);
        $criteria->compare('message_ua', $this->message_ua, true);
        $criteria->compare('id_user', $this->id_user);
        
        if ($this->created_from != "") {
            $criteria->addCondition('t.created > "' . $this->created_from . '"', "AND");
        }

        if ($this->created_to != "") {
            $criteria->addCondition('t.created < "' . $this->created_to . '"', "AND");
        }
        
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'sort' => array(
                'defaultOrder' => 'id_event DESC',
            ),
            '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 Events the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

}
