<?php
// Contenido del módulo Usuarios para el layout corporativo
?>
<!-- Encabezado superior removido según solicitud: título y botón Crear Usuario -->

<div class="premium-content-area">
    <div class="users-container">
    <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="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                    <circle cx="12" cy="7" r="4"/>
                </svg>
                Usuarios
            </h1>
            <p class="page-subtitle">Gestiona cuentas, roles y escritorios de forma centralizada.</p>
        </div>
        <div class="header-actions">
            <?php if (!empty($canCreateUser)): ?>
                <button class="btn-primary btn-size-md" onclick="openUserWizard()">
                    <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 Usuario
                </button>
            <?php endif; ?>
        </div>
    </div>

    <!-- Widgets de métricas -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon bg-blue-500">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                    <circle cx="12" cy="7" r="4"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo (int)$users_active_count; ?></div>
                <div class="stat-label">Usuarios Activos</div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon bg-yellow-500">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="12" cy="12" r="9"/>
                    <path d="M9 12h6M12 9v6"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo (int)$roles_count; ?></div>
                <div class="stat-label">Roles Disponibles</div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon bg-green-500">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <rect x="3" y="7" width="18" height="11" rx="2"/>
                    <path d="M7 7V4h10v3"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo (int)$desks_active_count; ?></div>
                <div class="stat-label">Escritorios Activos</div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon bg-teal-500">
                <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-4H8a4 4 0 0 0-4 4v2"/>
                    <circle cx="9" cy="7" r="4"/>
                    <path d="M22 2l-5 10-5-5-5 10"/>
                </svg>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?php echo (int)$leads_assigned_count; ?></div>
                <div class="stat-label">Leads Asignados</div>
            </div>
        </div>
    </div>
    <?php if (empty($users)): ?>
        <div class="alert alert-info">
            No hay usuarios registrados en el sistema.
        </div>
    <?php else: ?>
    <div class="card">
        <div class="card-header d-flex justify-between align-center">
            <h2 class="card-title">Listado de Usuarios</h2>
        </div>
        <div class="card-body">
            <table class="table data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Usuario</th>
                        <th>Nombre Completo</th>
                        <th>Email</th>
                        <th>Roles</th>
                        <th>Desk</th>
                        <th>Extensión Voiso</th>
                        <th>Leads Asignados</th>
                        <th>Estado</th>
                        <th>Último Login</th>
                        <th>Acciones</th>
                    </tr>
                </thead>
                <tbody id="usersTableBody">
                    <?php foreach ($users as $user): ?>
                        <tr id="user-row-<?php echo (int)$user['id']; ?>" data-user-id="<?php echo (int)$user['id']; ?>" data-username="<?php echo htmlspecialchars($user['username'], ENT_QUOTES); ?>">
                            <td><?php echo $user['id']; ?></td>
                            <td>
                                <strong><?php echo htmlspecialchars($user['username']); ?></strong>
                            </td>
                            <td>
                                <?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?>
                            </td>
                            <td><?php echo htmlspecialchars($user['email']); ?></td>
                            <td>
                                <?php if ($user['roles']): ?>
                                    <small class="user-roles-text"><?php echo htmlspecialchars($user['roles']); ?></small>
                                <?php else: ?>
                                    <small class="text-muted user-roles-text">Sin roles</small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="user-desk-name"><?php echo htmlspecialchars($user['desk_name'] ?? ''); ?></span>
                            </td>
                            <td>
                                <?php if (!empty($isVoisoConfigured)): ?>
                                    <span class="user-voiso-ext"><?php echo htmlspecialchars($user['voiso_extension'] ?? ''); ?></span>
                                <?php else: ?>
                                    <span class="user-voiso-ext">—</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-center">
                                <span class="user-leads-count"><?php echo number_format($user['total_leads']); ?></span>
                            </td>
                            <td>
                                <span class="badge user-status-badge badge-<?php echo $user['status']; ?>">
                                    <?php echo ucfirst($user['status']); ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($user['last_login']): ?>
                                    <span class="user-last-login"><?php echo date('d/m/Y H:i', strtotime($user['last_login'])); ?></span>
                                <?php else: ?>
                                    <small class="text-muted user-last-login">Nunca</small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="?module=users&action=view&id=<?php echo $user['id']; ?>" 
                                   class="btn-secondary btn-size-md">Ver</a>
                                <?php if (!empty($canEditUser)): ?>
                                    <button type="button" class="btn-secondary btn-size-md" onclick="openEditUserModal(<?php echo (int)$user['id']; ?>)">Editar</button>
                                <?php endif; ?>
                                <?php if (!empty($canDeleteUser) && $user['id'] != $_SESSION['user_id']): ?>
                                    <button type="button" class="btn-danger btn-size-md" onclick="openDeleteUserModal(<?php echo (int)$user['id']; ?>, '<?php echo htmlspecialchars($user['username']); ?>')">Eliminar</button>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
    </div><!-- /.users-container -->
</div>

