<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\web\NotFoundHttpException;
use app\models\Question;
use app\models\Survey;

class QuestionController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                        'matchCallback' => function () {
                            return Yii::$app->user->identity->isAdmin();
                        }
                    ],
                ],
            ],
        ];
    }

    public function actionIndex($survey_id)
    {
        $survey = $this->findSurvey($survey_id);
        $questions = Question::find()
            ->where(['survey_id' => $survey_id])
            ->orderBy(['order' => SORT_ASC])
            ->all();

        return $this->render('index', [
            'survey' => $survey,
            'questions' => $questions,
        ]);
    }

    public function actionCreate($survey_id)
    {
        $survey = $this->findSurvey($survey_id);
        $model = new Question();
        $model->survey_id = $survey_id;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('success', 'Вопрос успешно добавлен.');
            return $this->redirect(['index', 'survey_id' => $survey_id]);
        }

        return $this->render('create', [
            'model' => $model,
            'survey' => $survey,
        ]);
    }

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('success', 'Вопрос успешно обновлен.');
            return $this->redirect(['index', 'survey_id' => $model->survey_id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        $surveyId = $model->survey_id;
        $model->delete();

        Yii::$app->session->setFlash('success', 'Вопрос успешно удален.');
        return $this->redirect(['index', 'survey_id' => $surveyId]);
    }

    public function actionMoveUp($id)
    {
        $model = $this->findModel($id);
        
        $prevQuestion = Question::find()
            ->where(['survey_id' => $model->survey_id])
            ->andWhere(['<', 'order', $model->order])
            ->orderBy(['order' => SORT_DESC])
            ->one();
            
        if ($prevQuestion) {
            $temp = $model->order;
            $model->order = $prevQuestion->order;
            $prevQuestion->order = $temp;
            
            $model->save();
            $prevQuestion->save();
        }
        
        return $this->redirect(['index', 'survey_id' => $model->survey_id]);
    }

    public function actionMoveDown($id)
    {
        $model = $this->findModel($id);
        
        $nextQuestion = Question::find()
            ->where(['survey_id' => $model->survey_id])
            ->andWhere(['>', 'order', $model->order])
            ->orderBy(['order' => SORT_ASC])
            ->one();
            
        if ($nextQuestion) {
            $temp = $model->order;
            $model->order = $nextQuestion->order;
            $nextQuestion->order = $temp;
            
            $model->save();
            $nextQuestion->save();
        }
        
        return $this->redirect(['index', 'survey_id' => $model->survey_id]);
    }

    protected function findModel($id)
    {
        if (($model = Question::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('Вопрос не найден.');
    }

    protected function findSurvey($id)
    {
        if (($model = Survey::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('Опрос не найден.');
    }
}