<?php
session_start();
require_once __DIR__ . '/../utils/Auth.php';

// Activation du mode debug
/* ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
ini_set('log_errors', '1');
ini_set('error_log', __DIR__.'/../logs/error.log');
 */
// Nettoyage des tampons de sortie
//while (ob_get_level()) ob_end_clean();

// Définition des constantes
define('ROOT_PATH', dirname(__DIR__));
define('PUBLIC_PATH', __DIR__);

// Autoloader
spl_autoload_register(function ($class) {
    $mappings = [
        'Controllers\\' => ROOT_PATH . '/controllers/',
        'Models\\'      => ROOT_PATH . '/models/',
        'Utils\\'       => ROOT_PATH . '/utils/',
    ];

    foreach ($mappings as $prefix => $dir) {
        if (str_starts_with($class, $prefix)) {
            $relativeClass = substr($class, strlen($prefix));
            $file = $dir . str_replace('\\', '/', $relativeClass) . '.php';

            if (file_exists($file)) {
                require_once $file;
                return;
            }
        }
    }
});

try {
    $routes = require ROOT_PATH . '/config/routes.php';
    $requestUrl = $_GET['url'] ?? 'home';
    $requestUrl = strtolower(trim($requestUrl, '/'));

    if (!isset($routes[$requestUrl])) {
        throw new RuntimeException("Route $requestUrl non trouvée", 404);
    }

    $route = $routes[$requestUrl];

    if (substr_count($route, '@') !== 1) {
        throw new RuntimeException("Route $requestUrl mal définie", 500);
    }

    [$controller, $method] = explode('@', $route);

    if (!class_exists($controller)) {
        throw new RuntimeException("Contrôleur $controller introuvable", 500);
    }

    $instance = new $controller();

    if (!method_exists($instance, $method)) {
        throw new RuntimeException("Méthode $method introuvable dans $controller", 500);
    }

    $reflection = new ReflectionMethod($instance, $method);
    $paramCount = $reflection->getNumberOfParameters();

    if ($paramCount > 0) {
        $params = [];
        foreach ($reflection->getParameters() as $param) {
            $name = $param->getName();
            $params[] = $_GET[$name] ?? null;
        }
        call_user_func_array([$instance, $method], $params);
    } else {
        $instance->$method();
    }

} catch (Throwable $e) {
    http_response_code($e->getCode() ?: 500);
    echo "<h1>Erreur</h1>";
    echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>";
}
