<?php
/**
 * ASISMA CRM - Middleware de Control de Accesos
 */
class PermissionMiddleware {

    public static function handle($modulo) {
        if (SessionHelper::isAdmin()) {
            return true;
        }

        if (!SessionHelper::hasPermiso($modulo)) {
            $xrw    = isset($_SERVER['HTTP_X_REQUESTED_WITH']) ? strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) : '';
            $accept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : '';
            $isAjax = (!empty($xrw) && $xrw == 'xmlhttprequest')
                      || (strpos($accept, 'application/json') !== false);

            header('HTTP/1.1 403 Forbidden');

            if ($isAjax) {
                header('Content-Type: application/json; charset=utf-8');
                echo json_encode(array(
                    'success' => false,
                    'error'   => true,
                    'message' => 'No posee permisos para acceder al módulo: ' . ($modulo ? $modulo : 'Desconocido')
                ));
                exit;
            }

            $title = "403 - Acceso Denegado";
            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 "<div class='text-red-500 mb-4'><i data-lucide='shield-alert' class='w-20 h-20 mx-auto'></i></div>";
            echo "<h1 class='text-4xl font-bold mb-2'>Acceso Denegado</h1>";
            echo "<p class='text-slate-400 mb-6'>Su rol no cuenta con privilegios para ingresar a la sección <strong>" . htmlspecialchars($modulo) . "</strong>.</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'>Regresar al Inicio</a>";
            echo "</div>";
            echo "<script>lucide.createIcons();</script>";
            echo "</body></html>";
            exit;
        }

        return true;
    }
}
