<?php
class EditController extends AdminBaseController {
    public function accessRules() {
        return array(
            array('deny',
                'roles' => array('banned'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            ),
            array('allow',
                'actions' => array('index', 'setBan', 'unBan', 'chatEdit', 'forumEdit'),
                'roles' => array('moder'),
            ),
            array('deny',
                'users' => array('*'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            )
        );
    }
    
    public function actionSetBan($id) {
        $model = new AdminForm('banUser');
        $user = Users::model()->findByPk($id);
        $this->performAjaxValidation($model);
        if (isset($_POST['AdminForm'])) {
            $model->attributes = $_POST['AdminForm'];
            if ($model->validate()) {
                $ban = new UserBan();
                $ban->attributes = $model->attributes;
                $ban->id_user = $id;
                if ($model->type == 2) {
                    $ban->time = time() + 3600 * 24 * $model->number;
                }
                elseif ($model->type == 1) {
                    $ban->time = time() + 3600 * $model->number;
                } 
                else 
                    $ban->time = 0;
                if (!$ban->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при выдаче бана'));
                }
                $user->id_role = 7;
                $user->id_ban = $ban->id_ban;
                if (!$user->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при выдаче бана'));
                }
                //do anything here
                echo CJSON::encode(array(
                    'status'=>'success',
                    'reload'=>true,
                ));
                Yii::app()->end();
             }
             else{
                $error = CActiveForm::validate($model);
                if($error!='[]')
                    echo $error;
                Yii::app()->end();
             }
        }
        $this->renderPartial('setBan', array(
            'model'=>$model,
        ));
    }
    public function actionUnBan($id) {
        $user = Users::model()->findByPk($id);
        $user->id_ban = null;
        if (!$user->save(false)) {
            throw new CHttpException(500, Yii::t('layout', 'Ошибка при снятии бана'));
        }
        $this->redirect(Yii::app()->request->urlReferrer); 
        Yii::app()->end();
    }
    
    public function actionChatEdit($id) {
        $message = Chat::model()->findByPk($id);
        $this->messageEdit($message);
    }
    
    public function actionForumEdit($id) {
        $message = ForumMessages::model()->findByPk($id);
        $this->messageEdit($message);
    }
    
    public function messageEdit($message) {
        $model = new AdminForm('messageEdit');
        $model->attributes = $message->attributes;
        $this->performAjaxValidation($model);
        if (isset($_POST['AdminForm'])) {
            $model->attributes = $_POST['AdminForm'];
            if ($model->validate()) {
                if ($model->is_delete) {
                    if (!$message->delete()) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при работе с сообщением!'));
                    }
                }
                if ($model->message != $message->message) {
                    $message->message = $model->message;
                    $message->answer = 'отредактировал '.Yii::app()->user->login;
                    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', 'Ошибка при работе с пользователем!'));
                    }
                    $mail = new UserMail();
                    $mail->who = 0;
                    $mail->whom = $message->id_user;
                    $mail->id_user = $message->id_user;
                    $mail->text = 'Вы получили наказание "Молчание на '.$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('messageEdit', array(
            'model'=>$model,
            'message'=>$message,
        ));
    }
    
    /**
     * Performs the AJAX validation.
     * @param UserGroups $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'panel-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}