<?php
/**
 * ASISMA CRM - Enrutador MVC
 */
class Router {
    private $routes;

    public function __construct() {
        $routesPath = ROOT_DIR . '/config/routes.php';
        if (!file_exists($routesPath)) {
            throw new Exception("Archivo de rutas no encontrado.");
        }
        $this->routes = require $routesPath;
    }

    public function dispatch($route) {
        $route = trim($route, '/');
        if (empty($route)) {
            $route = 'dashboard';
        }

        if (!array_key_exists($route, $this->routes)) {
            $this->handle404();
            return;
        }

        $routeConfig = $this->routes[$route];

        if (isset($routeConfig['methods'])) {
            $currentMethod = $_SERVER['REQUEST_METHOD'];
            if (!in_array($currentMethod, $routeConfig['methods'])) {
                header("HTTP/1.1 405 Method Not Allowed");
                echo "Método HTTP no permitido.";
                exit;
            }
        }

        $authRequired = isset($routeConfig['auth']) ? $routeConfig['auth'] : true;
        if ($authRequired) {
            AuthMiddleware::handle();
        }

        if (isset($routeConfig['permiso']) && $authRequired) {
            PermissionMiddleware::handle($routeConfig['permiso']);
        }

        // Bitácora total: todo movimiento de un usuario autenticado queda registrado
        if ($authRequired) {
            AuditHelper::registrarMovimiento($route);
        }

        $controllerName = $routeConfig['controller'];
        $actionName     = $routeConfig['action'];

        if (!class_exists($controllerName)) {
            throw new Exception("El controlador '{$controllerName}' no existe.");
        }

        $controllerInstance = new $controllerName();

        if (!method_exists($controllerInstance, $actionName)) {
            throw new Exception("El método '{$actionName}' no existe en el controlador '{$controllerName}'.");
        }

        $controllerInstance->$actionName();
    }

    private function handle404() {
        header("HTTP/1.1 404 Not Found");

        if ($this->isAjax()) {
            header('Content-Type: application/json');
            echo json_encode(array('success' => false, 'message' => 'Ruta no encontrada (404).'));
            exit;
        }

        $title = "404 - No Encontrado";
        require_once ROOT_DIR . '/app/views/layout/head.php';
        echo "<body class='bg-slate-900 text-white flex items-center justify-center h-screen font-sans'>";
        echo "<div class='text-center max-w-md p-6 bg-slate-800 rounded-lg shadow-xl border border-slate-700'>";
        echo "<h1 class='text-7xl font-extrabold text-blue-500 mb-4'>404</h1>";
        echo "<h2 class='text-2xl font-bold mb-2'>Página No Encontrada</h2>";
        echo "<p class='text-slate-400 mb-6'>Lo sentimos, el recurso que está buscando no existe o fue movido.</p>";
        echo "<a href='" . APP_URL . "/dashboard' class='px-5 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors'>Volver al Dashboard</a>";
        echo "</div></body></html>";
        exit;
    }

    private function isAjax() {
        $xrw = isset($_SERVER['HTTP_X_REQUESTED_WITH']) ? strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) : '';
        $accept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : '';
        return (!empty($xrw) && $xrw == 'xmlhttprequest')
               || (strpos($accept, 'application/json') !== false);
    }
}
