<?php
namespace Controleur;
use Gateway\CharacterGateway;
use Gateway\SourceGateway;
use Model\CharacterModel;
use Model\CommentaryModel;
use Gateway\CommentaryGateway;
use Model\SourceModel;
use Model\UserModel;
use Gateway\UserGateway;
use Model\QuoteModel;
use Gateway\QuoteGateway;
use Gateway\QuestionGateway;
use Gateway\QuizGateway;
use Gateway\QuizQuestionGateway;
use Model\QuestionModel;
use Model\QuizModel;
use Model\QuizQuestionModel;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use Verification\Verification;
use Enum\TypeSourceEnum;

class UserControler {

    private CommentaryModel $cMod;
    private UserModel $uMod;
    private QuoteModel $qMod;
    private QuestionModel $mdl;
    private CharacterModel $caMod;

    public function __construct() {
        global $co;
        $this->cMod = new CommentaryModel(new CommentaryGateway($co));
        $this->uMod = new UserModel(new UserGateway($co));
        $this->qMod = new QuoteModel(new QuoteGateway($co));
        $this -> mdl = new QuestionModel(new QuestionGateway($co));
        $this -> caMod = new CharacterModel(new CharacterGateway($co));
        $this->srcMod = new SourceModel(new SourceGateway($co));
    }
    
    public function profil() {

        global $vues;
        $p = $this->uMod->getUsername($_SESSION["user"]);
        require_once $vues['profil'];

    }


    public function addComment(){
        global $racine;
        $id = $_POST['idQuote'];
        $this->cMod->createComment(Verification::verifChar($_POST['content']),
                                    Verification::verifChar($_POST['idQuote']),
                                    $this->uMod->getIdByUsername(Verification::verifChar($_SESSION['user'])));
        header("Location:".$racine."/quote/$id");
    }
    

    public function favorite(array $args) {
        global $vues;
        
        $userId = $this->uMod->getIdByUsername($_SESSION["user"]);

        $favorites = $this->qMod->getFavorites($userId);

        require_once $vues['favorite'];
    }

    public function unlog(){
        global $racine;
        session_unset();
        session_destroy();
        $_SESSION = array();
        header("Location:".$racine);
    }

    public function quiz(array $args){
        global $vues;
        $id=$args['id'];
        $nb_questions = $this->getNumberOfQuestion($id);

        $action = $_REQUEST['action'] ?? null;
        switch ($action) {
            case 'canswer':
                if ($this->CorrectAnswer())
                    $_SESSION['score'] = Verification::verifChar( isset( $_SESSION['score']) ? ($_SESSION['score'] + 1) : 1 ) ;
                $this->continueQuiz($id, $nb_questions);
                break;
            default:
                switch($id)
                {
                    case null:
                        // page erreur
                        break;
                    default:
                        $_SESSION['score'] = Verification::verifChar($_SESSION['score'] ?? 0);
                        $this->showQuestion($id, Verification::verifChar($_SESSION['no_question'] ?? 0));
                        break;
                }
        }
    }

    /**
     * @throws SyntaxError
     * @throws RuntimeError
     * @throws LoaderError
     */
    public function continueQuiz(int $id_quiz, int $total_questions) : void
    {
        global $racine;
        $score = $_SESSION['score'];
        $_SESSION['no_question'] = Verification::verifChar( isset($_SESSION['no_question']) ? ($_SESSION['no_question'] + 1) : 1);
        if ($_SESSION['no_question'] >= $total_questions) {
            $_SESSION['no_question'] = 0;
            $this->endQuiz($id_quiz, $score);
            $_SESSION['score'] = 0;
        }
        else header("Location: ".$racine."/quiz/$id_quiz"); ///~kekentin/WF/WF-Website

    }

    /**
     * @throws SyntaxError
     * @throws RuntimeError
     * @throws LoaderError
     */
    public function endQuiz(int $id_quiz, int $score) : void
    {
        global $vues,$co;

        $gw = new QuizGateway($co);
        $mdl = new QuizModel($gw);

        if ($mdl->getQuiz($id_quiz + 1)){
            require_once $vues['endQuiz'];
        }
        require_once $vues['endQuiz'];
    }

    public function CorrectAnswer() : bool
    {
        $answera = Verification::verifChar($_POST['answera'] ?? null);
        $answerb = Verification::verifChar($_POST['answerb'] ?? null);
        $answerc = Verification::verifChar($_POST['answerc'] ?? null);
        $answerd = Verification::verifChar($_POST['answerd'] ?? null);

        $id= null;
        $answer = null;

        if ($answera) {
            $answer = explode('-', $answera)[0];
            $id = (int) explode('-', $answera)[1];
        } elseif ($answerb) {
            $answer = explode('-', $answerb)[0];
            $id = (int) explode('-', $answerb)[1];
        } elseif ($answerc) {
            $answer = explode('-', $answerc)[0];
            $id = (int) explode('-', $answerc)[1];
        } elseif ($answerd) {
            $answer = explode('-', $answerd)[0];
            $id = (int) explode('-', $answerd)[1];
        }
        $res = $this->mdl->getQuestion($id);
        return $answer == $res->getCanswer();
    }

    public function GetQuestion(int $id): array
    {
        global $co;
        $gw = new QuizQuestionGateway($co);
        $mdl = new QuizQuestionModel($gw);
        return $mdl->getAllQuestionByQuiz($id, $co);
    }

