<?php
namespace App\Core;

class Router
{
    private array $routes = [];

    public function get(string $p, array $h, array $mw = []): void  { $this->add('GET',  $p, $h, $mw); }
    public function post(string $p, array $h, array $mw = []): void { $this->add('POST', $p, $h, $mw); }

    private function add(string $m, string $p, array $h, array $mw): void
    {
        $pattern = '#^' . \preg_replace('/\{([a-zA-Z_]+)\}/', '(?P<$1>[^/]+)', $p) . '$#';
        $this->routes[] = compact('m', 'pattern', 'h', 'mw');
    }

    public function dispatch(string $method, string $uri): void
    {
        $uri = '/' . \trim(\strtok($uri, '?'), '/');
        foreach ($this->routes as $r) {
            if ($r['m'] !== \strtoupper($method)) continue;
            if (!\preg_match($r['pattern'], $uri, $matches)) continue;
            $params = \array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
            foreach ($r['mw'] as $mw) (new $mw)->handle();
            [$cls, $met] = $r['h'];
            \call_user_func_array([new $cls, $met], \array_values($params));
            return;
        }
        \http_response_code(404);
        if (\file_exists(ROOT . '/resources/views/404.php')) require ROOT . '/resources/views/404.php';
        else echo '404 — Página não encontrada';
    }
}
