<?php

class ControllerAdminAdministrators
{
    private $gatewayAdministrator;

    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->gatewayAdministrator = new GatewayAdministrator($con);
    
                $administrators = $this->gatewayAdministrator->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->gatewayAdministrator->deleteAdministratorByID($param["id"]);
        header("Location:/admin/administrators");
    }

    function add($param) {

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

        $Admin = new Administrator($username, $password);

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

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

    function updatemodal($param) {

        $administrator = $this->gatewayAdministrator->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 = new Administrator($username, $password);

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

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