<?php

class ControllerAdminChapters
{
    private $gatewayChapter;

    private $twig;
    private $vues;

    function __construct()
    {
            global $dns, $user, $pass, $vues, $twig;
            session_start();
            try {
                if($_SESSION["idAdminConnected"] != null){
                    $this->twig =$twig;
                    $this->vues = $vues;
        
                    $con = new Connection($dns, $user, $pass);
        
                    $this->gatewayChapter = new GatewayChapter($con);
        
                    $chapters = $this->gatewayChapter->getChapters();
        
                    echo $twig->render($vues["adminChapters"], [
                        'chapters' => $chapters,
                    ]);
                }
                else {
                    header("Location:/login");
                }
            } catch (PDOException $e) {
                // Gérez les erreurs PDO ici
            } catch (Exception $e2) {
                // Gérez d'autres erreurs ici
            }
    }

    function delete($param) {
        $this->gatewayChapter->deleteChapter($param["id"]);
        header("Location:/admin/chapters");
    }

    function add($param) {

        $name = $_POST['name'];

        $Chapter = new Chapter($name);

        $this->gatewayChapter->addChapter($Chapter);

        header("Location:/admin/chapters");
    }

    function updatemodal($param) {

        $chapter = $this->gatewayChapter->getChapterByID($param["id"]);

        echo $this->twig->render($this->vues["adminChaptersModal"], [
            'chapter' => $chapter,
        ]);
    }

    function update($param) {

        $id = $_POST['id'];
        $name = $_POST['name'];

        $Chapter = new Chapter($name);

        $this->gatewayChapter->updateChapter($id,$Chapter);

        header("Location:/admin/chapters");
    }
}
