<?php

namespace App\Core;

class Router
{
    protected array $routes = [];
    
    public function get(string $path, array $handler): void
    {
        $this->addRoute('GET', $path, $handler);
    }
    
    public function post(string $path, array $handler): void
    {
        $this->addRoute('POST', $path, $handler);
    }

    protected function addRoute(string $method, string $path, array $handler): void
    {
        $this->routes[$method][$path] = $handler;
    }

    public function dispatch(): void
    {
        $requestMethod = $_SERVER['REQUEST_METHOD'];
        $requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

        // --- INICIO DE LA LÓGICA MEJORADA ---
        // Calcula la ruta base dinámicamente.
        // Esto funciona tanto en subcarpetas (local) como en la raíz (producción).
        $basePath = dirname($_SERVER['SCRIPT_NAME']);
        if ($basePath === '/' || $basePath === '\\') {
            $basePath = '';
        }

        if (strpos($requestUri, $basePath) === 0) {
            $requestUri = substr($requestUri, strlen($basePath));
        }
        // --- FIN DE LA LÓGICA MEJORADA ---

        if (empty($requestUri)) {
            $requestUri = '/';
        }

        $handler = null;
        $params = [];

        if (isset($this->routes[$requestMethod])) {
            foreach ($this->routes[$requestMethod] as $route => $routeHandler) {
                $pattern = preg_replace('/\{([a-zA-Z]+)\}/', '(?P<$1>[^/]+)', $route);
                $pattern = '#^' . $pattern . '$#';

                if (preg_match($pattern, $requestUri, $matches)) {
                    $handler = $routeHandler;
                    foreach ($matches as $key => $value) {
                        if (is_string($key)) {
                            $params[] = $value;
                        }
                    }
                    break;
                }
            }
        }

        if (!$handler) {
            $this->sendNotFound();
            return;
        }

        [$controllerClass, $method] = $handler;

        if (class_exists($controllerClass) && method_exists($controllerClass, $method)) {
            $controller = new $controllerClass();
            call_user_func_array([$controller, $method], $params);
        } else {
            $this->sendNotFound();
        }
    }

    protected function sendNotFound(): void
    {
        http_response_code(404);
        echo "<h1>404 - Página no encontrada</h1>";
    }
}
