<?php

class Chat extends CActiveRecord {

    public function tableName() {
        return 'chat';
    }

    public function rules() {
        return array(
            array('message', 'required'),
            array('id_chat, id_user, type, answer, answer_type, tid, time, id_moder', 'safe'),
        );
    }

    public function relations() {
        return array(
            'idUser' => array(self::BELONGS_TO, 'Users', 'id_user'),
            'idModer' => array(self::BELONGS_TO, 'Users', 'id_moder'),
        );
    }

    public function attributeLabels() {
        return array(
            'message' => Yii::t('layout', 'Сообщение'),
            'id_user' => Yii::t('layout', 'Пользователь'),
        );
    }

    protected function beforeSave() {
        if ($this->isNewRecord) {
            $this->id_user = Yii::app()->user->id;
            $this->time = time();
        }
        return parent::beforeSave();
    }

    public function search($type = null) {
        $criteria = new CDbCriteria;

        $criteria->compare('type', $this->type);
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'sort' => array(
                'sortVar' => 'sort',
                'defaultOrder' => 'time DESC',
            ),
            'pagination' => array(
                'route' => '/chat/index/',
                'params' => ($type == 'guild' ? array('type'=>'guild') : array()),
                'pageVar' => 'page',
                'pageSize' => '10',
            ),
        ));
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

}
