<?php

namespace App;

class Router {
    private array $routes = [];

    public function __construct() {
    }

    public function addRoute(string $method, string $path, mixed $handler): void {
        $this->routes[] = ['method' => $method, 'path' => $path, 'handler' => $handler];
    }

    public function dispatch() {
        $dispatcher = \FastRoute\simpleDispatcher(function($r) {
            foreach ($this->routes as $route) {
                $r->addRoute($route['method'], $route['path'], $route['handler']);
            }
        });
        $method = $_SERVER['REQUEST_METHOD'];
        $uri = $_SERVER['REQUEST_URI'];
        $path = parse_url($uri, PHP_URL_PATH);
        $routeInfo = $dispatcher->dispatch($method, $path);

        switch ($routeInfo[0]) {
            case \FastRoute\Dispatcher::NOT_FOUND:
                // Handle 404
                http_response_code(404);
                header('Content-Type: application/json');
                echo json_encode(['error' => 'Not Found']);
                break;
            case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
                // Handle 405
                $allowedMethods = $routeInfo[1];
                http_response_code(405);
                header('Content-Type: application/json');
                echo json_encode(['error' => 'Method Not Allowed', 'allowed' => $allowedMethods]);
                break;
            case \FastRoute\Dispatcher::FOUND:
                $handler = $routeInfo[1];
                $vars = $routeInfo[2];
                // Call the handler with route variables
                $handler(...array_values($vars));
                break;
        }
    }
}