<?php

namespace App\Core;

class Router {
    protected $routes = [];

    public function add($route, $handler) {
        $this->routes[$route] = $handler;
    }

    public function run() {
        $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        
        // Use APP_URL to detect the base path
        $appUrl = parse_url(APP_URL, PHP_URL_PATH) ?? '';
        $basePath = rtrim($appUrl, '/');

        // Strip Base Path from URI if project is in a subdirectory
        if (!empty($basePath) && strpos($uri, $basePath) === 0) {
            $uri = substr($uri, strlen($basePath));
        }

        // Clean URI for matching
        $uri = '/' . ltrim($uri, '/');
        if ($uri !== '/') {
            $uri = rtrim($uri, '/');
        }

        if (isset($this->routes[$uri])) {
            $handler = $this->routes[$uri];
            $controllerName = "App\\Controllers\\" . $handler[0];
            $methodName = $handler[1];

            if (class_exists($controllerName)) {
                $controller = new $controllerName();
                if (method_exists($controller, $methodName)) {
                    $controller->$methodName();
                } else {
                    echo "Method $methodName not found in $controllerName";
                }
            } else {
                echo "Controller $controllerName not found";
            }
        } else {
            http_response_code(404);
            echo "404 - Not Found";
        }
    }
}
