<?php

namespace Core\Router;

class Router
{
    private array $routes = [];

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

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

    public function resolve()
    {
        $method = $_SERVER['REQUEST_METHOD'];

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

        $basePath = $_ENV['BASE_PATH'] ?? '';

        $uri = str_replace($basePath, '', $uri);

        if ($uri === '') {
            $uri = '/';
        }

        $handler = $this->routes[$method][$uri] ?? null;

        if (!$handler) {
            http_response_code(404);
            exit('404 Not Found');
        }

        return $handler();
    }
}