<?php
declare (strict_types = 1);
namespace MyApp\Controller;

use Dompdf\Dompdf;
use MyApp\Entity\Chambre;
use MyApp\Entity\Compte;
use MyApp\Entity\Etablissement;
use MyApp\Entity\Facture;
use MyApp\Entity\Image_chambre;
use MyApp\Entity\Reservation;
use MyApp\Model\chambre_Model;
use MyApp\Model\compte_Model;
use MyApp\Model\etablissement_Model;
use MyApp\Model\facture_Model;
use MyApp\Model\image_Chambre_Model;
use MyApp\Model\proposer_Model;
use MyApp\Model\reservation_Model;
use MyApp\Model\role_Model;
use MyApp\Model\services_Disponible_Model;
use MyApp\Model\type_Chambre_Model;
use MyApp\Service\DependencyContainer;
use PHPMailer\PHPMailer\PHPMailer;
use Twig\Environment;

class DefaultController
{
    private $twig;
    private $image_Chambre_Model;
    private $type_Chambre_Model;
    private $chambre_Model;
    private $compte_Model;
    private $role_Model;
    private $etablissement_Model;
    private $facture_Model;
    private $proposer_Model;
    private $reservation_Model;
    private $services_Disponible_Model;

    public function __construct(Environment $twig, DependencyContainer $dependencyContainer)
    {
        $this->twig = $twig;
        $this->image_Chambre_Model = $dependencyContainer->get('Image_Chambre_Model');
        $this->type_Chambre_Model = $dependencyContainer->get('Type_Chambre_Model');
        $this->chambre_Model = $dependencyContainer->get('Chambre_Model');
        $this->compte_Model = $dependencyContainer->get('Compte_Model');
        $this->role_Model = $dependencyContainer->get('Role_Model');
        $this->etablissement_Model = $dependencyContainer->get('Etablissement_Model');
        $this->facture_Model = $dependencyContainer->get('Facture_Model');
        $this->proposer_Model = $dependencyContainer->get('Proposer_Model');
        $this->reservation_Model = $dependencyContainer->get('Reservation_Model');
        $this->services_Disponible_Model = $dependencyContainer->get('Services_Disponible_Model');
    }

    public function accueil()
    {
        if (isset($_SESSION['id_role'])) {
            header('Location: index.php?page=accueil_client');
        }
        $image_chambre = $this->image_Chambre_Model->getAllImageChambre();
        $reservation = $this->reservation_Model->getAllReservation();
        $chambre = $this->chambre_Model->getAllChambre();
        echo $this->twig->render('defaultController/accueil.html.twig', ['image_chambre' => $image_chambre, 'reservation' => $reservation, 'chambre' => $chambre]);
    }

    public function accueil_client()
    {
        if (!isset($_SESSION['id_role'])) {
            header('Location: index.php?page=accueil');
        }
        $image_chambre = $this->image_Chambre_Model->getAllImageChambre();
        $reservation = $this->reservation_Model->getAllReservation();
        $chambre = $this->chambre_Model->getAllChambre();
        echo $this->twig->render('defaultController/accueil_c.html.twig', ['image_chambre' => $image_chambre, 'reservation' => $reservation, 'chambre' => $chambre]);
    }

