<?php
namespace Tshen;

class Router {
    private array $routes = [];

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

    public function dispatch() {
        $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
        $rawUri = strtok($_SERVER['REQUEST_URI'] ?? '/', '?');
        // Trim application base path (when hosted in a subdirectory like /tshen)
        $base = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/\\');
        if ($base === '/' || $base === '\\') $base = '';
        if ($base !== '' && strpos($rawUri, $base) === 0) {
            $uri = substr($rawUri, strlen($base));
            if ($uri === '') $uri = '/';
        } else {
            $uri = $rawUri;
        }
        // Ensure leading slash
        if ($uri === '' || $uri[0] !== '/') $uri = '/' . ltrim($uri, '/');

        $handler = $this->routes[$method][$uri] ?? null;
        if (!$handler) {
            http_response_code(404);
            echo view('errors/404', ['title' => 'Not Found']);
            return;
        }

        [$controllerName, $action] = explode('@', $handler);
        $class = __NAMESPACE__ . '\\Controllers\\' . $controllerName;
        $controller = new $class();
        echo $controller->$action();
    }
}