<?php

class ControllerAdminChapters
{
    private $mdChapter;

    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;
                
                    $this->mdChapter = new ModelChapter();
        
                    $chapters = $this->mdChapter->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->mdChapter->deleteChapter($param["id"]);
        header("Location:/admin/chapters");
    }

    function add($param) {

        $name = $_POST['name'];

        $Chapter = [
            'name' => $name,
        ];

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

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

    function updatemodal($param) {

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

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

    function update($param) {

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

        $Chapter = [
            'name' => $name,
        ];

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

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