<?php

class UserMail extends CActiveRecord {

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

    /**
     * @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(
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id_user, id_mail, type, new, save, time, items, bottles, iron, money, text, who, whom, sender', '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(
            'idUser' => array(self::BELONGS_TO, 'Users', 'id_user'),
            'idItem' => array(self::BELONGS_TO, 'UserItems', 'items'),
            'idWho' => array(self::BELONGS_TO, 'Users', 'who'),
            'idWhom' => array(self::BELONGS_TO, 'Users', 'whom'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'text' => Yii::t('layout', 'Сообщение'),
        );
    }

    protected function beforeSave() {
        if (parent::beforeSave()) {
            if ($this->isNewRecord) {
                $this->time = time();
                if (isset(Yii::app()->user)) {
                    if ($this->who == Yii::app()->user->id && $this->id_user == Yii::app()->user->id) {
                        $this->new = 0;
                    }
                }
            }
            return true;
        } else
            return false;
    }

    /**
     * Проверяет есть ли у пользователя новая почта
     * @param int $id
     * @return int
     */
    public static function checkNewMail() {
        if (!Yii::app()->user->isGuest) {
            $criteria = new CDbCriteria;
            $criteria->compare('whom', Yii::app()->user->id);
            $criteria->compare('new', 1);
            return self::model()->count($criteria);
        }
        return false;
    }

    /**
     * Проверяет есть ли у пользователя новая почта с вложением
     * @param int $id
     * @return int
     */
    public static function checkNewMailWithAttachment() {
        if (!Yii::app()->user->isGuest) {
            $criteria = new CDbCriteria;
            $criteria->addCondition('type > 0');
            $criteria->compare('whom', Yii::app()->user->id);
            $criteria->compare('new', 1);
            return self::model()->count($criteria);
        }
        return false;
    }

    public function search() {
        $criteria = new CDbCriteria;
        $criteria->compare('id_user', $this->id_user);
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * 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 Files the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * Обрезает текст сообщения, чтоб он нормально отображался на выводе сообщений
     * @param string $text текст с бд
     * @return string обрезаный текст
     */
    public static function cutText($text) {
        $result = strip_tags($text);
        if (strlen($result) > 19) {
            $result = mb_substr($result, 0, 17, 'UTF-8');
            $result .= '...';
        }
        return $result;
    }

}
