<?php

class ForumController extends Controller {

    public function accessRules() {
        return array(
            array('deny',
                'roles' => array('banned'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            ),
            array('allow',
                'actions' => array('createCategory', 'updateCategory', 'editTheme', 'editMessage', 'deleteMessage'),
                'roles' => array('moder'),
            ),
            array('allow',
                'actions' => array('index', 'category', 'createTheme', 'theme', 'markAsRead'),
                'users' => array('@'),
            ),
            array('deny',
                'users' => array('*'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            )
        );
    }

    public function actionIndex() {
        $count = ForumCategories::model()->count();
        $pages = new CPagination($count);
        // элементов на страницу
        $pages->pageSize = 10;
        $pages->route = '/forum/index/';

        $models = ForumCategories::model()->findAll();

        $this->render('index', array(
            'models' => $models,
            'pages' => $pages,
        ));
    }

    public function actionCategory($id) {
        if ($id == 1) {
            $user = Users::findUser();
            $user->news_ntf = 0;
            if (!$user->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
            }
        }
        $criteria = new CDbCriteria();
        $criteria->compare('id_category', $id);
        $criteria->order = '`vip` DESC, `time` DESC';
        $count = ForumThemes::model()->count($criteria);
        $pages = new CPagination($count);
        // элементов на страницу
        $pages->pageSize = 10;
        $pages->route = '/forum/category/';
        $category = ForumCategories::model()->findByPk($id);
        $models = ForumThemes::model()->findAll($criteria);

        $this->render('category', array(
            'models' => $models,
            'category' => $category,
            'pages' => $pages,
        ));
    }

    public function actionMarkAsRead($id) {
        $this->loadModel($id);
        $user = Users::findUser();
        $criteria = new CDbCriteria();
        $criteria->compare('id_category', $id);
        $themes = ForumThemes::model()->findAll($criteria);
        $ids = CHtml::listData($themes, 'id_theme', 'id_theme');
        $old_ids = CHtml::listData($user->forum_themes, 'id_theme', 'id_theme');
        $user->forum_themes = array_merge($old_ids, $ids);
        $user->forum_themes = array_unique($user->forum_themes);
        if (!$user->save(false)) {
            throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя'));
        }
        $this->redirect(array('forum/category', 'id' => $id));
        Yii::app()->end();
    }

    public function actionCreateCategory() {
        $model = new ForumCategories();
        $this->performAjaxValidation($model);
        if (isset($_POST['ForumCategories'])) {
            $model->attributes = $_POST['ForumCategories'];
            if ($model->validate()) {
                if (!$model->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при создании категории!'));
                }
                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('_category', array(
            'model' => $model,
        ));
    }

    public function actionUpdateCategory($id) {
        if (Yii::app()->user->level > 4 && Yii::app()->user->mute < time()) {
            if (Yii::app()->user->checkAccess('moder')) {
                
            } elseif ($category->id_category > 1) {
                
            }
        }
        $model = ForumCategories::model()->findByPk($id);
        $this->performAjaxValidation($model);
        if (isset($_POST['ForumCategories'])) {
            $model->attributes = $_POST['ForumCategories'];
            if ($model->validate()) {
                if (!$model->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при редактировании категории!'));
                }
                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('_category', array(
            'model' => $model,
        ));
    }

    public function actionTheme($id) {
        $theme = $this->loadModel($id, 'ForumThemes');
        if (!ForumThemesForUsers::checkRead($theme->id_theme)) {
            $ids = CHtml::listData($theme->users, 'id_user', 'id_user');
            $ids[] = Yii::app()->user->id;
            $theme->users = $ids;
            if (!$theme->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении темы!'));
            }
        }
        $count = ForumMessages::model()->countByAttributes(array('id_theme' => $id));
        $model = new ForumMessages('search');
        $comment = new ForumMessages('insert');
        if (strstr(Yii::app()->request->getUrlReferrer(true), 'category')) {
            $model->search($id)->pagination->setCurrentPage(99);
        }
        if (isset($_POST['ForumMessages'])) {
            $comment->attributes = $_POST['ForumMessages'];
            $comment->id_theme = $id;
            if ($comment->validate()) {
                if (!$comment->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при создани комментария!'));
                }
                $theme->users = Yii::app()->user->id;
				$theme->time = time();
                if (!$theme->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении темы!'));
                }
                echo CJSON::encode(array(
                    'status' => 'success',
                    'updateList' => 'messages',
                ));
                Yii::app()->end();
            }
        }

        $this->render('theme', array(
            'model' => $model,
            'theme' => $theme,
            'comment' => $comment,
            'count' => $count
        ));
    }

    public function actionCreateTheme($id) {
        $category = $this->loadModel($id);
        if (Yii::app()->user->level > 9 && Yii::app()->user->mute < time() && (Yii::app()->user->checkAccess('moder') || $id > 1)) {
            $model = new ForumThemes();
            if (isset($_POST['ForumThemes'])) {
                $model->id_category = $id;
                $model->attributes = $_POST['ForumThemes'];
                if ($model->validate()) {
                    if (!$model->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при создании темы!'));
                    }
                    if ($id == 1) {
                        Yii::app()->db->createCommand()->update('users', array('news_ntf' => '1'), '`id_role`!=5 AND `id_role`!=6 AND `news_ntf`=0');
                    }
                    $this->redirect(array('/forum/theme', 'id' => $model->id_theme));
                    Yii::app()->end();
                }
            }
            $this->render('createTheme', array(
                'model' => $model,
            ));
        }
        else {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
    }

    public function actionEditTheme($id) {
        $model = $this->loadModel($id, 'ForumThemes');
        if (isset($_POST['ForumThemes'])) {
            $model->attributes = $_POST['ForumThemes'];
            if ($model->is_delete) {
                $id_category = $model->id_category;
                $model->delete();
                $this->redirect(array('/forum/category', 'id' => $id_category));
                Yii::app()->end();
            }
            if ($model->validate()) {
                if (!$model->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при редактировании темы!'));
                }
                $this->redirect(array('/forum/theme', 'id' => $id));
                Yii::app()->end();
            }
        }
        $this->render('editTheme', array(
            'model' => $model,
        ));
    }

    public function actionEditMessage($id) {
        $message = $this->loadModel($id, 'ForumMessages');
        $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 actionDeleteMessage($id) {
        if (Yii::app()->getRequest()->getIsPostRequest()) {
            $this->loadModel($id, 'ForumMessages')->delete();
            echo "true";
            Yii::app()->end();
        } else {
            throw new CHttpException(400, Yii::t('layout', 'Неверный запрос'));
        }
    }

    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'forum-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function loadModel($id, $name = 'ForumCategories') {
        $model = $name::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, Yii::t('admin_layout', 'Страница не найдена!'));
        return $model;
    }
}