    public function accueil_admin()
    {
        if (isset($_SESSION['id_role'])) {
            if ($_SESSION['id_role'] === 2) {
                header('Location: index.php?page=accueil_client');
            }
        } else {
            header('Location: index.php?page=accueil_client');
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $nom = filter_input(INPUT_POST, 'nom', FILTER_SANITIZE_STRING);
            $prenom = filter_input(INPUT_POST, 'prenom', FILTER_SANITIZE_STRING);
            $num_telephone = filter_input(INPUT_POST, 'num_telephone', FILTER_SANITIZE_STRING);
            $mail = filter_input(INPUT_POST, 'mail', FILTER_SANITIZE_STRING);
            $mot_de_passe = filter_input(INPUT_POST, 'mot_de_passe', FILTER_SANITIZE_STRING);
            $id_role = filter_input(INPUT_POST, 'id_role', FILTER_SANITIZE_NUMBER_INT);
            if (!empty($_POST['nom']) && !empty($_POST['prenom']) && !empty($_POST['num_telephone']) && !empty($_POST['mail']) && !empty($_POST['mot_de_passe']) && !empty($_POST['id_role'])) {
                // traduction role en identifiant de la table Role
                if ($id_role === 'admin' || $id_role === 'administrateur' || $id_role === '1') {
                    $id_role = $this->role_Model->getOneRole(1);
                } else {
                    $id_role = $this->role_Model->getOneRole(2);
                }
                // on crée le nouvel enregistrement de compte
                $compte = new Compte(null, $nom, $prenom, $num_telephone, $mail, $mot_de_passe, $id_role);
                $success = $this->compte_Model->createCompte($compte);
                if ($success) {
                    header('Location: index.php?page=accueil_admin');
                }
            }

            // on récupère les attributs du formulaire d'ajout de chambre
            $nom = filter_input(INPUT_POST, 'nom', FILTER_SANITIZE_STRING);
            $prix = filter_input(INPUT_POST, 'prix', FILTER_SANITIZE_STRING);
            $nbr_lit = filter_input(INPUT_POST, 'nbr_lit', FILTER_SANITIZE_NUMBER_INT);
            $num_chambre = filter_input(INPUT_POST, 'num_chambre', FILTER_SANITIZE_NUMBER_INT);
            $description = filter_input(INPUT_POST, 'description', FILTER_SANITIZE_STRING);
            $superficie = filter_input(INPUT_POST, 'superficie', FILTER_SANITIZE_STRING);
            $etat = filter_input(INPUT_POST, 'etat', FILTER_SANITIZE_STRING);
            $lien_image = filter_input(INPUT_POST, 'lien_image', FILTER_SANITIZE_STRING);
            $id_type_chambre = filter_input(INPUT_POST, 'id_type_chambre', FILTER_SANITIZE_NUMBER_INT);
            $id_type_chambre = $this->type_Chambre_Model->getOneTypeChambre(intVal($id_type_chambre));

            if (!empty($_POST['nom']) && !empty($_POST['prix']) && !empty($_POST['nbr_lit']) && !empty($_POST['num_chambre']) && !empty($_POST['description']) && !empty($_POST['superficie']) && !empty($_POST['etat']) && !empty($_POST['lien_image']) && !empty($_POST['id_type_chambre'])) {

                // on crée le nouvel enregistrement d'une chambre
                $chambre = new Chambre(null, $nom, floatVal($prix), intval($nbr_lit), intval($num_chambre), $description, floatVal($superficie), $etat, $id_type_chambre);
                $success = $this->chambre_Model->createChambre($chambre);
                $id_chambre = end($this->chambre_Model->getAllChambre());
                $image_chambre = new Image_chambre(null, $lien_image, $id_chambre);
                $success2 = $this->image_Chambre_Model->createImageChambre($image_chambre);
                if ($success && $success2) {
                    header('Location: index.php?page=accueil_admin');
                }
            }
        }
        // on récupère toutes les chambres recherchées et on les affichent
        $liste_chambres = filter_input(INPUT_GET, 'search_chambre', FILTER_SANITIZE_STRING);
        $chambres = $this->chambre_Model->getSearchChambre($liste_chambres);
        // on récupère toutes les images des chambres
        $image_chambres = [];
        foreach ($chambres as $ch) {
            foreach ($image = $this->image_Chambre_Model->getAllImageChambre() as $img) {
                if ($ch->getId() === $img->getId_chambre()->getId()) {
                    array_push($image_chambres, $img);
                }
            }
        }
        // on récupère les comptes recherchée et on les affichent
        $liste_comptes = filter_input(INPUT_GET, 'search_compte', FILTER_SANITIZE_STRING);
        $comptes = $this->compte_Model->getSearchCompte($liste_comptes);
        echo $this->twig->render('defaultController/accueil_a.html.twig', ['comptes' => $comptes, 'chambre' => $chambres, 'image_chambre' => $image_chambres]);
    }