    /**
     * @throws RuntimeError
     * @throws SyntaxError
     * @throws LoaderError
     */
    public function showQuestion(int $id, int $num) : void
    {
        global $vues,$twig;
        $q = $this->GetQuestion($id);
        $question = $q[$num] ?? $q[0];
        $idquestion = $question->getIdQuestion();
        require_once $vues['quiz'];

        //echo $twig->render('quiz.html.twig', ['question' => $question,'id'=>$idquestion]);
    }


    public function getNumberOfQuestion(int $id) : int
    {
        global $co;
        $gw = new QuizGateway($co);
        $mdl = new QuizModel($gw);
        return $mdl->getQuiz($id)->getNbQuestions();
    }

    public function addFav(array $arg){
        global $racine;
        $id= $arg['id'] ?? 1;
        $this->uMod->addFavorite(Verification::verifChar($_SESSION["user"]),$id);
        header("Location:" . $racine . "/quote/$id");
        
    }

    public function supFav(array $arg){
        global $racine;
        $id= $arg['id'] ?? 1;
        $this->uMod->supFavorite(Verification::verifChar($_SESSION["user"]),$id);
        header("Location:". $racine ."/quote/$id");
    }

    public function changedata() : void
    {
        global $vues, $racine;
        if ($_POST)
        {
            $newImage = $_POST['image'] ?? null;
            $newPseudo = $_POST['pseudo'] ?? null;
            $newEmail = $_POST['email'] ?? null;
            $newMdpFirst = $_POST['passwdFirst'] ?? null;
            $newMdpSecond = $_POST['passwdSecond'] ?? null;

            //Modif le pseudo
            if($newPseudo){
                $user = $this-> uMod->setUsername($_SESSION['user'], $newPseudo);
                if($user == $newPseudo){ //Si le pseudo existe déjà
                    $_SESSION['user'] = $newPseudo;
                }
            }

            else if($newEmail){
                $user = $this-> uMod->setEmail($_SESSION['user'], $newEmail);
            }

            else if($newMdpFirst && $newMdpSecond){

                if($newMdpFirst == $newMdpSecond){
                    
                    $option = ['cost' => 12];
                    $newPassWd = password_hash($newMdpFirst, PASSWORD_BCRYPT, $option);
                    $user = $this-> uMod->setPassWd($_SESSION['user'], $newPassWd);
                }
            }

            else if($newImage){
                $user = $this->uMod->setImage($_SESSION['user']);
            }
        }
        header("Location: ". $racine."/profil");
       
    }

    /**
     * @throws SyntaxError
     * @throws RuntimeError
     * @throws LoaderError
     */
    public function submit() : void
    {
        global $vues;
        $p = $this->caMod->getAllPerso();
        $s = $this->srcMod->getAllSources();
        require_once $vues['submitQuote'];
    }

    /**
     * @throws SyntaxError
     * @throws RuntimeError
     * @throws LoaderError
     */
    public function toSubmit() : ?array
    {
        global $co;
        if ($_POST)
        {
            $content = $_POST['content'] ?? null;
            $character = $_POST['character'] ?? null;
            $source  = $_POST['src'] ?? null;
            //$img = $_POST['img'] ?? null;

            $errors = [null, null];

            $gw = new CharacterGateway($co);
            $mdl = new CharacterModel($gw);

            $character = $mdl -> getCharacterById($character);

            $gw = new SourceGateway($co);
            $mdl = new SourceModel($gw);

            $source = $mdl -> getSourceById($source);

            if (!$character)
                $errors[0] = "Personnage inexistant";
            if (!$source)
                $errors[1] = "Source inexistante";
            if ($errors[0] || $errors[1])
            {
                global $twig;
                $this->submit();
                exit();
            }

            $gw = new QuoteGateway($co);
            $mdl = new QuoteModel($gw);

            //$mdl -> insert4User($content, '/imgPath', 'fr', $this -> getIdOfUser(), $source->getIdSource(), $character->getIdCharacter());

            return [$content, $_POST['character'], $_POST['src']];
        }
        return null;
    }

    /**
     * @throws SyntaxError
     * @throws RuntimeError
     * @throws LoaderError
     */
    public function validsubmit() : void
    {
        if($_POST['src'] == 'other' && $_POST['character'] == 'other'){
            global $vues;
            $src = true;
            $char = true;
            require_once $vues['create'];
            exit();
        }
        elseif($_POST['src'] == 'other'){
            global $vues;
            $src = true;
            $char = false;
            require_once $vues['create'];
            exit();
        }
        elseif($_POST['character'] == 'other'){
            global $vues;
            $src = false;
            $char = true;
            require_once $vues['create'];
            exit();
        }
        if($_POST)
            $recap = $this -> toSubmit();
        if ($recap)
        {
            $this -> recapSubmitQuote($recap);
        }
    }

    /**
     * @throws RuntimeError
     * @throws SyntaxError
     * @throws LoaderError
     */
    public function recapSubmitQuote(?array $recap) : void
    {
        global $twig;
        echo $twig -> render("recapSubmitQuote.html.twig", ['content' => $recap[0], 'character' => $recap[1], 'source' => $recap[2]]);
    }

    public function getIdOfUser() : ?int
    {
        if (isset($_SESSION['user']))
        {
            global $co;
            $gw = new UserGateway($co);
            $mdl = new UserModel($gw);

            return $mdl -> getUsername($_SESSION['user']) -> getId();
        }
        return null;
    }
}
