<?php

class SupportController extends AdminBaseController {

    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('index', 'answer', 'delete'),
                'roles' => array('moder'),
            ),
            array('allow',
                'actions' => array('categories'),
                'roles' => array('admin'),
            ),
            array('deny',
                'users' => array('*'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            )
        );
    }

    public function actionIndex() {
        $model = new SupportMessages('search');
        $model->unsetAttributes();
        if (isset($_GET['SupportMessages']))
            $model->attributes = $_GET['SupportMessages'];

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

    public function actionAnswer($id) {
        $model = $this->loadModel($id);
        if (isset($_POST['SupportMessages'])) {
            $model->attributes = $_POST['SupportMessages'];
            if ($model->validate()) {
                $model->answer .= '\r\n---------\r\nС уважением, служба поддержки mland.mobi';

                $id_dialog = Users::checkDialog($model->id_user, 101);
                $mail = new UsersMessages();
                $mail->id_dialog = $id_dialog;
                $mail->id_user = 101;
                $mail->users = $model->id_user;
                $mail->message = $model->answer;
                if (!$mail->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при отправке почты!'));
                }
                $model->save(false);
                Yii::app()->user->setFlash('success', 'Ответ отправлен');
                $this->redirect(array('index'));
            }
        }

        $this->render('answer', array(
            'model' => $model,
        ));
    }

    public function actionDelete($id) {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('/panel/support/index'));
    }

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

}
