<?php

class ChatController extends Controller {

    
     public function filters() {
        return array(
            'accessControl',
        );
    }

    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('index'),
                'users' => array('@'),
            ),
            array('allow',
                'actions' => array('del_message'),
                'roles' => array('moderator'),
                ),
            array('deny',
                'users' => array('*'),
               // 'deniedCallback' => $this->redirect('?r=site/index'),
            )
        );
    }
    
    
    public function actions() {
        return array(
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    
    public function actionDel_message($id) {
        $model = Chat::findChat($id);
        Chat::model()->deleteByPk($id);
        Yii::app()->user->setFlash('chat_notice', 'Сообщение успешно удалено');
        $this->redirect(array('chat/index'));
    }
    
    public function actionIndex() {

        $form = new Chat();
        $form->scenario = 'chat';

        if (!empty($_POST['Chat'])) {
            $form->attributes = $_POST['Chat'];
            if ($form->validate('/chat/index')) {
                $form->user = Yii::app()->user->id;
                $form->time = time();
                $form->text = htmlspecialchars($_POST['Chat']['text']);
                $form->save(FALSE);
                $this->refresh();
            }
        }


        $criteria = new CDbCriteria();
        $count = Chat::model()->count($criteria);
        $pages = new CPagination($count);
        // элементов на страницу
        $pages->pageSize = 10;
        $pages->applyLimit($criteria);
        $criteria->order = 'id DESC';

        $models = Chat::model()->findAll($criteria);

        $this->render('index', array(
            'form' => $form,
            'models' => $models,
            'pages' => $pages,
            'role' => Yii::app()->user->role,
        ));
    }

}
