<?php
class FrontController
{
    function __construct()
    {
        try {
            global $error, $vues, $rep;
            $nettoyage = new Nettoyage();
            session_start();
            // Check role permissions
            if (isset($_SESSION['role'])) {
                $role = $nettoyage->clean($_SESSION['role']);
            } else {
                $role = "visitor";
            }
            // Check if action exists
            $action = $nettoyage->clean($_REQUEST['action']);
            if ($role == "user") {
                if ($action == NULL) {
                    $_REQUEST['action'] = $action;
                    new UserController();
                } else if (method_exists('UserController', $action) == false) {
                    $error = "Action non valide ";
                    require($rep . $vues['erreur']);
                } else {
                    $_REQUEST['action'] = $action;
                    new UserController();
                }
            }
            else if ($role == "admin") {
                if ($action == NULL) {
                    $_REQUEST['action'] = $action;
                    new AdminController();
                } else if (method_exists('AdminController', $action) == false) {
                    $error = "Action non valide";
                    require($rep . $vues['erreur']);
                } else {
                    $_REQUEST['action'] = $action;
                    new AdminController();
                }
            } else {
                $_REQUEST['action'] = $action;
                new VisitorController();
            }
        } catch (Exception $e) {
            $error = $e->getMessage();
            require($rep . $vues['erreur']);
        }
    }
}