<?php

class UsersDialogs extends CActiveRecord {

    public $id_user;
    public $id_subuser;
    
    public function tableName() {
        return 'users_dialogs';
    }

    public function rules() {
        return array(
            array('id_dialog', 'required'),
            array('id_dialog', 'length', 'max' => 10),
            array('time', 'length', 'max' => 11),
            array('id_subuser, id_user, id_dialog, time', 'safe', 'on' => 'search'),
        );
    }

    public function relations() {
        return array(
            'users' => array(self::MANY_MANY, 'Users', 'users_dialogs_for_users(id_dialog, id_user)'),
            'usersMessages' => array(self::HAS_MANY, 'UsersMessages', 'id_dialog'),
        );
    }

    public function attributeLabels() {
        return array(
            'id_dialog' => 'Id Dialog',
            'time' => 'Time',
        );
    }

    public function behaviors() {
        return array('CAdvancedArBehavior' => array(
            'class' => 'application.extensions.CAdvancedArBehavior.CAdvancedArBehavior'));
    }
    
    public function search() {
        $criteria = new CDbCriteria;
        $criteria->with = array('users', 'usersMessages');
        $criteria->together = true;
        $count_sql = '(select count(*) from '.UsersMessages::model()->tableName().' usersMessages where usersMessages.id_dialog = t.id_dialog)';
        $criteria->select = array('*', '(select id_user from users_dialogs_for_users where users_dialogs_for_users.id_dialog = t.id_dialog AND `id_user`!='.Yii::app()->user->id.') as id_subuser');
        $criteria->compare('users.id_user', Yii::app()->user->id);
        $criteria->addCondition($count_sql.' > 0');
        //$criteria->group = 't.id_dialog';
        
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'sort' => array(
                'sortVar' => 'sort',
                'defaultOrder' => 'usersMessages.time DESC',
            ),
            'pagination' => array(
                'route' => '/mail/index/',
                'params' => array(),
                'pageVar' => 'page',
                'pageSize' => '88888',
                //было 10
            ),
        ));
    }

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

}