<style>
    /* Ajuste para eliminar espacio excesivo entre widgets y la tabla */
    .premium-content-area { min-height: auto; padding-bottom: 0; }
    .stats-grid { margin-bottom: 1rem; }
    .badge { padding: 0.25rem 0.5rem; border-radius: 3px; font-size: 0.8rem; font-weight: 500; }
    .badge-active { background: #28a745; color: white; }
    .badge-inactive { background: #6c757d; color: white; }
    .badge-suspended { background: #dc3545; color: white; }
    .text-muted { color: #6c757d; }
    .page-header { display:flex; justify-content:space-between; align-items:flex-end; margin-bottom:1rem; }
    .page-title { margin:0; }
    .page-subtitle { margin:0; color:#6c757d; }
    .page-actions { display:flex; gap:.5rem; }
    .card-body { overflow-x: auto; }
    .table th, .table td { white-space: nowrap; }
    @media (max-width: 768px) { .page-header { align-items:flex-start; } }
    .input-error { color: #dc3545; font-size: .8rem; margin-top: .25rem; }
    .form-floating input.invalid, .form-control.invalid { border-color: #dc3545; box-shadow: 0 0 0 0.2rem rgba(220,53,69,.15); }

    /* Wizard Stepper (circulitos) con iconos y colores del CRM */
    .wizard-stepper { display:flex; justify-content:space-between; align-items:center; gap:1rem; margin-bottom:1rem; }
    .wizard-step-item { display:flex; align-items:center; flex:1; position:relative; gap:.25rem; }
    .wizard-step-item .step-index { width:34px; height:34px; min-width:34px; border-radius:50%; border:2px solid var(--border-medium); background:#fff; display:flex; align-items:center; justify-content:center; font-weight:600; color:var(--secondary-gray); position:relative; z-index:1; }
    .wizard-step-item .step-title { margin-left:.5rem; font-weight:600; color:var(--secondary-gray); position:relative; z-index:1; }
    .wizard-step-item .step-icon { margin-left:.35rem; display:inline-flex; align-items:center; color:var(--secondary-gray); position:relative; z-index:1; }
    .wizard-step-item .step-icon svg { width:18px; height:18px; fill:currentColor; }
    .wizard-step-item.active .step-index { border-color: var(--primary-blue); color: var(--primary-blue); background:#e7f1ff; }
    .wizard-step-item.active .step-title, .wizard-step-item.active .step-icon { color: var(--primary-blue); }
    .wizard-step-item.completed .step-index { border-color: var(--primary-blue); background: var(--primary-blue); color:#fff; font-size:0; }
    .wizard-step-item.completed .step-index::after { content:'✓'; color:#fff; font-size:16px; font-weight:700; }
    .wizard-step-item.completed .step-title, .wizard-step-item.completed .step-icon { color: var(--primary-blue-dark); }
    .wizard-step-item::after { content:''; position:absolute; height:2px; background: var(--border-medium); top:50%; left:46px; width:calc(100% - 60px); transform:translateY(14px); z-index:0; pointer-events:none; }
    .wizard-step-item:last-child::after { display:none; }
    .wizard-step-item.completed::after { background: var(--primary-blue-light); }
    @media (max-width: 640px) {
        .wizard-stepper { flex-wrap:wrap; }
        .wizard-step-item { flex:0 0 calc(50% - .5rem); margin-bottom:.5rem; }
        .wizard-step-item::after { display:none; }
    }
</style>

<!-- Modal: Asistente Crear Usuario -->
<div id="userWizardBackdrop" class="modal-backdrop" style="display:none;">
    <div class="modal modal-premium" role="dialog" aria-modal="true" aria-labelledby="userWizardTitle" style="max-width: 800px; width: 95%;">
        <div class="modal-header">
            <h3 id="userWizardTitle">Asistente: Crear Usuario</h3>
            <button class="btn-ghost btn-size-md" onclick="closeUserWizard()">✕</button>
        </div>
        <div class="modal-body">
            <div id="userWizardSteps" class="wizard-stepper">
                <div class="wizard-step-item" data-step="1">
                    <span class="step-index">1</span>
                    <span class="step-title">Información</span>
                    <span class="step-icon" aria-hidden="true">
                        <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path d="M12 2a10 10 0 100 20 10 10 0 000-20zm0 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>
                        </svg>
                    </span>
                </div>
                <div class="wizard-step-item" data-step="2">
                    <span class="step-index">2</span>
                    <span class="step-title">Desk</span>
                    <span class="step-icon" aria-hidden="true">
                        <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path d="M4 7h16v11H4V7zm3-3h10v3H7V4z"/>
                        </svg>
                    </span>
                </div>
                <div class="wizard-step-item" data-step="3">
                    <span class="step-index">3</span>
                    <span class="step-title">Roles</span>
                    <span class="step-icon" aria-hidden="true">
                        <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path d="M12 2l8 4v6c0 5-3.5 9-8 10-4.5-1-8-5-8-10V6l8-4z"/>
                        </svg>
                    </span>
                </div>
                <div class="wizard-step-item" data-step="4">
                    <span class="step-index">4</span>
                    <span class="step-title">Confirmación</span>
                    <span class="step-icon" aria-hidden="true">
                        <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path d="M12 2a10 10 0 100 20 10 10 0 000-20zm-1 14l-4-4 1.4-1.4L11 12.2l4.6-4.6L17 9l-6 7z"/>
                        </svg>
                    </span>
                </div>
            </div>

            <!-- Paso 1: Información -->
            <div id="userWizardStep1">
                <div class="form-grid">
                    <div class="form-floating">
                        <input type="text" id="uw_username" placeholder=" " required>
                        <label for="uw_username">Usuario</label>
                        <small id="uw_username_error" class="input-error"></small>
                    </div>
                    <div class="form-floating">
                        <input type="email" id="uw_email" placeholder=" " required>
                        <label for="uw_email">Email</label>
                        <small id="uw_email_error" class="input-error"></small>
                    </div>
                    <div class="form-floating">
                        <input type="text" id="uw_first_name" placeholder=" " required>
                        <label for="uw_first_name">Nombre</label>
                        <small id="uw_first_name_error" class="input-error"></small>
                    </div>
                    <div class="form-floating">
                        <input type="text" id="uw_last_name" placeholder=" " required>
                        <label for="uw_last_name">Apellido</label>
                        <small id="uw_last_name_error" class="input-error"></small>
                    </div>
                    <div class="form-floating">
                        <input type="password" id="uw_password" placeholder=" " required>
                        <label for="uw_password">Contraseña</label>
                        <small id="uw_password_error" class="input-error"></small>
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="uw_status">Estado</label>
                        <select id="uw_status" class="form-control">
                            <option value="active">Activo</option>
                            <option value="inactive">Inactivo</option>
                            <option value="suspended">Suspendido</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- Paso 2: Desk -->
            <div id="userWizardStep2Desk" style="display:none;">
                <div class="form-group">
                    <label class="form-label" for="uw_desk_id">Asignar Desk</label>
                    <select id="uw_desk_id" class="form-control">
                        <option value="">Selecciona un desk</option>
                        <?php if (!empty($desks)): ?>
                            <?php foreach ($desks as $desk): ?>
                                <option value="<?php echo (int)$desk['id']; ?>"><?php echo htmlspecialchars($desk['name']); ?></option>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <option value="">No hay desks activos</option>
                        <?php endif; ?>
                    </select>
                    <small id="uw_desk_error" class="input-error"></small>
                </div>
                <?php if (!empty($isVoisoConfigured)): ?>
                <div class="form-floating">
                    <input type="text" id="uw_voiso_extension" placeholder=" " inputmode="numeric" pattern="[0-9]*" maxlength="10">
                    <label for="uw_voiso_extension">Extensión Voiso (opcional)</label>
                </div>
                <?php endif; ?>
            </div>

            <!-- Paso 3: Roles -->
            <div id="userWizardStep3Roles" style="display:none;">
                <div class="form-group">
                    <label class="form-label">Asignar Roles</label>
                    <div class="checkbox-grid" style="max-height:300px; overflow:auto; border:1px solid var(--border-light); padding: .75rem; border-radius:8px;">
                        <?php if (!empty($roles)): ?>
                            <?php foreach ($roles as $role): ?>
                                <label style="display:flex; align-items:center; gap:.5rem; padding:.35rem 0;">
                                    <input type="checkbox" name="uw_roles" value="<?php echo (int)$role['id']; ?>">
                                    <span><?php echo htmlspecialchars($role['display_name']); ?></span>
                                </label>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="alert alert-info">No hay roles creados. Crea roles primero.</div>
                        <?php endif; ?>
                    </div>
                    <small id="uw_roles_error" class="input-error"></small>
                </div>
            </div>

            <!-- Paso 4: Confirmación -->
            <div id="userWizardStep4" style="display:none;">
                <div class="summary-grid">
                    <div>
                        <strong>Usuario:</strong> <span id="uw_summary_username"></span>
                    </div>
                    <div>
                        <strong>Email:</strong> <span id="uw_summary_email"></span>
                    </div>
                    <div>
                        <strong>Nombre:</strong> <span id="uw_summary_name"></span>
                    </div>
                    <div>
                        <strong>Desk:</strong> <span id="uw_summary_desk"></span>
                    </div>
                    <div>
                        <strong>Estado:</strong> <span id="uw_summary_status"></span>
                    </div>
                    <div>
                        <strong>Roles:</strong> <span id="uw_summary_roles"></span>
                    </div>
                    <?php if (!empty($isVoisoConfigured)): ?>
                    <div>
                        <strong>Extensión Voiso:</strong> <span id="uw_summary_voiso_extension"></span>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button id="uw_back_btn" class="btn-secondary btn-size-md" onclick="uwPrev()">Atrás</button>
            <button id="uw_next_btn" class="btn-primary btn-size-md" onclick="uwNext()">Siguiente</button>
            <button id="uw_create_btn" class="btn-primary btn-size-md" style="display:none;" onclick="submitCreateUser()">Crear Usuario</button>
        </div>
    </div>
</div>

<!-- Modal: Editar Usuario -->
<div id="editUserBackdrop" class="modal-backdrop" style="display:none;">
    <div class="modal modal-premium" role="dialog" aria-modal="true" style="max-width: 760px; width:95%;">
        <div class="modal-header">
            <h3>Editar Usuario</h3>
            <button class="btn-ghost btn-size-md" onclick="closeEditUserModal()">✕</button>
        </div>
        <div class="modal-body">
            <form id="editUserForm">
                <input type="hidden" id="eu_user_id">
                <div class="form-grid">
                    <div class="form-floating">
                        <input type="text" id="eu_username" placeholder=" " disabled>
                        <label for="eu_username">Usuario</label>
                    </div>
                    <div class="form-floating">
                        <input type="email" id="eu_email" placeholder=" " required>
                        <label for="eu_email">Email</label>
                    </div>
                    <div class="form-floating">
                        <input type="text" id="eu_first_name" placeholder=" " required>
                        <label for="eu_first_name">Nombre</label>
                    </div>
                    <div class="form-floating">
                        <input type="text" id="eu_last_name" placeholder=" " required>
                        <label for="eu_last_name">Apellido</label>
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="eu_status">Estado</label>
                        <select id="eu_status" class="form-control">
                            <option value="active">Activo</option>
                            <option value="inactive">Inactivo</option>
                            <option value="suspended">Suspendido</option>
                        </select>
                    </div>
                    <div class="form-floating">
                        <input type="password" id="eu_password" placeholder=" ">
                        <label for="eu_password">Nueva Contraseña (opcional)</label>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Roles</label>
                    <div id="eu_roles_container" style="max-height:240px; overflow:auto; border:1px solid var(--border-light); padding:.75rem; border-radius:8px;">
                        <?php if (!empty($roles)): ?>
                            <?php foreach ($roles as $role): ?>
                                <label style="display:flex; align-items:center; gap:.5rem; padding:.3rem 0;">
                                    <input type="checkbox" name="eu_roles" value="<?php echo (int)$role['id']; ?>">
                                    <span><?php echo htmlspecialchars($role['display_name']); ?></span>
                                </label>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="alert alert-info">No hay roles creados.</div>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label" for="eu_desk_id">Desk</label>
                    <select id="eu_desk_id" class="form-control">
                        <option value="">Selecciona un desk</option>
                        <?php if (!empty($desks)): ?>
                            <?php foreach ($desks as $desk): ?>
                                <option value="<?php echo (int)$desk['id']; ?>"><?php echo htmlspecialchars($desk['name']); ?></option>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <option value="">No hay desks activos</option>
                        <?php endif; ?>
                    </select>
                </div>
                <?php if (!empty($isVoisoConfigured)): ?>
                <div class="form-floating">
                    <input type="text" id="eu_voiso_extension" placeholder=" " inputmode="numeric" pattern="[0-9]*" maxlength="10">
                    <label for="eu_voiso_extension">Extensión Voiso (opcional)</label>
                </div>
                <?php endif; ?>
            </form>
        </div>
        <div class="modal-footer">
            <button class="btn-secondary btn-size-md" onclick="closeEditUserModal()">Cancelar</button>
            <button class="btn-primary btn-size-md" onclick="submitEditUser()">Guardar</button>
        </div>
    </div>
</div>

<!-- Modal: Eliminar Usuario -->
<div id="deleteUserBackdrop" class="modal-backdrop" style="display:none;">
    <div class="modal modal-premium" role="dialog" aria-modal="true" style="max-width:520px; width:95%;">
        <div class="modal-header">
            <h3>Eliminar Usuario</h3>
            <button class="btn-ghost btn-size-md" onclick="closeDeleteUserModal()">✕</button>
        </div>
        <div class="modal-body">
            <p id="du_message">¿Confirma eliminar el usuario?</p>
        </div>
        <div class="modal-footer">
            <button class="btn-secondary btn-size-md" onclick="closeDeleteUserModal()">Cancelar</button>
            <button class="btn-danger btn-size-md" id="du_confirm_btn">Eliminar</button>
        </div>
    </div>
</div>

<script>
// Permisos UI embebidos
const uiPerms = {
    create: <?php echo !empty($canCreateUser) ? 'true' : 'false'; ?>,
    update: <?php echo !empty($canEditUser) ? 'true' : 'false'; ?>,
    delete: <?php echo !empty($canDeleteUser) ? 'true' : 'false'; ?>
};

// ====== Crear Usuario Wizard ======
let uwStep = 1;
function openUserWizard() {
    if (!uiPerms.create) { window.ProfixCRM.showNotification('No tienes permiso para crear usuarios', 'error'); return; }
    const b = document.getElementById('userWizardBackdrop');
    if (b) { b.style.display = 'flex'; uwStep = 1; updateUWUI(); validateStep1(); }
}
function closeUserWizard() {
    const b = document.getElementById('userWizardBackdrop');
    if (b) { b.style.display = 'none'; }
}
function updateUWUI() {
    document.getElementById('userWizardStep1').style.display = (uwStep === 1) ? 'block' : 'none';
    document.getElementById('userWizardStep2Desk').style.display = (uwStep === 2) ? 'block' : 'none';
    document.getElementById('userWizardStep3Roles').style.display = (uwStep === 3) ? 'block' : 'none';
    document.getElementById('userWizardStep4').style.display = (uwStep === 4) ? 'block' : 'none';
    document.getElementById('uw_back_btn').disabled = (uwStep === 1);
    const nextBtn = document.getElementById('uw_next_btn');
    nextBtn.style.display = (uwStep < 4) ? 'inline-block' : 'none';
    if (uwStep === 1) nextBtn.disabled = !validateStep1(false);
    else if (uwStep === 2) nextBtn.disabled = !validateDeskStep(false);
    else if (uwStep === 3) nextBtn.disabled = !validateRolesStep(false);
    else nextBtn.disabled = false;
    document.getElementById('uw_create_btn').style.display = (uwStep === 4) ? 'inline-block' : 'none';
    const stepper = document.getElementById('userWizardSteps');
    if (stepper) {
        stepper.querySelectorAll('.wizard-step-item').forEach(i => {
            const s = parseInt(i.getAttribute('data-step'), 10);
            i.classList.toggle('active', s === uwStep);
            i.classList.toggle('completed', s < uwStep);
        });
    }
}
function uwNext() {
    if (uwStep === 1 && !validateStep1()) { window.ProfixCRM.showNotification('Corrige los errores antes de continuar', 'error'); return; }
    if (uwStep === 2 && !validateDeskStep()) { window.ProfixCRM.showNotification('Selecciona un desk', 'error'); return; }
    if (uwStep === 3 && !validateRolesStep()) { window.ProfixCRM.showNotification('Selecciona al menos un rol', 'error'); return; }
    uwStep = Math.min(uwStep + 1, 4);
    if (uwStep === 4) {
        document.getElementById('uw_summary_username').textContent = document.getElementById('uw_username').value.trim();
        document.getElementById('uw_summary_email').textContent = document.getElementById('uw_email').value.trim();
        document.getElementById('uw_summary_name').textContent = document.getElementById('uw_first_name').value.trim() + ' ' + document.getElementById('uw_last_name').value.trim();
        const deskSel = document.getElementById('uw_desk_id');
        const deskName = deskSel && deskSel.value ? deskSel.options[deskSel.selectedIndex].textContent : '—';
        document.getElementById('uw_summary_desk').textContent = deskName;
        document.getElementById('uw_summary_status').textContent = document.getElementById('uw_status').value;
        const roles = Array.from(document.querySelectorAll('input[name="uw_roles"]:checked')).map(i => i.nextElementSibling.textContent);
        document.getElementById('uw_summary_roles').textContent = roles.join(', ') || 'Sin roles';
        const sumExt = document.getElementById('uw_summary_voiso_extension');
        if (sumExt) {
            const extInput = document.getElementById('uw_voiso_extension');
            const val = extInput && extInput.value ? extInput.value.trim() : '';
            sumExt.textContent = val || '—';
        }
    }
    updateUWUI();
}
function uwPrev() { uwStep = Math.max(uwStep - 1, 1); updateUWUI(); }

function isValidEmail(v) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);
}
function isStrongPassword(v) {
    return typeof v === 'string' && v.length >= 8 && /[A-Za-z]/.test(v) && /\d/.test(v);
}
function setError(id, msg, invalidInputId) {
    const el = document.getElementById(id);
    if (!el) return;
    el.textContent = msg || '';
    const input = invalidInputId ? document.getElementById(invalidInputId) : null;
    if (input) input.classList.toggle('invalid', !!msg);
}
function validateStep1(showMessages = true) {
    const u = document.getElementById('uw_username').value.trim();
    const e = document.getElementById('uw_email').value.trim();
    const f = document.getElementById('uw_first_name').value.trim();
    const l = document.getElementById('uw_last_name').value.trim();
    const p = document.getElementById('uw_password').value;
    let ok = true;
    if (showMessages) setError('uw_username_error', '', 'uw_username');
    if (showMessages) setError('uw_email_error', '', 'uw_email');
    if (showMessages) setError('uw_first_name_error', '', 'uw_first_name');
    if (showMessages) setError('uw_last_name_error', '', 'uw_last_name');
    if (showMessages) setError('uw_password_error', '', 'uw_password');
    if (!u) { ok = false; if (showMessages) setError('uw_username_error', 'Usuario es requerido', 'uw_username'); }
    if (!e || !isValidEmail(e)) { ok = false; if (showMessages) setError('uw_email_error', 'Email inválido', 'uw_email'); }
    if (!f) { ok = false; if (showMessages) setError('uw_first_name_error', 'Nombre es requerido', 'uw_first_name'); }
    if (!l) { ok = false; if (showMessages) setError('uw_last_name_error', 'Apellido es requerido', 'uw_last_name'); }
    if (!isStrongPassword(p)) { ok = false; if (showMessages) setError('uw_password_error', 'Contraseña débil: mínimo 8, letras y números', 'uw_password'); }
    return ok;
}
function validateDeskStep(showMessages = true) {
    const v = document.getElementById('uw_desk_id').value;
    let ok = !!v;
    if (showMessages) {
        const msg = ok ? '' : 'Debes seleccionar un desk';
        setError('uw_desk_error', msg);
        const sel = document.getElementById('uw_desk_id');
        if (sel) sel.classList.toggle('invalid', !ok);
    }
    return ok;
}
function validateRolesStep(showMessages = true) {
    const any = document.querySelector('input[name="uw_roles"]:checked') != null;
    if (showMessages) {
        const msg = any ? '' : 'Debes seleccionar al menos un rol';
        setError('uw_roles_error', msg);
    }
    return any;
}
const deskSel = document.getElementById('uw_desk_id');
if (deskSel) deskSel.addEventListener('change', () => { validateDeskStep(false); updateUWUI(); });
document.querySelectorAll('input[name="uw_roles"]').forEach(el => {
    el.addEventListener('change', () => { validateRolesStep(false); updateUWUI(); });
});
['uw_username','uw_email','uw_first_name','uw_last_name','uw_password'].forEach(id => {
    const el = document.getElementById(id);
    if (el) el.addEventListener('input', () => { validateStep1(false); updateUWUI(); });
});

async function submitCreateUser() {
  try {
    if (!validateStep1()) { window.ProfixCRM.showNotification('Revisa los campos del Paso 1', 'error'); return; }
    if (!validateDeskStep()) { window.ProfixCRM.showNotification('Selecciona un desk', 'error'); return; }
    if (!validateRolesStep()) { window.ProfixCRM.showNotification('Selecciona al menos un rol', 'error'); return; }

    const fd = new FormData();
    fd.append('username', document.getElementById('uw_username').value.trim());
    fd.append('email', document.getElementById('uw_email').value.trim());
    fd.append('first_name', document.getElementById('uw_first_name').value.trim());
    fd.append('last_name', document.getElementById('uw_last_name').value.trim());
    fd.append('password', document.getElementById('uw_password').value);
    fd.append('status', document.getElementById('uw_status').value);
    fd.append('desk_id', document.getElementById('uw_desk_id').value);
    document.querySelectorAll('input[name="uw_roles"]:checked').forEach(i => fd.append('roles[]', i.value));

    const uwExtEl = document.getElementById('uw_voiso_extension');
    if (uwExtEl && uwExtEl.value.trim()) {
      fd.append('voiso_extension', uwExtEl.value.trim());
    }

    const resp = await fetch('/modules/users/actions.php?action=create', { method: 'POST', body: fd });

    let data = null;
    let parsedJson = false;
    try {
      data = await resp.json();
      parsedJson = true;
    } catch (_) {
      parsedJson = false;
    }

    if (!resp.ok || (parsedJson && !data.success)) {
      const message = parsedJson ? (data.error || 'Error creando usuario') : `HTTP ${resp.status}: ${resp.statusText}`;
      let details = '';
      if (parsedJson) {
        try { details = JSON.stringify(data, null, 2); } catch (_) {}
      } else {
        try { details = (await resp.text()).slice(0, 1200); } catch (_) {}
      }
      showErrorModal(message, details);
      return;
    }

    window.ProfixCRM.showNotification('Usuario creado correctamente', 'success');

    // Actualizar tabla sin recargar
    try {
      const detailsResp = await fetch(`/modules/users/actions.php?action=get_details&user_id=${encodeURIComponent(data.user_id)}`);
      const detailsData = await detailsResp.json();
      if (detailsData.error) { throw new Error(detailsData.error); }
      const tbody = document.getElementById('usersTableBody');
      if (tbody) {
        const rowHtml = renderUserRow(detailsData.user, detailsData.roles, detailsData.desk, 0);
        const temp = document.createElement('tbody');
        temp.innerHTML = rowHtml;
        const newRow = temp.firstElementChild;
        tbody.insertAdjacentElement('afterbegin', newRow);
      }
    } catch (_) { /* no bloquear si falla la actualización UI */ }

    closeUserWizard();
  } catch (err) {
    showErrorModal(err.message || 'Error inesperado');
  }
}

// ====== Editar Usuario ======
function openEditUserModal(userId) {
    if (!uiPerms.update) { window.ProfixCRM.showNotification('No tienes permiso para editar usuarios', 'error'); return; }
    const b = document.getElementById('editUserBackdrop');
    if (b) { b.style.display = 'flex'; loadEditUser(userId); }
}
function closeEditUserModal() {
    const b = document.getElementById('editUserBackdrop');
    if (b) { b.style.display = 'none'; }
}
async function loadEditUser(userId) {
    try {
        const resp = await fetch(`/modules/users/actions.php?action=get_details&user_id=${encodeURIComponent(userId)}`);
        const data = await resp.json();
        if (data.error) throw new Error(data.error);
        const u = data.user;
        document.getElementById('eu_user_id').value = u.id;
        document.getElementById('eu_username').value = u.username;
        document.getElementById('eu_email').value = u.email;
        document.getElementById('eu_first_name').value = u.first_name;
        document.getElementById('eu_last_name').value = u.last_name;
        document.getElementById('eu_status').value = u.status;
        // Desk
        if (data.desk && data.desk.id) {
            const sel = document.getElementById('eu_desk_id');
            if (sel) sel.value = String(data.desk.id);
        } else {
            const sel = document.getElementById('eu_desk_id');
            if (sel) sel.value = '';
        }
        const euExt = document.getElementById('eu_voiso_extension');
        if (euExt) {
            euExt.value = (u.voiso_extension || '').toString();
        }
        // Roles
        const selected = (data.roles || []).map(r => String(r.id));
        document.querySelectorAll('#eu_roles_container input[name="eu_roles"]').forEach(chk => {
            chk.checked = selected.includes(chk.value);
        });
    } catch (err) {
        window.ProfixCRM.showNotification(err.message, 'error');
    }
}
async function submitEditUser() {
    try {
        const form = new FormData();
        form.append('user_id', document.getElementById('eu_user_id').value);
        form.append('email', document.getElementById('eu_email').value.trim());
        form.append('first_name', document.getElementById('eu_first_name').value.trim());
        form.append('last_name', document.getElementById('eu_last_name').value.trim());
        form.append('status', document.getElementById('eu_status').value);
        const pw = document.getElementById('eu_password').value;
        if (pw) form.append('password', pw);
        const deskSel = document.getElementById('eu_desk_id');
        if (deskSel && deskSel.value) form.append('desk_id', deskSel.value);
        const euExt = document.getElementById('eu_voiso_extension');
        if (euExt && euExt.value.trim()) {
            form.append('voiso_extension', euExt.value.trim());
        }
        document.querySelectorAll('#eu_roles_container input[name="eu_roles"]:checked').forEach(i => form.append('roles[]', i.value));

        const resp = await fetch('/modules/users/actions.php?action=update', { method: 'POST', body: form });
        const data = await resp.json();
        if (!data.success) { throw new Error(data.error || 'Error actualizando usuario'); }
        window.ProfixCRM.showNotification('Usuario actualizado', 'success');
        const id = document.getElementById('eu_user_id').value;
        const detailResp = await fetch(`/modules/users/actions.php?action=get_details&user_id=${encodeURIComponent(id)}`);
        const detail = await detailResp.json();
        if (detail.error) throw new Error(detail.error);
        const row = document.getElementById(`user-row-${id}`);
        if (row) {
            const leadsText = row.querySelector('.user-leads-count')?.textContent || '0';
            const leadsCount = parseInt(leadsText.replace(/[^0-9]/g,''), 10) || 0;
            const newRow = htmlToRow(renderUserRow(detail.user, detail.roles, detail.desk, leadsCount));
            row.replaceWith(newRow);
        }
        closeEditUserModal();
    } catch (err) {
        window.ProfixCRM.showNotification(err.message, 'error');
    }
}

// ====== Eliminar Usuario ======
let duUserId = null;
function openDeleteUserModal(userId, username) {
    if (!uiPerms.delete) { window.ProfixCRM.showNotification('No tienes permiso para eliminar usuarios', 'error'); return; }
    duUserId = userId;
    const b = document.getElementById('deleteUserBackdrop');
    const msg = document.getElementById('du_message');
    if (msg) { msg.textContent = `¿Confirma eliminar el usuario "${username}"?`; }
    const btn = document.getElementById('du_confirm_btn');
    if (btn) {
        btn.onclick = submitDeleteUser;
    }
    if (b) { b.style.display = 'flex'; }
}
function closeDeleteUserModal() {
    const b = document.getElementById('deleteUserBackdrop');
    if (b) { b.style.display = 'none'; }
}
async function submitDeleteUser() {
    try {
        const form = new FormData();
        form.append('user_id', duUserId);
        const resp = await fetch('/modules/users/actions.php?action=delete', { method: 'POST', body: form });
        const data = await resp.json();
        if (!data.success) throw new Error(data.error || 'Error eliminando usuario');
        window.ProfixCRM.showNotification('Usuario eliminado', 'success');
        // Eliminar fila directamente
        const row = document.getElementById(`user-row-${duUserId}`);
        if (row) row.remove();
        closeDeleteUserModal();
    } catch (err) {
        window.ProfixCRM.showNotification(err.message, 'error');
    }
}
</script>
<script>
function statusBadgeClass(status) {
    return `badge-${status}`;
}
function formatDateYMDH(i) {
    // Espera formato 'YYYY-MM-DD HH:MM:SS' del backend; muestra 'd/m/Y H:i'
    if (!i) return 'Nunca';
    const d = new Date(i.replace(' ', 'T'));
    if (isNaN(d.getTime())) return 'Nunca';
    const pad = n => n.toString().padStart(2, '0');
    return `${pad(d.getDate())}/${pad(d.getMonth()+1)}/${d.getFullYear()} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
function rolesToString(roles) {
    if (!Array.isArray(roles) || roles.length === 0) return 'Sin roles';
    return roles.map(r => r.display_name).join(', ');
}
function renderUserRow(u, roles, desk, leadsCount) {
    const canEdit = uiPerms.update;
    const canDelete = uiPerms.delete && String(u.id) !== String(<?php echo (int)$_SESSION['user_id']; ?>);
    const rolesText = rolesToString(roles);
    const lastLoginText = u.last_login ? formatDateYMDH(u.last_login) : 'Nunca';
    const statusClass = statusBadgeClass(u.status);
    const usernameEsc = (u.username || '').replace(/"/g, '&quot;');
    const deskName = desk && desk.name ? desk.name : '—';
    const voisoExt = (typeof u.voiso_extension !== 'undefined' && u.voiso_extension !== null && String(u.voiso_extension).trim() !== '') ? String(u.voiso_extension) : '—';
    return `
    <tr id="user-row-${u.id}" data-user-id="${u.id}" data-username="${usernameEsc}">
        <td>${u.id}</td>
        <td><strong>${u.username}</strong></td>
        <td>${u.first_name} ${u.last_name}</td>
        <td>${u.email}</td>
        <td><small class="user-roles-text">${rolesText}</small></td>
        <td><span class="user-desk-name">${deskName}</span></td>
        <td><span class="user-voiso-ext">${voisoExt}</span></td>
        <td class="text-center"><span class="user-leads-count">${leadsCount}</span></td>
        <td><span class="badge user-status-badge ${statusClass}">${u.status.charAt(0).toUpperCase()+u.status.slice(1)}</span></td>
        <td><span class="user-last-login">${lastLoginText}</span></td>
        <td>
            <a href="?module=users&action=view&id=${u.id}" class="btn-secondary btn-size-md">Ver</a>
            ${canEdit ? `<button type="button" class="btn-secondary btn-size-md" onclick="openEditUserModal(${u.id})">Editar</button>` : ''}
            ${canDelete ? `<button type="button" class="btn-danger btn-size-md" onclick="openDeleteUserModal(${u.id}, '${usernameEsc}')">Eliminar</button>` : ''}
        </td>
    </tr>`;
}
function htmlToRow(html) {
    const temp = document.createElement('tbody');
    temp.innerHTML = html.trim();
    return temp.firstElementChild;
}
</script>
<!-- Modal: Errores -->
<div id="errorModalBackdrop" class="modal-backdrop" style="display:none;">
  <div class="modal modal-premium" role="dialog" aria-modal="true" style="max-width: 640px; width: 95%;">
    <div class="modal-header">
      <h3 class="modal-title">Se produjo un error</h3>
      <button class="btn-ghost btn-size-md" onclick="closeErrorModal()" aria-label="Cerrar">✕</button>
    </div>
    <div class="modal-body">
      <div id="err_modal_message" class="alert alert-danger" style="margin-bottom:12px;"></div>
      <pre id="err_modal_details" style="background:#f7f7f7;border:1px solid #ddd;border-radius:6px;padding:10px;white-space:pre-wrap;max-height:240px;overflow:auto;display:none;"></pre>
      <div id="err_modal_hint" class="alert alert-info" style="display:none; margin-top:12px;"></div>
    </div>
    <div class="modal-footer">
      <button class="btn-secondary btn-size-md" onclick="closeErrorModal()">Cerrar</button>
    </div>
  </div>
</div>
<script>
function showErrorModal(message, details = '') {
  const backdrop = document.getElementById('errorModalBackdrop');
  const msgEl = document.getElementById('err_modal_message');
  const detEl = document.getElementById('err_modal_details');
  const hintEl = document.getElementById('err_modal_hint');

  msgEl.textContent = message || 'Ocurrió un error.';

  if (details) {
    detEl.textContent = details;
    detEl.style.display = 'block';
  } else {
    detEl.textContent = '';
    detEl.style.display = 'none';
  }

  // Sugerencia específica si el error menciona Voiso
  const lower = (message || '').toLowerCase() + ' ' + (details || '').toLowerCase();
  if (lower.includes('voiso')) {
    hintEl.innerHTML = 'La extensión Voiso es opcional al crear. Si aparece este error:<br>- Deja el campo vacío y vuelve a intentar.<br>- Verifica que la columna <code>users.voiso_extension</code> exista en la base de datos.<br>- Si no usas la integración Voiso, desactívala en configuración o ignora el campo.';
    hintEl.style.display = 'block';
  } else {
    hintEl.style.display = 'none';
    hintEl.innerHTML = '';
  }

  backdrop.style.display = 'block';
}

function closeErrorModal() {
  const backdrop = document.getElementById('errorModalBackdrop');
  if (backdrop) backdrop.style.display = 'none';
}
</script>