<?php

class ControllerAdminAdministrators
{
    private $mdAdministrator;

    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->mdAdministrator = new ModelAdministrator();
    
                $administrators = $this->mdAdministrator->getAdministrators();
    
                echo $twig->render($vues["adminAdministrators"], [
                    'administrators' => $administrators,
                ]);
            }
            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->mdAdministrator->deleteAdministratorByID($param["id"]);
        header("Location:/admin/administrators");
    }

    function add($param) {

        $username = $_POST['username'];
        $password = $_POST['password'];

        $Admin = [
            'username' => $username,
            'password' => $password,
        ];

        $this->mdAdministrator->addAdministrator($Admin);

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

    function updatemodal($param) {

        $administrator = $this->mdAdministrator->getAdministratorByID($param["id"]);

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

    function update($param) {

        $id = $_POST['id'];
        $username = $_POST['username'];
        $password = $_POST['password'];

        $Admin = [
            'username' => $username,
            'password' => $password,
        ];

        $this->mdAdministrator->updateAdministrator($id,$Admin);

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