<?php
/**
 * Router simple pour URLs propres
 * < 50 lignes de code
 */

class Router
{
    private array $routes = [];

    public function add(string $pattern, string $handler): self
    {
        // Convertit {param} en regex ([^/]+)
        $regex = preg_replace('/\{(\w+)\}/', '([^/]+)', $pattern);
        $regex = '#^' . $regex . '$#';
        $this->routes[$regex] = $handler;
        return $this;
    }

    public function resolve(string $uri): array
    {
        $uri = parse_url($uri, PHP_URL_PATH);
        $uri = rtrim($uri, '/') ?: '/';

        foreach ($this->routes as $regex => $handler) {
            if (preg_match($regex, $uri, $matches)) {
                array_shift($matches); // Enlève le match complet
                return [$handler, $matches];
            }
        }

        return ['pages/404.php', []];
    }

    public function dispatch(): void
    {
        $uri = $_SERVER['REQUEST_URI'] ?? '/';
        [$handler, $params] = $this->resolve($uri);

        // Rend les paramètres accessibles
        $GLOBALS['routeParams'] = $params;

        require __DIR__ . '/../' . $handler;
    }
}