    // méthode pour supprimer un enregistrement
    public function deleteEnregistrement()
    {
        // enregistrement chambre
        $id_image_chambre = filter_input(INPUT_GET, 'Id_image_chambre', FILTER_SANITIZE_NUMBER_INT);
        if ($id_image_chambre != null) {
            $image_chambre = $this->image_Chambre_Model->getOneImageChambre(intval($id_image_chambre));
            $this->chambre_Model->deleteChambre(intVal($image_chambre->getId_chambre()->getId()));
            $this->image_Chambre_Model->deleteImageChambre(intVal($id_image_chambre));
            header('Location: index.php?page=accueil_admin');
        }
        // enregistrement compte
        $id_compte = filter_input(INPUT_GET, 'Id_compte', FILTER_SANITIZE_NUMBER_INT);
        if ($id_compte != null) {
            $this->compte_Model->deleteCompte(intVal($id_compte));
            header('Location: index.php?page=accueil_admin');
        }

    }

    // méthode pour modifier l'enregistrement d'un compte
    public function update_compte()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $id = filter_input(INPUT_POST, 'id_compte', FILTER_SANITIZE_NUMBER_INT);
            $nom = filter_input(INPUT_POST, 'nom', FILTER_SANITIZE_STRING);
            $prenom = filter_input(INPUT_POST, 'prenom', FILTER_SANITIZE_STRING);
            $num_telephone = filter_input(INPUT_POST, 'num_telephone', FILTER_SANITIZE_STRING);
            $mail = filter_input(INPUT_POST, 'mail', FILTER_SANITIZE_STRING);
            $mot_de_passe = filter_input(INPUT_POST, 'mot_de_passe', FILTER_SANITIZE_STRING);
            $id_role = filter_input(INPUT_POST, 'id_role', FILTER_SANITIZE_NUMBER_INT);
            if (!empty($_POST['nom']) && !empty($_POST['prenom']) && !empty($_POST['num_telephone']) && !empty($_POST['mail']) && !empty($_POST['mot_de_passe']) && !empty($_POST['id_role'])) {
                if ($id_role === 'admin' || $id_role === 'administrateur' || $id_role === '1') {
                    $id_role = $this->role_Model->getOneRole(1);
                } else {
                    $id_role = $this->role_Model->getOneRole(2);
                }
                $compte = new Compte(intVal($id), $nom, $prenom, $num_telephone, $mail, $mot_de_passe, $id_role);
                $success = $this->compte_Model->updateCompte($compte);
                if ($success) {
                    header('Location: index.php?page=accueil_admin');
                }
            }
        } else {
            $id = filter_input(INPUT_GET, 'Id_compte', FILTER_SANITIZE_NUMBER_INT);
        }
        $compte = $this->compte_Model->getOneCompte(intVal($id));
        echo $this->twig->render('defaultController/update_compte.html.twig', ['compte' => $compte]);
    }

    // méthode pour modifier l'enregistrement d'une chambre
    public function update_chambre()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $id = filter_input(INPUT_POST, 'id_chambre', FILTER_SANITIZE_NUMBER_INT);
            $id_image_chambre = filter_input(INPUT_POST, 'id_image_chambre', FILTER_SANITIZE_NUMBER_INT);
            $nom = filter_input(INPUT_POST, 'nom', FILTER_SANITIZE_STRING);
            $prix = filter_input(INPUT_POST, 'prix', FILTER_SANITIZE_STRING);
            $nbr_lit = filter_input(INPUT_POST, 'nbr_lit', FILTER_SANITIZE_NUMBER_INT);
            $num_chambre = filter_input(INPUT_POST, 'num_chambre', FILTER_SANITIZE_NUMBER_INT);
            $description = filter_input(INPUT_POST, 'description', FILTER_SANITIZE_STRING);
            $superficie = filter_input(INPUT_POST, 'superficie', FILTER_SANITIZE_STRING);
            $etat = filter_input(INPUT_POST, 'etat', FILTER_SANITIZE_STRING);
            $lien_chambre = filter_input(INPUT_POST, 'lien_image', FILTER_SANITIZE_STRING);
            $id_type_chambre = filter_input(INPUT_POST, 'id_type_chambre', FILTER_SANITIZE_NUMBER_INT);
            $id_type_chambre = $this->type_Chambre_Model->getOneTypeChambre(intVal($id_type_chambre));

            if (!empty($_POST['nom']) && !empty($_POST['prix']) && !empty($_POST['nbr_lit']) && !empty($_POST['num_chambre']) && !empty($_POST['description']) && !empty($_POST['superficie']) && !empty($_POST['etat']) && !empty($_POST['lien_image']) && !empty($_POST['id_type_chambre'])) {
                $chambre = new Chambre(intVal($id), $nom, floatVal($prix), intVal($nbr_lit), intVal($num_chambre), $description, floatVal($superficie), $etat, $id_type_chambre);
                $image_chambre = new Image_chambre(intval($id_image_chambre), $lien_chambre, $chambre);
                $success = $this->chambre_Model->updateChambre($chambre);
                $success2 = $this->image_Chambre_Model->updateImagechambre($image_chambre);
                if ($success && $success2) {
                    header('Location: index.php?page=accueil_admin');
                }
            }
        } else {
            $id_image_chambre = filter_input(INPUT_GET, 'Id_image_chambre', FILTER_SANITIZE_NUMBER_INT);
        }
        $image_chambre = $this->image_Chambre_Model->getOneImageChambre(intVal($id_image_chambre));
        echo $this->twig->render('defaultController/update_chambre.html.twig', ['image_chambre' => $image_chambre]);
    }

    public function connexion()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $mail = filter_input(INPUT_POST, 'mail', FILTER_VALIDATE_EMAIL);
            $mot_de_passe = $_POST['mot_de_passe'];
            if ($mail === false) {
                $_SESSION['message'] = 'Utilisateur ou mot de passe erroné';
                header('Location: index.php?page=connexion');
                exit;
            } else {
                $compte = $this->compte_Model->getCompteByMail($mail);
                if (!$compte) {
                    $_SESSION['message'] = 'Utilisateur ou mot de passe erroné';
                    header('Location: index.php?page=connexion');
                } else {
                    if ($compte->verifyMot_de_passe($mot_de_passe)) {
                        $_SESSION['id'] = $compte->getId();
                        $_SESSION['mail'] = $compte->getMail();
                        $_SESSION['nom'] = $compte->getNom();
                        $_SESSION['prenom'] = $compte->getPrenom();
                        $_SESSION['num_telephone'] = $compte->getNum_telephone();
                        $_SESSION['id_role'] = $compte->getId_role()->getId_Role();
                        // si c'est une client on le redirige vers l'accueil client, sinon vers le panel admin
                        echo $_SESSION['id_role'];
                        if ($_SESSION['id_role'] === 1) {
                            header('Location: index.php?page=accueil_admin');
                        } else {
                            header('Location: index.php?page=accueil_client');
                        }
                        exit;
                    } else {
                        $_SESSION['message'] = 'Utilisateur ou mot de passe erroné';
                        header('Location: index.php?page=connexion');
                        exit;
                    }
                }
            }
        }
        echo $this->twig->render('defaultController/connexion.html.twig', []);
    }

    public function logout()
    {
        $_SESSION = array();
        session_destroy();
        header('Location: index.php');
        exit;
    }

    public function inscription()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $nom = filter_input(INPUT_POST, 'nom', FILTER_SANITIZE_STRING);
            $prenom = filter_input(INPUT_POST, 'prenom', FILTER_SANITIZE_STRING);
            $num_telephone = filter_input(INPUT_POST, 'num_telephone', FILTER_SANITIZE_STRING);
            $mail = filter_input(INPUT_POST, 'mail', FILTER_SANITIZE_STRING);
            $mot_de_passe = filter_input(INPUT_POST, 'mot_de_passe', FILTER_SANITIZE_STRING);
            $id_role = filter_input(INPUT_POST, 'id_role', FILTER_SANITIZE_NUMBER_INT);

            if (!empty($_POST['nom']) && !empty($_POST['prenom']) && !empty($_POST['num_telephone']) && !empty($_POST['mail']) && !empty($_POST['mot_de_passe'])) {
                $id_role = $this->role_Model->getOneRole(2);
                // on crée le nouvel enregistrement de compte
                $compte = new Compte(null, $nom, $prenom, $num_telephone, $mail, $mot_de_passe, $id_role);
                $success = $this->compte_Model->createCompte($compte);
                if ($success) {
                    header('Location: index.php?page=connexion');
                }
            }
        }
        echo $this->twig->render('defaultController/inscription.html.twig', []);
    }

    public function compte()
    {
        $compte = $this->compte_Model->getAllCompte();
        echo $this->twig->render('defaultController/compte.html.twig', ['compte' => $compte, 'mail' => $_SESSION['mail'], 'nom' => $_SESSION['nom'], 'prenom' => $_SESSION['prenom'], 'num_telephone' => $_SESSION['num_telephone'], 'id_role' => $_SESSION['id_role']]);
    }

    public function detailschambre()
    {
        // Récupérer l'ID de la chambre depuis l'URL
        $chambre_id = isset($_GET['id']) ? $_GET['id'] : null;
        $image_chambre = $this->image_Chambre_Model->getAllImageChambre();
        $chambres = $this->chambre_Model->getAllChambre();
        $chambre = $this->chambre_Model->getOneChambre((int) $chambre_id);
        $proposes = $this->proposer_Model->getServicesForOneChambre((int) $chambre_id);
        echo $this->twig->render('defaultController/detailschambre.html.twig', ['proposes' => $proposes, 'image_chambre' => $image_chambre, 'reservation' => $reservation, 'chambre' => $chambre, 'chambres' => $chambres, 'id' => $chambre_id]);
    }

    public function detailschambre_client()
    {
        // Récupérer l'ID de la chambre depuis l'URL
        $_SESSION['id_chambre'] = isset($_GET['id']) ? $_GET['id'] : null;
        $image_chambre = $this->image_Chambre_Model->getAllImageChambre();
        $chambres = $this->chambre_Model->getAllChambre();
        $chambre = $this->chambre_Model->getOneChambre((int) $_SESSION['id_chambre']);
        $proposes = $this->proposer_Model->getServicesForOneChambre((int) $_SESSION['id_chambre']);
        echo $this->twig->render('defaultController/detailschambre_c.html.twig', ['proposes' => $proposes, 'image_chambre' => $image_chambre, 'chambre' => $chambre, 'chambres' => $chambres, 'id' => $_SESSION['id_chambre']]);
    }

    public function reservation_1()
    {
        echo $this->twig->render('defaultController/reservation_1.html.twig', []);
    }

    public function reservation_2()
    {
        $destinataire = $_SESSION["mail"];
        if (isset($_POST['send_pdf'])) {
            require_once __DIR__ . '/../../vendor/autoload.php';

            $date_reception = "2024-01-30"; // Date de réception de la réservation
            $date_remise = "2024-02-03"; // Date de remise de la chambre
            $dompdf = new Dompdf();
            $html = '
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Détails de Réservation</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }
    h1 {
      color: #333;
    }
    table {
      width: 100%;
      border-collapse: collapse;
    }
    th, td {
      border: 1px solid #999;
      padding: 8px;
    }
  </style>
</head>
<body>
  <h1>Détails de Réservation</h1>
  <table>
    <tr>
      <th>Nom</th>
      <td>' . $_SESSION["nom"] . ' ' . $_SESSION["prenom"] . '</td>
    </tr>
    <tr>
      <th>Email</th>
      <td>' . $_SESSION["mail"] . '</td>
    </tr>
    <tr>
      <th>Date d\'arrivée</th>
      <td>' . $date_reception . '</td>
    </tr>
    <tr>
      <th>Date de départ</th>
      <td>' . $date_remise .'</td>
    </tr>
    <tr>
      <th>Chambre</th>
      <td>Chambre Deluxe</td>
    </tr>
    <tr>
      <th>Montant Total</th>
      <td>$300</td>
    </tr>
  </table>
</body>
</html>
';
            $dompdf->loadHtml($html);
            $dompdf->setPaper('A4', 'landscape');
            $dompdf->render();
            $pdf = $dompdf->output(); // on récupère le fichier pdf
            file_put_contents(__DIR__ . '/Details_reservation.pdf', $pdf);

            // on crée un mail
            // on se connecte à notre serveur SMTP
            $mail = new PHPMailer(true);
            $mail->isSMTP();
            $mail->Host = 'smtp.gmail.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'arrasneptune@gmail.com';
            $mail->Password = 'ozey rluw doow gjja';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587;
            // On défini un expediteur et un recepteur
            $mail->setFrom('arrasneptune@gmail.com', 'Hotel Neptune');
            $mail->addAddress($destinataire);
            // on ajoute le pdf
            $mail->addAttachment(__DIR__ . '/Details_reservation.pdf');
            // Contenu
            $mail->isHTML(true);
            $mail->Subject = 'Details de votre reservation de chambre Hotel Neptune';
            $mail->Body = '<p>Votre réservation dans un Hôtel Neptune à Arras a été réglée avec succès.<br> Retrouvez tous les détails de votre réservation dans la pièce jointe ci-dessus.<br>A bientôt chez Neptune Hotel !</p>';
            $mail->Send(); // on envoi le mail
            unlink(__DIR__ . '/Details_reservation.pdf');
            $facture2 = new Facture(null, 1000, 1000, '10 rue des pivoines', 'carte', '2024-12-15', 'aucun', 1);
            $facture = $this->facture_Model->createFacture($facture2);
            $id_lastfacture = $this->facture_Model->getLastFactureId();
            $temp = $_SESSION['id_chambre']+1;
            $id_facture = $this->facture_Model->getOneFacture((int) $id_lastfacture);
            $id_chambre = $this->chambre_Model->getOneChambre((int) $temp); // ID de la chambre réservée (par exemple)
            $id_compte = $this->compte_Model->getOneCompte((int) $_SESSION['id']);; // ID du compte utilisateur qui fait la réservation (par exemple)

            // Créez une nouvelle instance de Reservation avec les données fournies
            $reservation2 = new Reservation(null, $date_reception, $date_remise, $id_lastfacture, $_SESSION['id_chambre']+1, $_SESSION['id']);

            // Appelez la méthode createReservation du modèle Reservation_Model pour insérer la réservation dans la base de données
            $reservation = $this->reservation_Model->createReservation($reservation2);

            header('Location: index.php?page=accueil_client');
        }
        echo $this->twig->render('defaultController/reservation_2.html.twig', []);
    }

    public function contact()
    {
        $etablissements = $this->etablissement_Model->getAllEtablissements();
        echo $this->twig->render('defaultController/contact.html.twig', ['etablissements' => $etablissements]);
    }

    public function error404()
    {
        echo $this->twig->render('defaultController/error404.html.twig', []);
    }

    public function error500()
    {
        echo $this->twig->render('defaultController/error500.html.twig', []);
    }
}
