<?php

namespace Model;

use Config\Clean;
use Config\Validate;
use Exception;
use Exceptions\InvalidLoginOrPasswordException;
use Exceptions\InexistantLoginException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

/**
 * Permet de développer les fonctions appelées par le controllerCandidate pour gérer
 * les actions de l'utilisateur
 */
class ModelCandidate
{

    private Client $client;

    public function __construct(){
        $this->client = new Client();
    }

    /**
     * Permet de soumettre et d'envoyer la réponse à un formulaire.
     *
     * @return void
     * @throws Exception
     */
    public function submitForm(): void
    {
        $answersAndCategories = $_POST['answers'];

        $dataIds = null;
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'submitForm') {
            $dataIdsJson = $_POST['data_ids'];
            $dataIds = json_decode($dataIdsJson);
        }

        $answer = [];
        $category = [];
        $questionsId = [];
        foreach ($answersAndCategories as $answerAndCategory) {
            $exploded = explode("||",$answerAndCategory);
            if( count($exploded) == 3 ){
                $questionsId[] = $exploded[0];
                $answer[] = $exploded[1];
                $categs = $exploded[2];
                $categs = explode("_", $categs);
                array_pop($categs);
                $category[] = $categs;
            }
            else {
                $questionsId[] = array_shift($dataIds);
                $answer[] = $answerAndCategory;
                $category[] = [];
            }
        }
        try {
            $res = $this->client->request('GET', 'https://codefirst.iut.uca.fr/containers/Temoignages-deploy_api_form/getForm');
            if ($res->getStatusCode()!=200){
                throw new Exception('GetForm failed');
            }
            $form = json_decode($res->getBody());
            $title = $form[0]["title"];
            $res =$this->client->request('POST', 'https://codefirst.iut.uca.fr/containers/Temoignages-deploy_api_form/insertListResponsesOfCandidate?
                                    id='.implode(",",$questionsId).'&
                                    answer='.implode(",",$answer).'&
                                    category='.implode(",",$category).'&
                                    titleForm='.$title
            );
            if ($res->getStatusCode()!=200){
                throw new Exception('InsertListResponsesOfCandidate failed');
            }
        }catch (GuzzleException $g){
            throw new Exception($g->getMessage(),$g->getCode(),$g);
        }
    }

    /**
     * Permet de récupérer le code html à afficher dans la page du formulaire,
     * on récupère donc le formulaire et toutes les questions qu'il contient.
     * On les traduit en code HTML puis on le retourne. On utilise une Factory
     * pour récupérer les questions.
     *
     * @return string
     * @throws Exception
     */
    public function getForm(): string
    {
        try {
            $res = $this->client->request('GET', 'https://codefirst.iut.uca.fr/containers/Temoignages-deploy_api_form/getForm');
            if ($res->getStatusCode()!=200){
                throw new Exception('GetForm failed');
            }
            $form = json_decode($res->getBody());
            if (empty($form)) {
                return "PAS DE FORMULAIRE\n";
            }

            $title = $form[0]['title'];
            $description = $form[0]['description'];
            $res = $this->client->request('GET', 'https://codefirst.iut.uca.fr/containers/Temoignages-deploy_api_form/getAllQuestions?
                                            idForm='.$form[0]['id']
            );
            if ($res->getStatusCode()!=200){
                throw new Exception('GetAllQuestion failed');
            }
            $questionsTab = json_decode($res->getBody());
        }catch (GuzzleException $g){
            throw new Exception($g->getMessage(),$g->getCode(),$g);
        }


        $questions = Factory::getBuiltObjects($questionsTab, "Question");
        $nbQuestions = count($questions);
        $time = round(($nbQuestions * 20)/60);

        $html = "<div class='container mt-5'>
    <div class='row d-flex justify-content-center align-items-center'>
        <div class='col-md-8'>
            <form id='regForm' method='post'>
                <h1 id='register'>$title</h1>
                <div class='all-steps' id='all-steps'>";

        $html .= str_repeat("<span class='step'><i class='fa'></i></span>", sizeof($questions));
        $html.= "</div>";

        foreach ($questions as $question) {
            $html.= $question->printStrategy()."\n";
        }

        if (count($questions) > 0) {
            $html.= "<div class='thanks-message text-center' id='text-message'> <img src='https://i.imgur.com/O18mJ1K.png' alt='text-message' width='100' class='mb-4' >
                    <h3>Souhaitez-vous envoyer vos réponses ?</span>
                    <input type='hidden' name='data_ids' value=''>
                    <input type='submit' value='Envoyer' id='button'>\n
                    <input type='hidden' name='action' value='submitForm'>
                </div>
                <div style='overflow:auto;' id='nextprevious'>
                    <div style='float:right;'>
                        <button type='button' id='prevBtn' onclick='nextPrev(-1)'><i class='fa fa-angle-double-left'></i></button>
                        <button type='button' id='nextBtn' onclick='nextPrev(1)'><i class='fa fa-angle-double-right'></i></button> </div>
                </div>
            </form>
        </div>
    </div>
</div>";
        } else {
            $html.= "\t\t</form>\n
\t</div>\n";
        }

        return $html;
    }

    /**
     * @throws InvalidLoginOrPasswordException
     * @throws InexistantLoginException
     * @throws Exception
     */
    public function login() :void {
        global $rep,$views,$sel;
        $password = Clean::simpleString($_REQUEST['password']);
        $identifiant = Clean::simpleString($_REQUEST['login']);
        try {
            if (Validate::login($identifiant) && Validate::password($password)) {
                $res = $this->client->request('GET', 'https://codefirst.iut.uca.fr/containers/Temoignages-deploy_api_form/getPasswordWithLogin?
                                                login='.$identifiant
                );
                if ($res->getStatusCode()!=200){
                    throw new Exception('GetPasswordWithLogin failed');
                }
                $passwordbdd = json_decode($res->getBody());
                if ($passwordbdd == null) {
                    throw new InexistantLoginException();
                }
                if (password_verify($sel . $password, $passwordbdd)) {
                    $_SESSION['role'] = 'Admin';
                } else {
                    $_SESSION['role'] = 'Visitor';
                }
            } else {
                throw new InvalidLoginOrPasswordException();
            }
        }catch (GuzzleException $g){
            throw new Exception($g->getMessage(),$g->getCode(),$g);
        }
    }
}
