<?php

class Router
{
    private array $routes = [];

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

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

    private function normalize(string $path): string
    {
        $path = trim($path, '/');
        return $path === '' ? '/' : '/' . $path;
    }

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

        // Support ?url=xxx (cPanel no-rewrite fallback) and clean path (localhost with .htaccess)
        $uri = $_GET['url'] ?? $this->pathFromRequestUri();
        $uri = $this->normalize($uri);

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

        if ($handler === null) {
            http_response_code(404);
            require APP_PATH . '/views/errors/404.php';
            return;
        }

        [$controllerName, $action] = explode('@', $handler);
        $controllerFile = APP_PATH . '/controllers/' . $controllerName . '.php';

        if (!file_exists($controllerFile)) {
            http_response_code(500);
            echo "Controller not found: {$controllerName}";
            return;
        }

        require_once $controllerFile;
        $controller = new $controllerName();

        if (!method_exists($controller, $action)) {
            http_response_code(500);
            echo "Action not found: {$controllerName}@{$action}";
            return;
        }

        $controller->$action();
    }

    private function pathFromRequestUri(): string
    {
        $script = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? ''));
        $uri = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
        if ($script !== '/' && $script !== '' && str_starts_with($uri, $script)) {
            $uri = substr($uri, strlen($script));
        }
        return $uri === '' ? '/' : $uri;
    }

    // Helper for views: build a URL that works both on localhost (clean) and
    // cPanel live hosting (index.php?url=) depending on APP_ENV.
    public static function url(string $path = ''): string
    {
        $path = ltrim($path, '/');
        if (APP_ENV === 'local') {
            return BASE_URL . '/' . $path;
        }
        return BASE_URL . '/index.php?url=' . $path;
    }
}
