<?php
namespace Controleur;

use Model\QuoteModel;
use Model\CommentaryModel;
use Gateway\Connection;
use Gateway\QuoteGateway;
use Gateway\CommentaryGateway;
use Model\SearchModel;
use Gateway\UserGateway;
use Model\UserModel;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;

use Verification\Verification;

Class VisitorControler {

    private QuoteModel $qMod;
    private CommentaryModel $cMod;

    private SearchModel $sMod;
    
    private UserGateway $gw;

    private UserModel $uMod;

    private array $errors;


    /**
     * @throws SyntaxError
     * @throws RuntimeError
     * @throws LoaderError
     */
    public function __construct() {
        global $co;
        $this->qMod = new QuoteModel(new QuoteGateway($co));
        $this->cMod = new CommentaryModel(new CommentaryGateway($co));
        $this->sMod = new SearchModel(new QuoteGateway($co));
        $this->uMod = new UserModel(new UserGateway($co));
    }

    public function accueil(){
        global $vues;

        // Récupérer la citation du jour via AccueilGateway
        $citationDuJour = $this->qMod->getQuoteOfTheDay('fr');
        $suggestions = $this->qMod->getSuggest(0, 'fr');

        // Passer les données à la vue
        require_once $vues['accueil'];
    }

    public function quote(array $arg){
        global $vues;
        $id= $arg['idQuote'] ?? 1;
        if($id > 999999999){
            $erreur = [404,"Citation inexistante pour le moment",'../'];
            require_once($vues['erreur']);
            exit();
        }
        $f = $this->uMod->isFavorite($_SESSION["user"],$id);
        $q = $this->qMod->searchId($id);
        $c = $this->cMod->getComment($id);
        if($q->getContent() != 'NULL'){
            require_once $vues['quote'];
        }
        else{
            $erreur = [404,"Citation inexistante pour le moment","../"];
            require_once($vues['erreur']);
        }
    }

    public function favorite() {
        global $vues;
        require_once $vues['favorite'];
    }

    public function search(array $arg){
        global $vues;

        $type = ( Verification::verifChar( $_POST['type'] ?? ""));
        $search = ( Verification::verifChar( $_POST['search'] ?? NULL));
        $filtre = ( Verification::verifArrayChar( $arg['filtre'] ?? []));


        $tq=$this->sMod->searchQuote($type,$search,$filtre);

        require_once $vues['search'];
    }

    /**
     * @throws SyntaxError
     * @throws RuntimeError
     * @throws LoaderError
     */
    public function login()
    {
        global $vues;
        require_once $vues['login'];

        //global $twig;

        //echo $twig->render("login.html.twig");

        //$this -> toLogIn();
    }

    /**
     * @throws SyntaxError
     * @throws RuntimeError
     * @throws LoaderError
     */
    public function signin(): void
    {
        global $vues;
        require_once $vues['signin'];

        //global $twig;

        //echo $twig->render("login.html.twig");

        //$this -> signin();
    }


    public function validlogin() : void
    {
        
        global $vues,$racine;
        if ($_POST)
        {
            $pseudo = Verification::verifChar($_POST['pseudo'] ?? null);
            $mdp = Verification::verifChar($_POST['mdp'] ?? null);

            $user = $this -> uMod -> getUsername($pseudo);

            if ($user)
            {
                if (password_verify($mdp, $user->getPassword()))
                {
                    $_SESSION['user'] = Verification::verifChar($pseudo);
                    $_SESSION['role'] = 'user';
                    header("Location: ". $racine); 
                    exit();
                }else
                {
                    global $twig;
                    $errors = "Identifiant ou mot de passe incorrect";
                    require_once $vues['login'];
                    exit();
                }
            }
            else
            {
                global $twig;
                $errors = "Identifiant ou mot de passe incorrect";
                require_once $vues['login'];
                exit();
            }
        }

    }
    /**
     * @throws RuntimeError
     * @throws SyntaxError
     * @throws LoaderError
     */
    public function validsignin() : void
    {
        global $vues,$racine;


        if ($_POST) {
            $pseudo = Verification::verifChar($_POST['pseudo'] ?? null);
            $email = Verification::verifChar($_POST['email'] ?? null);
            $mdp = Verification::verifChar($_POST['mdp'] ?? null);
            $cmdp = Verification::verifChar($_POST['cmdp'] ?? null);

            if ($mdp != $cmdp) {
                $errors[2] = "Mots de passe incorrects";
                
                require_once $vues['signin'];   
                exit();
            }
            $option = ['cost' => 12];
            $hmdp = password_hash($mdp, PASSWORD_BCRYPT, $option);

            $isUserAlreadyUsed = $this -> uMod -> getUsername($pseudo);
            $isEmailAlreadyUsed = $this -> uMod -> getEmail($email);

            if ($isUserAlreadyUsed and !$isEmailAlreadyUsed)  {
                $errors[0] = "Pseudo déjà utilisé";
                require_once $vues['signin'];   
                exit();
            }
            else if ($isEmailAlreadyUsed and !$isUserAlreadyUsed)  {
                $errors[1] = "Email déjà utilisé";
                require_once $vues['signin'];   
                exit();
            }
            else if ($isEmailAlreadyUsed and $isUserAlreadyUsed)  {
                $errors[0] = "Pseudo déjà utilisé";
                $errors[1] = "Email déjà utilisé";
                require_once $vues['signin'];   
                exit();
            }
            else echo $this->uMod->insertUser($pseudo, $email, $hmdp);

            $this->sendEmailSubmit($email, $pseudo);
            

            $_SESSION["role"] = Verification::verifChar('user');
            $_SESSION["user"] = Verification::verifChar($pseudo);

            header("Location: ". $racine);
        }
    }


    function sendEmailSubmit(string $email, string $pseudo) {
        // Génère les données du message
        $sujet = "What The Fantasy - Création de compte";
        $urlImage = "public/images/Baneer.png";


        // Génère une frontière unique pour l'email
        $boundary = "-----=" . md5(uniqid(mt_rand()));
    
        //Instancie les headers
            $headers = "From: noreply@whatTheFantasy.com\r\n";
            $headers .= "MIME-Version: 1.0\r\n";
            $headers .= "Content-Type: multipart/related; boundary=\"$boundary\"\r\n";
        
    
        // Corps de l'email HTML avec l'image intégrée
        $corpsMessage = "--$boundary\r\n";
        $corpsMessage .= "Content-Type: text/html; charset=UTF-8\r\n";
        $corpsMessage .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
    
        // Ajoute le message HTML
        $corpsMessage .= "<html>
        <body>
            <img src=\"cid:image1\" alt=\"Image\" style=\"width: 1200px; height: auto;\" />
            <p>Bonjour $pseudo,</p>
    
            <p>Merci de vous être inscrit sur notre site What The Fantasy. C’est avec grande joie que nous vous accueillons au sein de notre confrérie, pour découvrir ensemble...
            </p>
            <p>À bientôt !</p>
            <p>L'équipe du site</p>
        </body>
    </html>\r\n";
    
        // Ajoute l'image en pièce jointe
        $corpsMessage .= "--$boundary\r\n";
        $corpsMessage .= "Content-Type: image/jpeg; name=\"image.jpg\"\r\n";
        $corpsMessage .= "Content-Transfer-Encoding: base64\r\n";
        $corpsMessage .= "Content-ID: <image1>\r\n\r\n";
    
        
        $imageContent = file_get_contents($urlImage);// Lecture et encodage de l'image en base64
        if ($imageContent === false) {
            return "Impossible de charger l'image spécifiée.";
        }
        $corpsMessage .= chunk_split(base64_encode($imageContent)) . "\r\n";
    
        
        $corpsMessage .= "--$boundary--";// Fin du corps de l'email
    
        
        mail($email, $sujet, $corpsMessage, $headers);// Envoi de l'email
        
    }
}