<?php
require_once '../../core/permissions.php';
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../core/format.php';

require_login();
require_permission('admin.users.view');

$page_title = 'Usuarios';
$pdo = db();

$q = isset($_GET['q']) ? trim($_GET['q']) : '';
$role = isset($_GET['role']) ? trim($_GET['role']) : '';
$status = isset($_GET['status']) ? trim($_GET['status']) : '';

$sql = "SELECT * FROM users WHERE 1 = 1";
$params = array();

if ($q !== '') {
    $sql .= " AND (name LIKE ? OR email LIKE ?)";
    $params[] = "%$q%";
    $params[] = "%$q%";
}
if ($role !== '') {
    $sql .= " AND role = ?";
    $params[] = $role;
}
if ($status !== '') {
    $sql .= " AND status = ?";
    $params[] = $status;
}

$sql .= " ORDER BY name ASC, email ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll();

require_once '../../layouts/header.php';
require_once '../../layouts/sidebar.php';
?>

<main class="app-main" id="admin-users-main">
    <style>
    #admin-users-main.app-main { overflow: hidden !important; display: flex !important; flex-direction: column !important; }
    #admin-users-main .content { flex: 1 1 auto; display: flex; flex-direction: column; overflow: hidden; min-height: 0; }
    #admin-users-main .card-table-container { flex: 1 1 auto; display: flex; flex-direction: column; overflow: hidden; min-height: 0; margin-bottom: 0; }
    #admin-users-main .table-container-scroll { flex: 1 1 auto; overflow-y: auto; overflow-x: auto; min-height: 0; -webkit-overflow-scrolling: touch; }
    #admin-users-main .table-container-scroll thead th { position: sticky; top: 0; z-index: 10; background: var(--surface-2); box-shadow: 0 1px 0 var(--border-subtle); }

    #admin-users-main .product-modal-backdrop { position: fixed !important; inset: 0 !important; display: none; align-items: center !important; justify-content: center !important; padding: 24px !important; overflow: hidden !important; background: rgba(0,0,0,0.68) !important; backdrop-filter: blur(5px) !important; z-index: var(--z-modal, 1050) !important; opacity: 0; transition: opacity 0.2s ease !important; }
    #admin-users-main .product-modal-backdrop.show { display: flex !important; opacity: 1 !important; }
    #admin-users-main .product-modal-box { width: min(760px, calc(100vw - 48px)) !important; max-width: calc(100vw - 48px) !important; height: min(700px, calc(100dvh - 100px)) !important; min-height: min(560px, calc(100dvh - 100px)) !important; max-height: calc(100dvh - 100px) !important; display: flex !important; flex-direction: column !important; overflow: hidden !important; background: var(--surface-1) !important; border: 1px solid var(--border-default) !important; border-radius: var(--radius-xl) !important; box-shadow: var(--shadow-lg) !important; transform: translateY(20px); transition: transform 0.2s ease !important; }
    #admin-users-main .product-modal-backdrop.show .product-modal-box { transform: translateY(0); }
    #admin-users-main .product-modal-header { flex: 0 0 auto !important; min-height: 78px !important; padding: 20px 24px !important; display: flex !important; align-items: flex-start !important; justify-content: space-between !important; gap: 14px !important; border-bottom: 1px solid var(--border-subtle) !important; background: var(--surface-1) !important; }
    #admin-users-main .product-modal-body { flex: 1 1 auto !important; min-height: 0 !important; max-height: none !important; padding: 20px 24px !important; overflow-y: auto !important; overflow-x: hidden !important; -webkit-overflow-scrolling: touch !important; overscroll-behavior: contain !important; }
    #admin-users-main .product-modal-footer { flex: 0 0 auto !important; min-height: 76px !important; height: auto !important; padding: 14px 20px !important; display: flex !important; align-items: center !important; justify-content: space-between !important; gap: 12px !important; flex-wrap: nowrap !important; background: var(--surface-0) !important; border-top: 1px solid var(--border-subtle) !important; border-radius: 0 0 var(--radius-xl) var(--radius-xl) !important; overflow: visible !important; }

    #admin-users-main .action-square-btn { width: 42px !important; min-width: 42px !important; max-width: 42px !important; height: 42px !important; min-height: 42px !important; padding: 0 !important; display: inline-flex !important; align-items: center !important; justify-content: center !important; border-radius: var(--radius-lg) !important; flex: 0 0 42px !important; }
    #admin-users-main .modal-footer-actions-right { display: flex !important; align-items: center !important; justify-content: flex-end !important; gap: 12px !important; flex: 1 1 auto !important; min-width: 0 !important; overflow: visible !important; flex-wrap: nowrap !important; }
    #admin-users-main .product-modal-footer .btn { width: auto !important; min-width: 118px !important; height: 48px !important; min-height: 48px !important; padding: 0 18px !important; display: inline-flex !important; align-items: center !important; justify-content: center !important; gap: 8px !important; flex: 0 0 auto !important; white-space: nowrap !important; text-align: center !important; overflow: visible !important; text-overflow: clip !important; border-radius: var(--radius-lg) !important; }
    #admin-users-main .product-modal-footer .btn-primary { min-width: 156px !important; }
    #admin-users-main .product-modal-footer .btn span { display: inline-flex !important; align-items: center !important; justify-content: center !important; max-width: none !important; overflow: visible !important; text-overflow: clip !important; white-space: nowrap !important; }
    #admin-users-main #form-delete-user { flex: 0 0 auto !important; margin-right: auto !important; }
    #admin-users-main #form-delete-user[style*="display: none"] { display: none !important; }
    #admin-users-main .btn-delete-mobile { width: 48px !important; min-width: 48px !important; max-width: 48px !important; height: 48px !important; min-height: 48px !important; padding: 0 !important; flex: 0 0 48px !important; display: inline-flex !important; align-items: center !important; justify-content: center !important; color: var(--color-error) !important; border-color: rgba(255,77,79,0.58) !important; background: rgba(255,77,79,0.06) !important; }
    #admin-users-main .btn-delete-mobile span { display: none !important; }
    #admin-users-main .btn-delete-mobile svg { margin: 0 !important; color: var(--color-error) !important; stroke: var(--color-error) !important; }
    #admin-users-main .user-permissions-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 20px; background: var(--surface-2); padding: 20px; border-radius: var(--radius-md); border: 1px solid var(--border-default); }

    /* ==========================================================================
       FILTROS ADMIN USERS
       ========================================================================== */
    #admin-users-main .admin-user-filter-card {
        flex: 0 0 auto;
        margin-bottom: 16px !important;
        border-radius: var(--radius-xl) !important;
    }

    #admin-users-main .admin-user-filter-card .card-body {
        padding: 14px 16px !important;
    }

    #admin-users-main .admin-user-filters {
        display: grid !important;
        grid-template-columns: minmax(280px, 1fr) minmax(150px, 180px) minmax(150px, 180px) auto auto;
        gap: 10px !important;
        align-items: center !important;
        width: 100% !important;
    }

    #admin-users-main .admin-user-filters .form-field {
        min-width: 0 !important;
        margin: 0 !important;
    }

    #admin-users-main .admin-user-filters .input,
    #admin-users-main .admin-user-filters .select,
    #admin-users-main .admin-user-filters .btn {
        height: 44px !important;
        min-height: 44px !important;
    }

    #admin-users-main .admin-user-filters .select {
        min-width: 0 !important;
        width: 100% !important;
        padding-left: 12px !important;
        padding-right: 34px !important;
        text-overflow: ellipsis !important;
        white-space: nowrap !important;
        overflow: hidden !important;
    }

    #admin-users-main .admin-user-filter-submit,
    #admin-users-main .admin-user-filter-clear {
        min-width: 118px !important;
        justify-content: center !important;
        white-space: nowrap !important;
    }

    #admin-users-main .input-with-icon {
        position: relative;
        width: 100%;
        display: flex;
        align-items: center;
    }

    #admin-users-main .input-with-icon svg {
        position: absolute !important;
        left: 14px !important;
        top: 50% !important;
        transform: translateY(-50%) !important;
        width: 18px !important;
        height: 18px !important;
        color: var(--text-muted) !important;
        pointer-events: none !important;
        z-index: 1;
    }

    #admin-users-main .input-with-icon .input {
        width: 100% !important;
        padding-left: 42px !important;
    }

    /* ==========================================================================
       TABLA USUARIOS - ESCRITORIO
       ========================================================================== */
    #admin-users-main .users-table {
        table-layout: fixed !important;
        width: 100% !important;
        min-width: 0 !important;
    }

    #admin-users-main .users-table .col-user {
        width: 25% !important;
    }

    #admin-users-main .users-table .col-email {
        width: 24% !important;
    }

    #admin-users-main .users-table .col-role {
        width: 16% !important;
    }

    #admin-users-main .users-table .col-status {
        width: 10% !important;
    }

    #admin-users-main .users-table .col-last-login {
        width: 16% !important;
    }

    #admin-users-main .users-table .col-action {
        width: 12% !important;
    }

    #admin-users-main .users-table th,
    #admin-users-main .users-table td {
        min-width: 0 !important;
        vertical-align: middle !important;
    }

    #admin-users-main .users-table .col-email,
    #admin-users-main .users-table .col-last-login {
        white-space: nowrap !important;
        overflow: hidden !important;
        text-overflow: ellipsis !important;
    }

    #admin-users-main .users-table .customer-cell {
        min-width: 0 !important;
        max-width: 100% !important;
    }

    #admin-users-main .users-table .customer-cell-text {
        min-width: 0 !important;
        max-width: 100% !important;
        overflow: hidden !important;
    }

    #admin-users-main .users-table .customer-cell-text strong {
        display: block !important;
        max-width: 100% !important;
        overflow: hidden !important;
        text-overflow: ellipsis !important;
        white-space: nowrap !important;
    }

    #admin-users-main .users-table .col-action .btn {
        width: 40px !important;
        min-width: 40px !important;
        max-width: 40px !important;
        height: 40px !important;
        padding: 0 !important;
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
    }

    @media (max-width: 760px) {
    /* =========================================================
       Mobile layout: pantalla sin scroll vertical global
       Sólo la tabla debe hacer scroll interno
       ========================================================= */
        #admin-users-main.app-main {
            height: 100dvh !important;
            max-height: 100dvh !important;
            overflow: hidden !important;
            display: flex !important;
            flex-direction: column !important;
        }
    
        #admin-users-main .content {
            flex: 1 1 0 !important;
            min-height: 0 !important;
            height: auto !important;
            max-height: none !important;
            display: flex !important;
            flex-direction: column !important;
            overflow: hidden !important;
            padding-bottom: calc(12px + env(safe-area-inset-bottom)) !important;
        }
    
        /* Header compacto */
        #admin-users-main .page-header {
            flex: 0 0 auto !important;
            display: flex !important;
            flex-direction: row !important;
            flex-wrap: nowrap !important;
            justify-content: space-between !important;
            align-items: flex-start !important;
            margin-bottom: 12px !important;
        }
    
        #admin-users-main .page-header-content {
            flex: 1 1 auto !important;
            min-width: 0 !important;
            padding-right: 12px !important;
        }
    
        #admin-users-main .page-header-content h1 {
            font-size: 1.35rem !important;
            line-height: 1.2 !important;
            margin-bottom: 4px !important;
            word-break: break-word !important;
        }
    
        #admin-users-main .page-header-content p {
            display: none !important;
        }
    
        #admin-users-main .actions-cluster {
            flex: 0 0 auto !important;
            display: flex !important;
            gap: 8px !important;
        }
    
        #admin-users-main .mobile-hidden {
            display: none !important;
        }
    
        #admin-users-main .icon-btn-mobile {
            width: 44px !important;
            height: 44px !important;
            min-width: 44px !important;
            max-width: 44px !important;
            padding: 0 !important;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
        }
    
        /* =========================================================
           Filtros móviles
           ========================================================= */
        #admin-users-main .admin-user-filter-card {
            flex: 0 0 auto !important;
            margin-bottom: 12px !important;
        }
    
        #admin-users-main .admin-user-filter-card .card-body {
            padding: 12px !important;
        }
    
        #admin-users-main .admin-user-filters {
            display: grid !important;
            grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) !important;
            gap: 10px !important;
            align-items: stretch !important;
        }
    
        #admin-users-main .admin-user-filter-search,
        #admin-users-main .admin-user-filter-submit,
        #admin-users-main .admin-user-filter-clear {
            grid-column: 1 / -1 !important;
        }
    
        #admin-users-main .admin-user-filter-role,
        #admin-users-main .admin-user-filter-status {
            grid-column: auto !important;
            min-width: 0 !important;
        }
    
        #admin-users-main .admin-user-filters .input,
        #admin-users-main .admin-user-filters .select,
        #admin-users-main .admin-user-filters .btn {
            height: 44px !important;
            min-height: 44px !important;
            font-size: 0.92rem !important;
        }
    
        #admin-users-main .admin-user-filters .select {
            min-width: 0 !important;
            width: 100% !important;
            padding-left: 12px !important;
            padding-right: 32px !important;
            text-overflow: ellipsis !important;
            white-space: nowrap !important;
            overflow: hidden !important;
        }
    
        #admin-users-main .admin-user-filter-submit,
        #admin-users-main .admin-user-filter-clear {
            width: 100% !important;
            min-width: 0 !important;
            justify-content: center !important;
        }
    
        #admin-users-main .admin-user-filter-submit {
            margin-top: 2px !important;
        }
    
        #admin-users-main .admin-user-filter-submit svg,
        #admin-users-main .admin-user-filter-clear svg {
            width: 17px !important;
            height: 17px !important;
        }
    
        /* =========================================================
           Tabla: ocupa alto restante sin crecer la página
           ========================================================= */
        #admin-users-main .card-table-container {
            flex: 1 1 0 !important;
            min-height: 0 !important;
            height: auto !important;
            max-height: none !important;
            display: flex !important;
            flex-direction: column !important;
            overflow: hidden !important;
            margin-bottom: 0 !important;
        }
    
        #admin-users-main .table-container-scroll {
            flex: 1 1 0 !important;
            min-height: 0 !important;
            height: auto !important;
            max-height: none !important;
            overflow-y: auto !important;
            overflow-x: hidden !important;
            -webkit-overflow-scrolling: touch !important;
        }
    
        #admin-users-main .table-mobile-compact {
            width: 100% !important;
            min-width: 100% !important;
            height: auto !important;
            table-layout: fixed !important;
        }
    
        #admin-users-main .col-user {
            width: 55% !important;
        }
    
        #admin-users-main .col-role {
            width: 25% !important;
            padding-left: 4px !important;
            padding-right: 4px !important;
        }
    
        #admin-users-main .col-action {
            width: 20% !important;
        }
    
        /* =========================================================
           Modal usuario móvil
           ========================================================= */
        #admin-users-main .product-modal-backdrop {
            padding: 12px !important;
        }
    
        #admin-users-main .product-modal-box {
            width: calc(100vw - 24px) !important;
            max-width: calc(100vw - 24px) !important;
            height: calc(100dvh - 200px) !important;
            min-height: 0 !important;
            max-height: calc(100dvh - 200px) !important;
            border-radius: 18px !important;
        }
    
        #admin-users-main .product-modal-header {
            min-height: 64px !important;
            padding: 14px !important;
            gap: 10px !important;
        }
    
        #admin-users-main .product-modal-header .h3,
        #admin-users-main .product-modal-header h2 {
            font-size: 1.05rem !important;
            line-height: 1.14 !important;
            margin-bottom: 2px !important;
        }
    
        #admin-users-main .product-modal-header .text-sm {
            font-size: 0.78rem !important;
            line-height: 1.15 !important;
        }
    
        #admin-users-main .product-modal-body {
            padding: 14px !important;
        }
    
        #admin-users-main .form-grid-2 {
            grid-template-columns: 1fr !important;
            gap: 12px !important;
        }
    
        #admin-users-main .user-permissions-grid {
            grid-template-columns: 1fr !important;
            gap: 14px !important;
            padding: 14px !important;
        }
    
        #admin-users-main .product-modal-footer {
            min-height: 68px !important;
            padding: 10px 12px calc(10px + env(safe-area-inset-bottom)) !important;
            gap: 10px !important;
        }
    
        #admin-users-main .modal-footer-actions-right {
            gap: 10px !important;
            flex: 1 1 auto !important;
        }
    
        #admin-users-main .product-modal-footer .btn {
            height: 44px !important;
            min-height: 44px !important;
            min-width: 98px !important;
            padding: 0 12px !important;
            font-size: 0.92rem !important;
            flex: 0 1 auto !important;
        }
    
        #admin-users-main .product-modal-footer .btn-primary {
            min-width: 124px !important;
        }
    
        #admin-users-main .btn-delete-mobile {
            width: 44px !important;
            min-width: 44px !important;
            max-width: 44px !important;
            height: 44px !important;
            min-height: 44px !important;
            padding: 0 !important;
            flex: 0 0 44px !important;
        }
    }
    </style>

    <?php require_once '../../layouts/topbar.php'; ?>

    <section class="content">
        <div class="page-header">
            <div class="page-header-content">
                <span class="label">Administración</span>
                <h1>Usuarios</h1>
                <p class="text-secondary">Gestiona quién tiene acceso al sistema y sus permisos.</p>
            </div>
            <div class="cluster actions-cluster">
                <?php if (user_can('admin.users.edit')): ?>
                <button type="button" class="btn btn-primary icon-btn-mobile" onclick="openUserModal()" title="Nuevo Usuario">
                    <i data-lucide="plus"></i><span class="mobile-hidden">Nuevo Usuario</span>
                </button>
                <?php endif; ?>
            </div>
        </div>

        <section class="card mb-4 admin-user-filter-card">
            <div class="card-body">
                <form method="GET" class="admin-user-filters" style="margin: 0;">
                    <div class="form-field admin-user-filter-search">
                        <div class="input-with-icon">
                            <i data-lucide="search"></i>
                            <input
                                type="text"
                                name="q"
                                class="input"
                                placeholder="Buscar por nombre o email..."
                                value="<?php echo safe_text($q); ?>"
                                autocomplete="off"
                            >
                        </div>
                    </div>

                    <div class="form-field admin-user-filter-role">
                        <select name="role" class="select" onchange="this.form.submit()">
                            <option value="">Todos los roles</option>
                            <option value="admin" <?php echo $role === 'admin' ? 'selected' : ''; ?>>Admin</option>
                            <option value="administracion" <?php echo $role === 'administracion' ? 'selected' : ''; ?>>Administración</option>
                            <option value="comercial" <?php echo $role === 'comercial' ? 'selected' : ''; ?>>Comercial</option>
                            <option value="operaciones" <?php echo $role === 'operaciones' ? 'selected' : ''; ?>>Operaciones</option>
                        </select>
                    </div>

                    <div class="form-field admin-user-filter-status">
                        <select name="status" class="select" onchange="this.form.submit()">
                            <option value="">Todos los estados</option>
                            <option value="active" <?php echo $status === 'active' ? 'selected' : ''; ?>>Activo</option>
                            <option value="inactive" <?php echo $status === 'inactive' ? 'selected' : ''; ?>>Inactivo</option>
                        </select>
                    </div>

                    <button type="submit" class="btn btn-primary admin-user-filter-submit">
                        <i data-lucide="search"></i>
                        <span>Buscar</span>
                    </button>

                    <?php if ($q !== '' || $role !== '' || $status !== ''): ?>
                        <a href="/modules/admin/users.php" class="btn btn-outline admin-user-filter-clear">
                            <i data-lucide="x"></i>
                            <span>Limpiar</span>
                        </a>
                    <?php endif; ?>
                </form>
            </div>
        </section>

        <section class="card card-table-container">
            <div class="table-wrap table-container-scroll">
                <table class="table table-mobile-compact users-table">
                    <thead>
                        <tr>
                            <th class="col-user">Usuario</th>
                            <th class="col-email mobile-hidden">Email</th>
                            <th class="col-role">Rol</th>
                            <th class="col-status mobile-hidden">Estado</th>
                            <th class="col-last-login mobile-hidden">Último acceso</th>
                            <th class="col-action text-left">Acción</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $user): ?>
                            <?php $initial = mb_substr($user['name'] ?: $user['email'], 0, 1, 'UTF-8'); ?>
                            <tr>
                                <td>
                                    <div class="customer-cell">
                                        <span class="customer-avatar-mini"><?php echo safe_text(strtoupper($initial)); ?></span>
                                        <span class="customer-cell-text">
                                            <strong><?php echo safe_text($user['name'] ?: 'Pendiente'); ?></strong>
                                            <small class="mobile-only"><?php echo safe_text($user['email']); ?></small>
                                        </span>
                                    </div>
                                </td>
                                <td class="col-email mobile-hidden"><?php echo safe_text($user['email']); ?></td>
                                <td class="col-role"><span class="badge"><?php echo safe_text(role_label($user['role'])); ?></span></td>
                                <td class="col-status mobile-hidden">
                                    <span class="badge <?php echo $user['status'] === 'active' ? 'badge-success' : 'badge-error'; ?>">
                                        <?php echo $user['status'] === 'active' ? 'Activo' : 'Inactivo'; ?>
                                    </span>
                                </td>
                                <td class="col-last-login mobile-hidden text-muted text-sm"><?php echo $user['last_login'] ?: '—'; ?></td>
                                <td class="col-action text-left">
                                    <?php if (user_can('admin.users.edit')): ?>
                                        <button class="btn btn-sm btn-outline" onclick="openUserModal(<?php echo $user['id']; ?>)">
                                            <i data-lucide="edit-3"></i>
                                        </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </section>
    </section>

    <div id="userModal" class="product-modal-backdrop">
        <div class="product-modal-box">
            <div class="product-modal-header">
                <div>
                    <h2 id="modal_title" class="h3">Nuevo Usuario</h2>
                    <span id="modal_subtitle" class="text-secondary text-sm">Autoriza un email para que ingrese al sistema</span>
                </div>
                <button type="button" class="btn btn-outline action-square-btn" onclick="closeUserModal()" title="Cerrar"><i data-lucide="x"></i></button>
            </div>

            <div class="product-modal-body">
                <form id="userForm" action="/modules/admin/user_store.php" method="POST" data-no-spa="true" style="margin:0;">
                    <input type="hidden" name="id" id="modal_user_id">
                    <div class="form-grid">
                        <div class="form-field is-required">
                            <label class="label">Email de Acceso</label>
                            <input class="input" type="email" name="email" id="modal_email" placeholder="usuario@correo.com" required>
                        </div>
                        
                        <div class="form-field">
                            <label class="label">Nombre (Opcional)</label>
                            <input class="input" type="text" name="name" id="modal_name" placeholder="Nombre completo">
                        </div>

                        <div class="form-field">
                            <label class="label">Contraseña de acceso</label>
                            <input class="input" type="text" name="password" id="modal_password" placeholder="Escribe una contraseña (déjalo en blanco si usará Google)">
                        </div>
                        
                        <div class="form-grid-2 grid gap-4" style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                            <div class="form-field is-required">
                                <label class="label">Rol en el Sistema</label>
                                <select class="select" name="role" id="modal_role" required>
                                    <option value="comercial">Comercial</option>
                                    <option value="administracion">Administración</option>
                                    <option value="operaciones">Operaciones</option>
                                    <option value="admin">Admin (Total)</option>
                                </select>
                            </div>
                            <div class="form-field is-required">
                                <label class="label">Estado</label>
                                <select class="select" name="status" id="modal_status" required>
                                    <option value="active">Activo</option>
                                    <option value="inactive">Inactivo</option>
                                </select>
                            </div>
                        </div>

                        <div style="grid-column: 1 / -1; margin-top: var(--space-4);">
                            <label class="label">Permisos de Acceso a Módulos</label>
                            <span class="text-sm text-secondary block mb-3">Selecciona a qué partes del sistema tendrá acceso este usuario. (Los Administradores tienen acceso total por defecto).</span>
                            
                            <div class="user-permissions-grid">
                                <?php 
                                $all_modules = get_system_modules(true);
                                $grouped_modules = [];
                                foreach ($all_modules as $key => $mod) {
                                    $grouped_modules[$mod['section']][$key] = $mod;
                                }
                                
                                foreach ($grouped_modules as $section_name => $mods): 
                                ?>
                                    <div>
                                        <strong style="display: block; margin-bottom: 12px; font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px;">
                                            <?php echo safe_text($section_name); ?>
                                        </strong>
                                        
                                        <?php foreach ($mods as $key => $mod): ?>
                                            <label style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px; cursor: pointer;">
                                                <input type="checkbox" name="permissions[]" value="module.<?php echo $key; ?>" class="perm-checkbox" style="width: 16px; height: 16px;">
                                                <span style="font-size: 0.9rem;"><?php echo safe_text($mod['title']); ?></span>
                                            </label>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </form>
            </div>

            <div class="product-modal-footer" style="justify-content: space-between; align-items: center;">
                <form id="form-delete-user" action="/modules/admin/user_delete.php" method="POST" data-no-spa="true" style="margin:0; display: none;">
                    <input type="hidden" name="id" id="delete_user_id" value="">
                    <button type="submit" class="btn btn-outline btn-delete-mobile" style="color: var(--color-error); border-color: var(--color-error);" title="Eliminar Usuario" onclick="return confirm('¿Estás seguro de eliminar a este usuario de manera permanente?');">
                        <i data-lucide="trash-2"></i><span class="mobile-hidden">Eliminar</span>
                    </button>
                </form>

                <div class="modal-footer-actions-right">
                    <button type="button" class="btn btn-outline" onclick="closeUserModal()">Cancelar</button>
                    <button type="submit" form="userForm" class="btn btn-primary"><i data-lucide="save"></i><span id="modal_btn_text">Guardar Usuario</span></button>
                </div>
            </div>
        </div>
    </div>

    <script>
    (function () {
        function getUserModal() { return document.getElementById('userModal'); }
        function getUserForm() { return document.getElementById('userForm'); }
        function setValue(id, value) { var el = document.getElementById(id); if (el) el.value = value == null ? '' : value; }
        function setText(id, value) { var el = document.getElementById(id); if (el) el.innerText = value == null ? '' : value; }

        window.openUserModal = function (id) {
            var userModal = getUserModal();
            var uForm = getUserForm();
            if (!userModal || !uForm) return;

            uForm.reset();
            setValue('modal_user_id', id || '');
            var email = document.getElementById('modal_email');
            if (email) email.disabled = false;

            document.querySelectorAll('#userModal .perm-checkbox').forEach(function (cb) { cb.checked = false; });

            var isMobile = window.innerWidth <= 760;
            var deleteForm = document.getElementById('form-delete-user');
            var deleteInput = document.getElementById('delete_user_id');

            if (id) {
                setText('modal_title', 'Editar Usuario');
                setText('modal_subtitle', 'Modifica los permisos de acceso');
                uForm.action = '/modules/admin/user_update.php';
                setText('modal_btn_text', isMobile ? 'Actualizar' : 'Actualizar Usuario');
                if (deleteForm) deleteForm.style.display = 'block';
                if (deleteInput) deleteInput.value = id;

                fetch('/modules/admin/user_get.php?id=' + encodeURIComponent(id), { credentials: 'same-origin' })
                    .then(function (res) { return res.json(); })
                    .then(function (data) {
                        setValue('modal_email', data.email || '');
                        var emailInput = document.getElementById('modal_email');
                        if (emailInput) emailInput.disabled = true;
                        setValue('modal_name', data.name || '');
                        setValue('modal_role', data.role || 'comercial');
                        setValue('modal_status', data.status || 'active');

                        if (data.module_permissions) {
                            var perms = [];
                            try { perms = JSON.parse(data.module_permissions) || []; } catch (err) { perms = []; }
                            perms.forEach(function (permissionValue) {
                                document.querySelectorAll('#userModal input[name="permissions[]"]').forEach(function (checkbox) {
                                    if (checkbox.value === permissionValue) checkbox.checked = true;
                                });
                            });
                        }
                    })
                    .catch(function () {
                        alert('No fue posible cargar el usuario.');
                    });
            } else {
                setText('modal_title', 'Nuevo Usuario');
                setText('modal_subtitle', 'Autoriza un email para que ingrese al sistema');
                uForm.action = '/modules/admin/user_store.php';
                setText('modal_btn_text', isMobile ? 'Guardar' : 'Guardar Usuario');
                if (deleteForm) deleteForm.style.display = 'none';
                if (deleteInput) deleteInput.value = '';
            }

            userModal.style.display = 'flex';
            setTimeout(function () { userModal.classList.add('show'); }, 10);
        };

        window.closeUserModal = function () {
            var userModal = getUserModal();
            if (!userModal) return;
            userModal.classList.remove('show');
            setTimeout(function () { userModal.style.display = 'none'; }, 200);
        };

        if (!window.__ICY_USERS_MODAL_CLICK_BOUND) {
            document.addEventListener('click', function (e) {
                var userModal = getUserModal();
                if (userModal && e.target === userModal) window.closeUserModal();
            });
            window.__ICY_USERS_MODAL_CLICK_BOUND = true;
        }
    })();
    </script>
</main>

<?php require_once '../../layouts/footer.php'; ?>