<?php
namespace Core;

class Router {
    private array $routes = [];

    public function get(string $path, string $handler): void  { $this->add('GET',  $path, $handler); }
    public function post(string $path, string $handler): void { $this->add('POST', $path, $handler); }

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

    public function dispatch(string $method, string $uri): void {
        $uri = strtok($uri, '?');
        foreach ($this->routes as $route) {
            $pattern = preg_replace('/\{[a-zA-Z]+\}/', '([^/]+)', $route['path']);
            $pattern = '#^' . $pattern . '$#';
            if ($route['method'] === $method && preg_match($pattern, $uri, $matches)) {
                array_shift($matches);
                [$class, $action] = explode('@', $route['handler']);
                $class = "Controllers\\$class";
                (new $class())->$action(...$matches);
                return;
            }
        }
        http_response_code(404);
        require VIEWS . '/errors/404.php';
    }
}
