<?php

class Router
{
    private array $routes = [];

    public function get(string $uri, array $action, array $middleware = [])
    {
        $this->routes['GET'][$uri] = [
            'action' => $action,
            'middleware' => $middleware
        ];
    }

    public function post(string $uri, array $action, array $middleware = [])
    {
        $this->routes['POST'][$uri] = [
            'action' => $action,
            'middleware' => $middleware
        ];
    }

    public function dispatch(): void
    {
        $method = $_SERVER['REQUEST_METHOD'];

        $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

        // Remove index.php from URI
        $uri = str_replace('/index.php', '', $uri);

        $uri = rtrim($uri, '/') ?: '/';

        if (!isset($this->routes[$method][$uri])) {

            http_response_code(404);

            echo "404 - Route not found: " . $uri;
            return;
        }

        $route = $this->routes[$method][$uri];

        // Execute Middleware
        foreach ($route['middleware'] as $middleware) {

            if (is_array($middleware)) {
                $class = $middleware[0];
                $param = $middleware[1];
                (new $class($param))->handle();
            } else {
                (new $middleware())->handle();
            }
        }

        [$controller, $method] = $route['action'];
        (new $controller())->$method();
    }
}
