<?php
declare(strict_types=1);

namespace App\Core;

class Router
{
    private array $routes = [];

    public function get(string $path, callable|array $handler, array $middleware = []): void
    {
        $this->routes['GET'][$path] = ['handler' => $handler, 'middleware' => $middleware];
    }

    public function post(string $path, callable|array $handler, array $middleware = []): void
    {
        $this->routes['POST'][$path] = ['handler' => $handler, 'middleware' => $middleware];
    }

    public function dispatch(string $uri, string $method): void
    {
        $path = parse_url($uri, PHP_URL_PATH) ?: '/';
        $route = $this->routes[$method][$path] ?? null;
        if (!$route) {
            http_response_code(404);
            echo '404';
            return;
        }
        foreach ($route['middleware'] as $mw) {
            $mwInstance = new $mw();
            if (method_exists($mwInstance, 'handle')) {
                $result = $mwInstance->handle();
                if ($result === false) {
                    return;
                }
            }
        }
        $handler = $route['handler'];
        if (is_array($handler)) {
            $controller = new $handler[0]();
            $methodName = $handler[1];
            $controller->$methodName();
            return;
        }
        call_user_func($handler);
    }
}
