<?php

namespace controllers;

use \Exception;
use \PDOException;
use models\ModelQuestion;
use models\ModelAnswer;
use models\ModelChapter;

class ControllerAdminQuestions
{
    private $mdQuestion;
    private $mdChapter;
    private $mdAnswer;

    private $twig;
    private $vues;

    function __construct()
    {
        global $vues, $twig;
        session_start();
        try {
            if ($_SESSION["idAdminConnected"] != null) {
                $this->twig = $twig;
                $this->vues = $vues;

                $this->mdQuestion = new ModelQuestion();
                $this->mdAnswer = new ModelAnswer();
                $this->mdChapter = new ModelChapter();
                $questions = array();
                $questions = $this->mdQuestion->getQuestions();
                $chapters = $this->mdChapter->getChapters();

                echo $twig->render($vues["adminQuestions"], [
                    'questions' => $questions,
                    'chapters' => $chapters,
                    'error' => $_SESSION["error"],
                ]);
                $_SESSION["error"] = null;
            } else {
                header("Location:/loginAdmin");
            }
        } catch (PDOException $e) {
            // Gérez les erreurs PDO ici
        } catch (Exception $e2) {
            // Gérez d'autres erreurs ici
        }
    }

    function delete($param)
    {
        $this->mdQuestion->deleteQuestionByID($param["id"]);
        header("Location:/admin/questions");
    }

    function add($param)
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $_SESSION["error"] = "Méthode non autorisée.";
            header("Location:/admin/questions");
        } else {
            $trimmedContent = trim($_POST['content']);
            $trimmedAnswer1 = trim($_POST['answer1']);
            $trimmedAnswer2 = trim($_POST['answer2']);
            $trimmedAnswer3 = trim($_POST['answer3']);
            $trimmedAnswer4 = trim($_POST['answer4']);
            if (
                isset($_POST['content']) && !empty($_POST['content']) && !empty($trimmedContent)
                && isset($_POST['answer1']) && !empty($_POST['answer1']) && !empty($trimmedAnswer1)
                && isset($_POST['answer2']) && !empty($_POST['answer2']) && !empty($trimmedAnswer2)
                && isset($_POST['answer3']) && !empty($_POST['answer3']) && !empty($trimmedAnswer3)
                && isset($_POST['answer4']) && !empty($_POST['answer4']) && !empty($trimmedAnswer4)
            ) {
                $content = $_POST['content'];
                $idChapter = intval($_POST['idChapter']);
                $AnswersPost = array();
                $AnswersPost[0] = $_POST['answer1'];
                $AnswersPost[1] = $_POST['answer2'];
                $AnswersPost[2] = $_POST['answer3'];
                $AnswersPost[3] = $_POST['answer4'];
                $correctAnswer = intval($_POST['correctAnswer']);

                $Question = [
                    'content' => $content,
                    'idchapter' => $idChapter,
                    'idanswergood' => $correctAnswer,
                    'difficulty' => 1,
                    'nbfails' => 0,
                ];

                $idquestion = intval($this->mdQuestion->addQuestion($Question));

                for ($i = 0; $i <= 3; $i++) {
                    $Answers[] = [
                        'content' => $AnswersPost[$i],
                        'idquestion' => $idquestion,
                    ];
                }

                $answersId = array();
                for ($i = 0; $i <= 3; $i++) {
                    $answersId[$i] = $this->mdAnswer->addAnswer($Answers[$i]);
                }

                $Question = [
                    'content' => $content,
                    'idchapter' => $idChapter,
                    'difficulty' => 1,
                    'nbfails' => 0,
                    'idanswergood' => $answersId[$correctAnswer],
                ];

                $this->mdQuestion->updateQuestion($idquestion, $Question);

                header("Location:/admin/questions");
            } else {
                $_SESSION["error"] = "Veuillez remplir tous les champs";
                header("Location:/admin/questions");
            }
        }
    }

    function updatemodal($param)
    {

        $question = $this->mdQuestion->getQuestionByID($param["id"]) ?? null;

        $answers = $this->mdAnswer->getAnswersByIDQuestions($param["id"]) ?? null;

        $chapters = $this->mdChapter->getChapters() ?? null;

        if ($question == null || $answers == null || $chapters == null) {
            $_SESSION["error"] = "Erreur lors de la récupération des données";
            header("Location:/admin/questions");
        } else {

            echo $this->twig->render($this->vues["adminQuestionsModal"], [
                'question' => $question,
                'chapters' => $chapters,
                'answers' => $answers,
            ]);
        }
    }

    function update($param)
    {
        if (
            isset($_POST['content'], $_POST['answer1'], $_POST['answer2'], $_POST['answer3'], $_POST['answer4'], $_POST['idChapter'], $_POST['correctAnswer']) &&
            !empty($_POST['content']) && !empty(trim($_POST['content'])) &&
            !empty($_POST['answer1']) && !empty(trim($_POST['answer1'])) &&
            !empty($_POST['answer2']) && !empty(trim($_POST['answer2'])) &&
            !empty($_POST['answer3']) && !empty(trim($_POST['answer3'])) &&
            !empty($_POST['answer4']) && !empty(trim($_POST['answer4'])) &&
            !empty($_POST['idChapter']) &&
            is_numeric($_POST['correctAnswer']) && $_POST['correctAnswer'] >= 0 && $_POST['correctAnswer'] <= 3
        ) {
            $id = intval($_POST['id']);
            $content = $_POST['content'];
            $idChapter = intval($_POST['idChapter']);
            $correctAnswer = intval($_POST['correctAnswer']);

            $answersId = array();
            $answersId[0] = intval($_POST['IdAnswer1']);
            $answersId[1] = intval($_POST['IdAnswer2']);
            $answersId[2] = intval($_POST['IdAnswer3']);
            $answersId[3] = intval($_POST['IdAnswer4']);

            $answers = array();
            $answers[0] = $_POST['answer1'];
            $answers[1] = $_POST['answer2'];
            $answers[2] = $_POST['answer3'];
            $answers[3] = $_POST['answer4'];


            $questionDataArray = [
                'content' => $content,
                'idchapter' => $idChapter,
                'idanswergood' => $answersId[$correctAnswer],
            ];

            $this->mdQuestion->updateQuestion($id, $questionDataArray);

            for ($i = 0; $i <= 3; $i++) {
                $answersDataArray[] = [
                    'content' => $answers[$i],
                    'id' => $id,
                ];
            }

            for ($i = 0; $i <= 3; $i++) {
                $this->mdAnswer->updateAnswer($answersId[$i], $answersDataArray[$i]);
            }

            header("Location:/admin/questions");

        } else {
            $_SESSION["error"] = "Veuillez remplir tous les champs";
            header("Location:/admin/questions");
        }
    }
}