<?php

namespace app\controllers;

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

class SurveyController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        $user = Yii::$app->user->identity;
        
        if ($user->isAdmin()) {
            $surveys = Survey::find()
                ->orderBy(['created_at' => SORT_DESC])
                ->all();
        } else {
            $surveys = Survey::find()
                ->where(['is_active' => true])
                ->andWhere(['<=', 'start_date', date('Y-m-d')])
                ->andWhere(['>=', 'end_date', date('Y-m-d')])
                ->orderBy(['created_at' => SORT_DESC])
                ->all();
        }

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

    public function actionView($id)
    {
        $survey = $this->findModel($id);
        $user = Yii::$app->user->identity;

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

    public function actionCreate()
    {
        if (!Yii::$app->user->identity->isAdmin()) {
            Yii::$app->session->setFlash('error', 'Только администраторы могут создавать опросы.');
            return $this->redirect(['index']);
        }

        $model = new Survey();

        if ($model->load(Yii::$app->request->post())) {
            $model->is_active = 1; 
            
            if ($model->save()) {
                Yii::$app->session->setFlash('success', 'Опрос успешно создан.');
                return $this->redirect(['view', 'id' => $model->id]);
            } else {
                Yii::$app->session->setFlash('error', 'Ошибка при создании опроса.');
            }
        }

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

    public function actionUpdate($id)
    {
        if (!Yii::$app->user->identity->isAdmin()) {
            Yii::$app->session->setFlash('error', 'Только администраторы могут редактировать опросы.');
            return $this->redirect(['index']);
        }

        $model = $this->findModel($id);

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

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

    public function actionDelete($id)
    {
        if (!Yii::$app->user->identity->isAdmin()) {
            Yii::$app->session->setFlash('error', 'Только администраторы могут удалять опросы.');
            return $this->redirect(['index']);
        }

        $model = $this->findModel($id);
        $model->delete();

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

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

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

   public function actionTake($id)
{
    $survey = $this->findModel($id);
    $user = Yii::$app->user->identity;

    
    if ($user->isAdmin() || !$survey->isActive()) {
        Yii::$app->session->setFlash('error', 'Опрос недоступен.');
        return $this->redirect(['view', 'id' => $survey->id]);
    }

    $questions = \app\models\Question::find()
        ->where(['survey_id' => $survey->id])
        ->orderBy(['order' => SORT_ASC])
        ->all();

    if (empty($questions)) {
        Yii::$app->session->setFlash('error', 'В опросе нет вопросов.');
        return $this->redirect(['view', 'id' => $survey->id]);
    }

   
    $questionIds = array_column($questions, 'id');
    $existingAnswer = \app\models\Answer::find()
        ->where(['user_id' => $user->id])
        ->andWhere(['question_id' => $questionIds])
        ->exists();

    if ($existingAnswer) {
        Yii::$app->session->setFlash('error', 'Вы уже проходили этот опрос.');
        return $this->redirect(['view', 'id' => $survey->id]);
    }

    if (Yii::$app->request->isPost) {
        $answers = Yii::$app->request->post('answers', []);
        $allAnswered = true;
        
        
        foreach ($questions as $question) {
            if ($question->type !== 'text' && empty($answers[$question->id])) {
                $allAnswered = false;
                Yii::$app->session->setFlash('error', "Пожалуйста, ответьте на вопрос: " . $question->question_text);
                break;
            }
        }
        
        if ($allAnswered) {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $savedCount = 0;
                foreach ($questions as $question) {
                    $answerValue = $answers[$question->id] ?? '';
                    
                    $answer = new \app\models\Answer();
                    $answer->user_id = $user->id;
                    $answer->question_id = $question->id;
                    $answer->answer_value = (string)$answerValue;
                    
                    if ($answer->save()) {
                        $savedCount++;
                    }
                }
                
                if ($savedCount > 0) {
                    $transaction->commit();
                    Yii::$app->session->setFlash('success', "Спасибо! Ваши ответы сохранены.");
                    return $this->redirect(['view', 'id' => $survey->id]);
                } else {
                    $transaction->rollBack();
                    Yii::$app->session->setFlash('error', 'Не удалось сохранить ответы.');
                }
            } catch (\Exception $e) {
                $transaction->rollBack();
                Yii::$app->session->setFlash('error', 'Произошла ошибка при сохранении: ' . $e->getMessage());
            }
        }
    }

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


public function actionResults($id)
{
    if (!Yii::$app->user->identity->isAdmin()) {
        Yii::$app->session->setFlash('error', 'Только администраторы могут просматривать результаты.');
        return $this->redirect(['view', 'id' => $id]);
    }

    $survey = $this->findModel($id);
    
    
    $questions = \app\models\Question::find()
        ->where(['survey_id' => $survey->id])
        ->orderBy(['order' => SORT_ASC])
        ->all();
    
    
    $stats = [];
    $answersData = [];
    
    foreach ($questions as $question) {
        
        $answers = \app\models\Answer::find()
            ->where(['question_id' => $question->id])
            ->with(['user'])  
            ->all();
        
        $stats[$question->id] = [
            'total' => count($answers),
            'answers' => $answers,
        ];
        
        $answersData[$question->id] = $answers;
        
        
        if ($question->type === \app\models\Question::TYPE_SCALE) {
            $scaleStats = array_fill(1, 5, 0);
            foreach ($answers as $answer) {
                $value = (int)$answer->answer_value;
                if ($value >= 1 && $value <= 5) {
                    $scaleStats[$value]++;
                }
            }
            $stats[$question->id]['scale_stats'] = $scaleStats;
        }
        
        
        if ($question->type === \app\models\Question::TYPE_SINGLE_CHOICE) {
            $choiceStats = [];
            foreach ($answers as $answer) {
                $value = $answer->answer_value;
                if (!isset($choiceStats[$value])) {
                    $choiceStats[$value] = 0;
                }
                $choiceStats[$value]++;
            }
            $stats[$question->id]['choice_stats'] = $choiceStats;
        }
    }

   
    Yii::info('Статистика собрана для опроса ' . $id);
    Yii::info('Количество вопросов: ' . count($questions));
    Yii::info('Статистика: ' . print_r($stats, true));

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