<?php
class FrontController
{
    function __construct()
    {
        global $dsn, $user, $pass, $vues;
        
        try {
            // Initialize AltoRouter
            $router = new AltoRouter();

            //$router->setBasePath('/');

            // Define routes
            $router->map('GET', '/', 'ControllerUser#home'); // Route pour la page d'accueil
            $router->map('GET|POST', '/[a:action]', 'ControllerUser');
            //$router->map('GET', '/admin', 'ControllerAdminAdministrators');
            $router->map('POST', '/login/[a:action]', 'ControllerUser');
            $router->map('GET', '/admin/chapters', 'ControllerAdminChapters');
            $router->map('POST', '/admin/chapters/[a:action]', 'ControllerAdminChapters');
            $router->map('GET', '/admin/chapters/[a:action]/[i:id]', 'ControllerAdminChapters');
            $router->map('GET', '/admin/administrators', 'ControllerAdminAdministrators');
            $router->map('POST', '/admin/administrators/[a:action]', 'ControllerAdminAdministrators');
            $router->map('GET', '/admin/administrators/[a:action]/[i:id]', 'ControllerAdminAdministrators');
            $router->map('GET', '/admin/questions', 'ControllerAdminQuestions');
            $router->map('POST', '/admin/questions/[a:action]', 'ControllerAdminQuestions');
            $router->map('GET', '/admin/questions/[a:action]/[i:id]', 'ControllerAdminQuestions');

            // Match the current request
            $match = $router->match();

            if (!$match) {
                echo "404"; // Redirige vers une page d'erreur 404
                die;
            }

            if ($match) {
                $controller = $match['target'];
                if (strpos($controller, "#") !== false) {
                    list($controller,$action)=explode("#",$controller);
                }
                else {
                    $action=$match['params']['action'];
                    $id=$match['params']['id'];
                }
                $controller	= new $controller;
                if	(is_callable(array($controller,	$action))) {
                    call_user_func_array(array($controller,	$action), array($match['params']));	
                }
            }
        }
        catch (Exception $e) {
            header("Location:" . $vues["erreur"]);
        }
    }
}
