<?php
/**
 * Módulo de Roles y Permisos
 */

// Iniciar sesión si no está iniciada
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Definir BASE_PATH si no está definido
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__DIR__)));
}

// Verificar si el usuario está logueado
if (!function_exists('isLoggedIn')) {
    function isLoggedIn() {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
}

// Incluir configuración y conexión de base de datos
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

// Obtener conexión a la base de datos
$db = getDB();
$pdo = $db->getConnection();

// Mensajes de estado
$messages = [];

// Obtener roles y permisos
$stmt = $pdo->query("
    SELECT r.*, 
           COUNT(ur.user_id) as user_count
    FROM roles r 
    LEFT JOIN user_roles ur ON r.id = ur.role_id 
    GROUP BY r.id 
    ORDER BY r.name
");
$roles = $stmt->fetchAll();

// Obtener todos los permisos agrupados por módulo
$stmt = $pdo->query("SELECT * FROM permissions ORDER BY module, name");
$all_permissions = $stmt->fetchAll();

// Agrupar permisos por módulo
$permissions = [];
$permissions_by_module = [];
foreach ($all_permissions as $perm) {
    $permissions[$perm['id']] = $perm;
    $permissions_by_module[$perm['module']][] = $perm;
}

// Obtener permisos por rol
$role_ids = array_column($roles, 'id');
if (!empty($role_ids)) {
    $placeholders = str_repeat('?,', count($role_ids) - 1) . '?';
    $stmt = $pdo->prepare("SELECT role_id, permission_id FROM role_permissions WHERE role_id IN ($placeholders)");
    $stmt->execute($role_ids);
    $role_permissions_data = $stmt->fetchAll();
    
    $role_permissions = [];
    foreach ($role_permissions_data as $rp) {
        $role_permissions[$rp['role_id']][] = $rp['permission_id'];
    }
} else {
    $role_permissions = [];
}

// Configurar página
$page_title = 'Roles y Permisos';
ob_start();
?>

<div class="premium-content-area">
    <?php if (!empty($messages)): ?>
        <div class="messages">
            <?php foreach ($messages as $m): ?>
                <div class="notification notification-<?php echo htmlspecialchars($m['type']); ?>">
                    <?php echo htmlspecialchars($m['text']); ?>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
    <!-- Header de Roles -->
    <div class="roles-header">
        <div class="header-left">
            <h1 class="page-title">
                <svg class="title-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M9 12l2 2 4-4"/>
                    <path d="M21 12c-1 0-3-1-3-3s2-3 3-3 3 1 3 3-2 3-3 3"/>
                    <path d="M3 12c1 0 3-1 3-3s-2-3-3-3-3 1-3 3 2 3 3 3"/>
                    <path d="M12 3c0 1-1 3-3 3s-3-2-3-3 1-3 3-3 3 2 3 3"/>
                    <path d="M12 21c0-1 1-3 3-3s3 2 3 3-1 3-3 3-3-2-3-3"/>
                </svg>
                Roles y Permisos
            </h1>
            <p class="page-subtitle">Gestiona roles dinámicamente y asigna permisos de forma granular</p>
        </div>
        <div class="header-actions">
            <?php
            if (!function_exists('userHasPermission')) {
                function userHasPermission($pdo, $permName, $userId) {
                    if (empty($userId)) return false;
                    $stmt = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
                    $stmt->execute([$userId, $permName]);
                    return (bool)$stmt->fetchColumn();
                }
            }
            $current_user_id = $_SESSION['user_id'] ?? 0;
            if (userHasPermission($pdo, 'roles.create', $current_user_id)):
            ?>
            <button class="btn-primary" onclick="openRoleWizard()">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="12" y1="5" x2="12" y2="19"/>
                    <line x1="5" y1="12" x2="19" y2="12"/>
                </svg>
                Crear Rol
            </button>
            <?php endif; ?>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon roles">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
                    <circle cx="8.5" cy="7" r="4"/>
                    <path d="M20 8v6M23 11h-6"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo count($roles); ?></div>
                <div class="stat-label">Roles Activos</div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon permissions">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
                    <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo count($all_permissions); ?></div>
                <div class="stat-label">Permisos Disponibles</div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon modules">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo count($permissions_by_module); ?></div>
                <div class="stat-label">Módulos del Sistema</div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon users">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
                    <circle cx="9" cy="7" r="4"/>
                    <path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo array_sum(array_column($roles, 'user_count')); ?></div>
                <div class="stat-label">Usuarios Asignados</div>
            </div>
        </div>
    </div>

    <!-- Se eliminan formularios clásicos: creación de rol y permiso ahora solo vía asistente -->

    <!-- Roles Table -->
<div class="roles-table-container">
    <div class="table-header">
        <div class="table-title">
            <h2>Roles del Sistema</h2>
            <p>Todos los roles</p>
        </div>
            <div class="table-filters">
                <div class="search-box">
                    <svg class="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="11" cy="11" r="8"/>
                        <path d="m21 21-4.35-4.35"/>
                    </svg>
                    <input type="text" id="roleSearch" placeholder="Buscar roles..." class="search-input">
                </div>
                <select id="moduleFilter" class="filter-select">
                    <option value="">Todos los módulos</option>
                    <?php foreach ($permissions_by_module as $module => $perms): ?>
                        <option value="<?php echo htmlspecialchars($module); ?>"><?php echo ucfirst($module); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <?php if (empty($roles)): ?>
            <div class="empty-state">
                <div class="empty-icon">
                    <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="10"/>
                        <line x1="12" y1="8" x2="12" y2="12"/>
                        <circle cx="12" cy="16" r="1"/>
                    </svg>
                </div>
                <h3>No hay roles creados</h3>
                <p>Crea un rol inicial con el asistente guiado.</p>
                <button class="btn-primary" onclick="openRoleWizard()">Crear Rol con Asistente</button>
            </div>
        <?php endif; ?>

        <div class="roles-grid">
            <?php foreach ($roles as $role): ?>
                <div class="role-card" data-role-id="<?php echo (int)$role['id']; ?>">
                    <div class="role-header">
                        <div class="role-info">
                            <h3 class="role-name"><?php echo htmlspecialchars($role['display_name'] ?? $role['name']); ?></h3>
                            <p class="role-description"><?php echo htmlspecialchars($role['description'] ?? 'Sin descripción'); ?></p>
                        </div>
                        <div class="role-actions">
                            <?php if (userHasPermission($pdo, 'roles.edit', $current_user_id)): ?>
                            <button class="action-btn edit" type="button" onclick="editRole(<?php echo $role['id']; ?>)" title="Editar">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                                    <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
                                </svg>
                            </button>
                            <?php endif; ?>
                            <?php if (userHasPermission($pdo, 'users.view', $current_user_id)): ?>
                            <button class="action-btn" type="button" onclick="openRoleUsersModal(<?php echo $role['id']; ?>)" title="Usuarios del rol">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
                                    <circle cx="8.5" cy="7" r="4"/>
                                    <path d="M20 8v6M23 11h-6"/>
                                </svg>
                            </button>
                            <?php endif; ?>
                            <?php if (userHasPermission($pdo, 'roles.delete', $current_user_id)): ?>
                            <button class="action-btn delete" type="button" onclick="deleteRole(<?php echo $role['id']; ?>)" title="Eliminar">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <polyline points="3,6 5,6 21,6"/>
                                    <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                                </svg>
                            </button>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="role-stats">
                        <div class="stat-item">
                            <span class="stat-value"><?php echo $role['user_count']; ?></span>
                            <span class="stat-text">usuarios</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-value"><?php echo isset($role_permissions[$role['id']]) ? count($role_permissions[$role['id']]) : 0; ?></span>
                            <span class="stat-text">permisos</span>
                        </div>
                    </div>

                </div>
            <?php endforeach; ?>
        </div>
    </div>

</div>

<!-- Modal Asistente de Creación de Roles -->
<div id="roleWizardBackdrop" class="modal-backdrop" style="display:none;">
    <div class="modal modal-premium">
        <div class="modal-header">
            <h3>Asistente: Crear Rol</h3>
            <button class="close-btn" onclick="closeRoleWizard()">&times;</button>
        </div>
        <div class="modal-body">
            <div class="wizard-steps" id="roleWizardSteps">
                <div class="wizard-step-item active" data-step="1">
                    <span class="step-index">1</span>
                    <span class="step-label">Información</span>
                </div>
                <div class="wizard-step-item" data-step="2">
                    <span class="step-index">2</span>
                    <span class="step-label">Permisos</span>
                </div>
                <div class="wizard-step-item" data-step="3">
                    <span class="step-index">3</span>
                    <span class="step-label">Confirmación</span>
                </div>
            </div>
            <div id="wizardStep1" class="wizard-step">
                <h4>1. Información del Rol</h4>
                <div class="form-group">
                    <label class="form-label">Nombre técnico</label>
                    <input type="text" id="wiz_name" class="form-control" placeholder="ej. sales_rep" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Nombre para mostrar</label>
                    <input type="text" id="wiz_display_name" class="form-control" placeholder="Ej. Representante de Ventas" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Descripción</label>
                    <textarea id="wiz_description" class="form-control" rows="3" placeholder="Opcional"></textarea>
                </div>
            </div>

            <div id="wizardStep2" class="wizard-step" style="display:none;">
                <h4>2. Seleccionar Permisos</h4>
                <div class="wizard-tools">
                    <div class="search-box compact">
                        <svg class="search-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="11" cy="11" r="8"/>
                            <path d="m21 21-4.35-4.35"/>
                        </svg>
                        <input type="text" id="wiz_perm_search" placeholder="Buscar permisos o módulos..." class="search-input">
                    </div>
                </div>
                <p class="muted">Marca los permisos que tendrá este rol. Usa búsqueda o selecciona todo por módulo.</p>
                <div class="permissions-by-module">
                    <?php foreach ($permissions_by_module as $module => $module_permissions): ?>
                        <div class="module-section" data-module="<?php echo htmlspecialchars($module); ?>">
                            <div class="module-header">
                                <h5 class="module-title"><?php echo ucfirst($module); ?></h5>
                                <label class="select-all">
                                    <input type="checkbox" class="module-select-all" data-module="<?php echo htmlspecialchars($module); ?>">
                                    Seleccionar todo
                                </label>
                            </div>
                            <div class="module-permissions">
                                <?php foreach ($module_permissions as $permission): ?>
                                    <label class="permission-check">
                                        <input type="checkbox" class="wiz-permission" value="<?php echo (int)$permission['id']; ?>">
                                        <span class="permission-label" data-text="<?php echo htmlspecialchars(strtolower($permission['name'])); ?>"><?php echo htmlspecialchars($permission['name']); ?></span>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div id="wizardStep3" class="wizard-step" style="display:none;">
                <h4>3. Confirmación</h4>
                <div class="review-block">
                    <p><strong>Nombre técnico:</strong> <span id="review_name"></span></p>
                    <p><strong>Nombre para mostrar:</strong> <span id="review_display_name"></span></p>
                    <p><strong>Descripción:</strong> <span id="review_description"></span></p>
                    <p><strong>Permisos seleccionados:</strong></p>
                    <ul id="review_permissions"></ul>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn-secondary" id="wizBackBtn" onclick="wizardPrev()" disabled>Atrás</button>
            <button class="btn-primary" id="wizNextBtn" onclick="wizardNext()">Siguiente</button>
            <button class="btn-primary" id="wizCreateBtn" onclick="wizardCreateRole()" style="display:none;">Crear Rol</button>
        </div>
    </div>
    <style>
        /* estilos específicos del asistente */
        .modal-body{max-height:70vh;overflow:auto}
        .wizard-step{margin-bottom:12px}
        .permissions-by-module{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:12px}
        .module-section{border:1px solid #eee;border-radius:12px;padding:12px; background:#fff}
        .module-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}
        .module-title{margin:0}
        .select-all{font-size:12px;color:#475569;display:flex;align-items:center;gap:8px;cursor:pointer}
        .module-permissions{display:flex;flex-direction:column;gap:6px}
        .permission-check{display:flex;align-items:center;gap:8px}
        .permission-label{line-height:1.4}
        .empty-state{border:1px dashed #cbd5e1;padding:24px;border-radius:12px;text-align:center;background:#f8fafc;margin-bottom:16px}
        .empty-icon{color:#64748b;margin-bottom:8px}
        .wizard-steps{display:flex;gap:12px;margin-bottom:12px}
        .wizard-step-item{display:flex;align-items:center;gap:8px;padding:8px 10px;border:1px solid #e2e8f0;border-radius:10px;color:#475569}
        .wizard-step-item.active{border-color:#1e3a8a;background:#f1f5f9;color:#1e3a8a}
        .step-index{width:22px;height:22px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;background:#e2e8f0;color:#0f172a;font-weight:600}
        .wizard-step-item.active .step-index{background:#1e3a8a;color:#fff}
        .wizard-tools{display:flex;justify-content:flex-end;margin-bottom:8px}
        .search-box.compact{border:1px solid #e2e8f0;border-radius:10px;padding:6px 10px;display:flex;align-items:center;gap:8px}
        .search-box.compact .search-input{border:none;outline:none}
    </style>
</div>

<!-- Ajuste de estilos: centrar contadores en tarjetas de rol -->
<style>
.role-stats { justify-content: center; }
.role-stats .stat-item { text-align: center; }
</style>

<!-- Se elimina el modal del asistente de permisos; la creación de permisos ocurre dentro del asistente de rol -->

<!-- Modal Edición de Rol -->
<div id="editRoleBackdrop" class="modal-backdrop" style="display:none;">
    <div id="editRoleModal" class="modal">
        <div class="modal-header">
            <h3>Editar Rol</h3>
            <button class="close-btn" onclick="closeEditRoleModal()">&times;</button>
        </div>
        <div class="modal-body">
            <input type="hidden" id="edit_role_id">
            <div class="form-group">
                <label class="form-label">Nombre para mostrar</label>
                <input type="text" id="edit_display_name" class="form-control" placeholder="Ej. Representante de Ventas" required>
            </div>
            <div class="form-group">
                <label class="form-label">Descripción</label>
                <textarea id="edit_description" class="form-control" rows="3" placeholder="Opcional"></textarea>
            </div>

            <div class="form-group">
                <label class="form-label">Permisos del rol</label>
                <div class="wizard-tools" style="display:flex;justify-content:flex-end;margin-bottom:8px;">
                    <div class="search-box compact">
                        <svg class="search-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="11" cy="11" r="8"/>
                            <path d="m21 21-4.35-4.35"/>
                        </svg>
                        <input type="text" id="edit_perm_search" placeholder="Buscar permisos o módulos..." class="search-input">
    </div>
</div>
                <div class="permissions-by-module" id="editPermissionsByModule">
                    <?php foreach ($permissions_by_module as $module => $module_permissions): ?>
                        <div class="module-section" data-module="<?php echo htmlspecialchars($module); ?>">
                            <div class="module-header">
                                <h5 class="module-title"><?php echo ucfirst($module); ?></h5>
                                <label class="select-all">
                                    <input type="checkbox" class="edit-module-select-all" data-module="<?php echo htmlspecialchars($module); ?>">
                                    Seleccionar todo
                                </label>
                            </div>
                            <div class="module-permissions">
                                <?php foreach ($module_permissions as $permission): ?>
                                    <label class="permission-check">
                                        <input type="checkbox" class="edit-permission" value="<?php echo (int)$permission['id']; ?>">
                                        <span class="permission-label" data-text="<?php echo htmlspecialchars(strtolower($permission['name'])); ?>"><?php echo htmlspecialchars($permission['name']); ?></span>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn-secondary" onclick="closeEditRoleModal()">Cancelar</button>
            <button class="btn-primary" onclick="saveRoleChanges()">Guardar Cambios</button>
        </div>
    </div>
    <div class="modal-overlay" onclick="closeEditRoleModal()"></div>
    <style>
        /* estilado consistente con el asistente */
        #editPermissionsByModule{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:12px}
        #editPermissionsByModule .module-section{border:1px solid #eee;border-radius:12px;padding:12px;background:#fff}
        #editPermissionsByModule .module-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}
        #editPermissionsByModule .module-permissions{display:flex;flex-direction:column;gap:6px}
        .search-box.compact{border:1px solid #e2e8f0;border-radius:10px;padding:6px 10px;display:flex;align-items:center;gap:8px}
        .search-box.compact .search-input{border:none;outline:none}
    </style>
</div>

<!-- Modal Usuarios del Rol -->
<div id="roleUsersBackdrop" class="modal-backdrop" style="display:none;">
    <div id="roleUsersModal" class="modal modal-premium">
        <div class="modal-header">
            <h3>Usuarios del Rol</h3>
            <button class="close-btn" onclick="closeRoleUsersModal()">&times;</button>
        </div>
        <div class="modal-body">
            <div id="roleUsersContent">
                <div class="loading">Cargando usuarios...</div>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn-secondary" onclick="closeRoleUsersModal()">Cerrar</button>
        </div>
    </div>
    <div class="modal-overlay" onclick="closeRoleUsersModal()"></div>
    <style>
        #roleUsersContent .user-row { display:flex; align-items:center; gap:8px; padding:6px 0; border-bottom:1px solid var(--border-light); }
        #roleUsersContent .user-row:last-child { border-bottom:none; }
        #roleUsersContent .user-name { font-weight:600; color: var(--text-primary); }
        #roleUsersContent .user-email { color: var(--text-secondary); font-size:.85rem; }
        #roleUsersContent .muted { color: var(--text-muted); }
        #roleUsersContent .loading { color: var(--text-secondary); }
    </style>
</div>

<script>
// Funciones para gestión de roles
let wizStep = 1;
function openRoleWizard() {
    const backdrop = document.getElementById('roleWizardBackdrop');
    if (backdrop) backdrop.style.display = 'flex';
    wizStep = 1;
    updateWizardUI();
}
function closeRoleWizard() {
    const backdrop = document.getElementById('roleWizardBackdrop');
    if (backdrop) backdrop.style.display = 'none';
}

function updateWizardUI() {
    document.getElementById('wizardStep1').style.display = (wizStep === 1) ? 'block' : 'none';
    document.getElementById('wizardStep2').style.display = (wizStep === 2) ? 'block' : 'none';
    document.getElementById('wizardStep3').style.display = (wizStep === 3) ? 'block' : 'none';
    document.getElementById('wizBackBtn').disabled = (wizStep === 1);
    document.getElementById('wizNextBtn').style.display = (wizStep < 3) ? 'inline-block' : 'none';
    document.getElementById('wizCreateBtn').style.display = (wizStep === 3) ? 'inline-block' : 'none';

    const stepper = document.getElementById('roleWizardSteps');
    if (stepper) {
        stepper.querySelectorAll('.wizard-step-item').forEach(item => {
            const s = parseInt(item.getAttribute('data-step'), 10);
            if (s === wizStep) item.classList.add('active'); else item.classList.remove('active');
        });
    }
}

function wizardNext() {
    if (wizStep === 1) {
        const name = document.getElementById('wiz_name').value.trim();
        const displayName = document.getElementById('wiz_display_name').value.trim();
        if (!name || !displayName) {
            alert('Nombre técnico y nombre para mostrar son obligatorios.');
            return;
        }
    }
    if (wizStep === 2) {
        // preparar resumen
        document.getElementById('review_name').textContent = document.getElementById('wiz_name').value.trim();
        document.getElementById('review_display_name').textContent = document.getElementById('wiz_display_name').value.trim();
        document.getElementById('review_description').textContent = document.getElementById('wiz_description').value.trim();
        const list = document.getElementById('review_permissions');
        list.innerHTML = '';
        document.querySelectorAll('.wiz-permission:checked').forEach(chk => {
            const li = document.createElement('li');
            li.textContent = chk.nextElementSibling?.textContent || ('Permiso #' + chk.value);
            list.appendChild(li);
        });
    }
    wizStep = Math.min(3, wizStep + 1);
    updateWizardUI();
}

function wizardPrev() {
    wizStep = Math.max(1, wizStep - 1);
    updateWizardUI();
}

async function wizardCreateRole() {
    const name = document.getElementById('wiz_name').value.trim();
    const displayName = document.getElementById('wiz_display_name').value.trim();
    const description = document.getElementById('wiz_description').value.trim();
    const permissions = Array.from(document.querySelectorAll('.wiz-permission:checked')).map(chk => chk.value);

    const form = new FormData();
    form.append('name', name);
    form.append('display_name', displayName);
    form.append('description', description);
    permissions.forEach(p => form.append('permissions[]', p));

    try {
        const resp = await fetch('/modules/roles/actions.php?action=create', {
            method: 'POST',
            body: form
        });
        const data = await resp.json();
        if (data.success) {
            alert('Rol creado exitosamente');
            window.location.reload();
        } else {
            alert('Error: ' + (data.error || data.message || 'No se pudo crear'));
        }
    } catch (e) {
        alert('Error de red: ' + e.message);
    }
}

function openQuickRole() {
    openRoleWizard();
}


function closeEditRoleModal() {
    const backdrop = document.getElementById('editRoleBackdrop');
    if (backdrop) backdrop.style.display = 'none';
}

async function editRole(roleId) {
    try {
        const resp = await fetch(`/modules/roles/actions.php?action=get_role_details&role_id=${encodeURIComponent(roleId)}`);
        const data = await resp.json();
        if (data.error || data.success === false) {
            alert('Error: ' + (data.error || data.message || 'No autorizado'));
            return;
        }
        const role = data.role;
        if (!role) {
            alert('No se pudo obtener el detalle del rol.');
            return;
        }
        document.getElementById('edit_role_id').value = roleId;
        document.getElementById('edit_display_name').value = role.display_name || '';
        document.getElementById('edit_description').value = role.description || '';
        // Preseleccionar permisos del rol
        const selectedPermIds = new Set((data.permissions || []).map(p => String(p.id)));
        document.querySelectorAll('#editPermissionsByModule .edit-permission').forEach(ch => {
            ch.checked = selectedPermIds.has(String(ch.value));
        });
        // Actualizar "seleccionar todo" por módulo
        document.querySelectorAll('#editPermissionsByModule .module-section').forEach(section => {
            const allChecks = section.querySelectorAll('.edit-permission');
            const allChecked = Array.from(allChecks).every(ch => ch.checked);
            const selAll = section.querySelector('.edit-module-select-all');
            if (selAll) selAll.checked = allChecked;
        });
        const backdrop = document.getElementById('editRoleBackdrop');
        if (backdrop) backdrop.style.display = 'flex';
    } catch (e) {
        console.error('editRole error', e);
        alert('Error de red: ' + (e && e.message ? e.message : 'Error desconocido'));
    }
}

async function saveRoleChanges() {
    const roleId = document.getElementById('edit_role_id').value;
    const displayName = document.getElementById('edit_display_name').value.trim();
    const description = document.getElementById('edit_description').value.trim();
    if (!displayName) {
        alert('El nombre para mostrar es obligatorio.');
        return;
    }
    const form = new FormData();
    form.append('role_id', roleId);
    form.append('display_name', displayName);
    form.append('description', description);
    try {
        const resp = await fetch('/modules/roles/actions.php?action=update', { method: 'POST', body: form });
        const data = await resp.json();
        if (data.success) {
            // Actualiza la descripción en la tarjeta sin recargar
            const card = document.querySelector(`.role-card[data-role-id="${CSS.escape(roleId)}"]`);
            if (card) {
                const nameEl = card.querySelector('.role-name');
                if (nameEl && displayName) nameEl.textContent = displayName;
                const descEl = card.querySelector('.role-description');
                if (descEl) descEl.textContent = description || 'Sin descripción';
            }
            // Actualizar permisos
            const permForm = new FormData();
            permForm.append('role_id', roleId);
            const selectedPerms = Array.from(document.querySelectorAll('#editPermissionsByModule .edit-permission:checked')).map(ch => ch.value);
            selectedPerms.forEach(p => permForm.append('permissions[]', p));
        const respPerm = await fetch('/modules/roles/actions.php?action=update_permissions', { method: 'POST', body: permForm });
            const permData = await respPerm.json();
            if (!permData.success) {
                alert('Rol guardado, pero no se pudieron actualizar los permisos: ' + (permData.error || permData.message || 'Error desconocido'));
            }
            // Actualiza el contador de permisos en la tarjeta
            if (card) {
                const permCountEl = card.querySelector('.role-stats .stat-item:nth-child(2) .stat-value');
                if (permCountEl) permCountEl.textContent = String(selectedPerms.length);
            }
            closeEditRoleModal();
            alert('Rol actualizado exitosamente');
        } else {
            alert('Error: ' + (data.error || data.message || 'No se pudo actualizar'));
        }
    } catch (e) {
        alert('Error de red: ' + e.message);
    }
}

// Modal Usuarios del Rol
function closeRoleUsersModal() {
    const backdrop = document.getElementById('roleUsersBackdrop');
    if (backdrop) backdrop.style.display = 'none';
}

async function openRoleUsersModal(roleId) {
    const backdrop = document.getElementById('roleUsersBackdrop');
    const content = document.getElementById('roleUsersContent');
    if (backdrop) backdrop.style.display = 'flex';
    if (content) content.innerHTML = '<div class="loading">Cargando usuarios...</div>';
    try {
        const resp = await fetch(`/modules/roles/actions.php?action=get_users&role_id=${encodeURIComponent(roleId)}`);
        const data = await resp.json();
        if (data && data.error) {
            content.textContent = `Error: ${data.error}`;
            return;
        }
        const users = Array.isArray(data) ? data : [];
        if (users.length === 0) {
            content.textContent = 'No hay usuarios asignados a este rol.';
            return;
        }
        const list = document.createElement('div');
        users.forEach(u => {
            const row = document.createElement('div');
            row.className = 'user-row';
            const nameSpan = document.createElement('span');
            nameSpan.className = 'user-name';
            const fullName = `${(u.first_name||'').trim()} ${(u.last_name||'').trim()}`.trim();
            nameSpan.textContent = fullName || u.username || `Usuario #${u.id}`;
            const emailSpan = document.createElement('span');
            emailSpan.className = 'user-email';
            emailSpan.textContent = u.email || '';
            row.appendChild(nameSpan);
            row.appendChild(emailSpan);
            list.appendChild(row);
        });
        content.innerHTML = '';
        content.appendChild(list);
    } catch (e) {
        content.textContent = `Error de red: ${e.message}`;
    }
}

// Exportar funciones al ámbito global para uso desde atributos onclick
window.editRole = editRole;
window.closeEditRoleModal = closeEditRoleModal;
window.saveRoleChanges = saveRoleChanges;
window.openRoleUsersModal = openRoleUsersModal;
window.closeRoleUsersModal = closeRoleUsersModal;

async function deleteRole(roleId) {
    const confirmed = confirm('¿Estás seguro de que deseas eliminar este rol?');
    if (!confirmed) return;
    const form = new FormData();
    form.append('role_id', roleId);
    try {
        const resp = await fetch('/modules/roles/actions.php?action=delete', { method: 'POST', body: form });
        const data = await resp.json();
        if (data.success) {
            const card = document.querySelector(`.role-card[data-role-id="${CSS.escape(roleId)}"]`);
            if (card) card.remove();
            alert('Rol eliminado exitosamente');
        } else {
            alert('Error: ' + (data.error || data.message || 'No se pudo eliminar'));
        }
    } catch (e) {
        alert('Error de red: ' + e.message);
    }
}

// Filtros y búsqueda
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('roleSearch');
    const moduleFilter = document.getElementById('moduleFilter');
    const permSearch = document.getElementById('wiz_perm_search');
    const moduleSelectAll = document.querySelectorAll('.module-select-all');
    
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            filterRoles();
        });
    }
    
    if (moduleFilter) {
        moduleFilter.addEventListener('change', function() {
            filterRoles();
        });
    }

    if (permSearch) {
        permSearch.addEventListener('input', function() {
            const term = permSearch.value.trim().toLowerCase();
            document.querySelectorAll('#wizardStep2 .module-section').forEach(section => {
                const moduleName = (section.getAttribute('data-module') || '').toLowerCase();
                let visibleCount = 0;
                section.querySelectorAll('.permission-check').forEach(row => {
                    const label = row.querySelector('.permission-label');
                    const text = label ? (label.getAttribute('data-text') || label.textContent).toLowerCase() : '';
                    const match = !term || text.includes(term) || moduleName.includes(term);
                    row.style.display = match ? 'flex' : 'none';
                    if (match) visibleCount++;
                });
                section.style.display = (term === '' || visibleCount > 0 || moduleName.includes(term)) ? 'block' : 'none';
            });
        });
    }

    moduleSelectAll.forEach(chk => {
        chk.addEventListener('change', function() {
            const mod = chk.getAttribute('data-module');
            const container = document.querySelector(`#wizardStep2 .module-section[data-module="${CSS.escape(mod)}"]`);
            if (!container) return;
            const rows = container.querySelectorAll('.wiz-permission');
            rows.forEach(cb => { cb.checked = chk.checked; });
        });
    });

    // Edición: seleccionar todo por módulo
    document.querySelectorAll('#editPermissionsByModule .edit-module-select-all').forEach(chk => {
        chk.addEventListener('change', function() {
            const mod = chk.getAttribute('data-module');
            const container = document.querySelector(`#editPermissionsByModule .module-section[data-module="${CSS.escape(mod)}"]`);
            if (!container) return;
            const rows = container.querySelectorAll('.edit-permission');
            rows.forEach(cb => { cb.checked = chk.checked; });
        });
    });

    // Edición: búsqueda en permisos
    const editPermSearch = document.getElementById('edit_perm_search');
    if (editPermSearch) {
        editPermSearch.addEventListener('input', function() {
            const term = editPermSearch.value.trim().toLowerCase();
            document.querySelectorAll('#editPermissionsByModule .module-section').forEach(section => {
                const moduleName = (section.getAttribute('data-module') || '').toLowerCase();
                let visibleCount = 0;
                section.querySelectorAll('.permission-check').forEach(row => {
                    const label = row.querySelector('.permission-label');
                    const text = label ? (label.getAttribute('data-text') || label.textContent).toLowerCase() : '';
                    const match = !term || text.includes(term) || moduleName.includes(term);
                    row.style.display = match ? 'flex' : 'none';
                    if (match) visibleCount++;
                });
                section.style.display = (term === '' || visibleCount > 0 || moduleName.includes(term)) ? 'block' : 'none';
            });
        });
    }

    // Cerrar modales con ESC
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            if (typeof closeEditRoleModal === 'function') closeEditRoleModal();
            if (typeof closeRoleUsersModal === 'function') closeRoleUsersModal();
            if (typeof closeRoleWizard === 'function') closeRoleWizard();
        }
    });
});

function filterRoles() {
    const searchTerm = document.getElementById('roleSearch')?.value.toLowerCase() || '';
    const selectedModule = document.getElementById('moduleFilter')?.value || '';
    const roleCards = document.querySelectorAll('.role-card');
    
    roleCards.forEach(card => {
        const roleName = card.querySelector('.role-name')?.textContent.toLowerCase() || '';
        const roleDescription = card.querySelector('.role-description')?.textContent.toLowerCase() || '';
        const permissionTags = Array.from(card.querySelectorAll('.permission-tag')).map(tag => tag.textContent.toLowerCase());
        
        const matchesSearch = roleName.includes(searchTerm) || roleDescription.includes(searchTerm);
        const matchesModule = !selectedModule || permissionTags.some(tag => tag.includes(selectedModule.toLowerCase()));
        
        if (matchesSearch && matchesModule) {
            card.style.display = 'block';
        } else {
            card.style.display = 'none';
        }
    });
}
</script>

<?php
$content = ob_get_clean();
include BASE_PATH . '/modules/shared/layout.php';
?>