<?php
class ChatController extends Controller {
    public function accessRules() {
        return array(
            array('deny',
                'roles' => array('banned'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            ),
            array('allow',
                'actions' => array('index'),
                'users' => array('@'),
            ),
            array('allow',
                'actions' => array('delete', 'edit'),
                'roles' => array('moder'),
            ),
            array('deny',
                'users' => array('*'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            )
        );
    }
    
    public function actionIndex($type = null) {
        $user = Users::findUser();
        $model = new Chat('search');
        if ($type == 'guild' && $user->guild_id) {
            $model->type = $user->guild_id;
        }
        else {
            $model->type = 0;
        }
        $message = new Chat();

        if (isset($_POST['Chat'])) {
            $message->message = $_POST['Chat']['message'];
            if ($type == 'guild' && $user->guild_id && $_POST['Chat']['type'] && $_POST['Chat']['type'] == $user->guild_id) {
                $message->type = $_POST['Chat']['type'];
            }
            if ($message->validate()) {
                $message->save(false);
                echo CJSON::encode(array(
                     'status'=>'success',
                     'updateList'=>'messages',
                ));
                Yii::app()->end();
             }
             else {
                $error = CActiveForm::validate($model);
                if($error!='[]')
                    echo $error;
                Yii::app()->end();
             }
        }
        $this->render('index', array(
            'model' => $model,
            'user' => $user,
            'message' => $message,
            'type' => $type
        ));
    }
    
    public function actionEdit($id) {
        $message = $this->loadModel($id);
        $model = new AdminForm('messageEdit');
        $model->message = $message->message;
        if (isset($_POST['AdminForm'])) {
            $model->attributes = $_POST['AdminForm'];
            if ($model->validate()) {
                if ($model->message != $message->message) {
                    $message->id_moder = Yii::app()->user->id;
                    $message->message = $model->message;
                    $message->answer = 'отредактировано';
                    if (!$message->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при работе с сообщением!'));
                    }
                }
                elseif ($model->answer) {
                    $message->id_moder = Yii::app()->user->id;
                    $message->answer = $model->answer;
                    $message->answer_type = 2;
                    if (!$message->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при работе с сообщением!'));
                    }
                }
                elseif ($model->mute) {
                    $message->id_moder = Yii::app()->user->id;
                    $message->answer = '';
                    if ($model->reason)
                        $message->answer .= $model->reason.'. ';
                    $message->answer .= 'Молчание на '.$model->mute.' ч.';
                    $message->answer_type = 3;
                    if (!$message->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при работе с сообщением!'));
                    }
                    $user = Users::model()->findByPk($message->id_user);
                    $user->mute_time = time()+$model->mute*60*60;
                    if (!$user->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при работе с пользователем!'));
                    }
                    
                    $id_dialog = Users::checkDialog($message->id_user, 100);
                    $mail = new UsersMessages();
                    $mail->id_dialog = $id_dialog;
                    $mail->id_user = 100;
                    $mail->users = $message->id_user;
                    $mail->message = 'Вы получили наказание "Молчание на '.$model->mute.' ч."';
                    if (!$mail->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при отправке почты!'));
                    }
                }
                echo CJSON::encode(array(
                     'status'=>'success',
                     'updateList'=>'messages',
                ));
                Yii::app()->end();
             }
             else{
                $error = CActiveForm::validate($model);
                if($error!='[]')
                    echo $error;
                Yii::app()->end();
             }
        }
        $this->renderPartial('edit', array(
            'model'=>$model,
            'message'=>$message,
        ));
    }
    
    public function actionDelete($id) {
        if (Yii::app()->getRequest()->getIsPostRequest()) {
            $model = $this->loadModel($id);
            $model->delete();
            echo "true";
            Yii::app()->end();
        } else {
            throw new CHttpException(400, Yii::t('layout', 'Неверный запрос'));
        }
    }
    
    public function loadModel($id) {
        $model = Chat::model()->findByPk($id);
        if ($model === null) {
            throw new CHttpException(404, Yii::t('layout', 'Страница не найдена!'));
        }
        return $model;
    }
}