<?php
/**
 * ASISMA CRM - Gestión de Usuarios
 */
$esAdmin = SessionHelper::isAdmin();
?>
<!-- Header -->
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8">
    <div>
        <h1 class="text-3xl font-extrabold text-white tracking-tight">Usuarios del Sistema</h1>
        <p class="text-slate-400 text-sm mt-1">Control de acceso, roles y permisos por módulo.</p>
    </div>
    <?php if ($esAdmin): ?>
    <button onclick="abrirModalCrear()"
            class="inline-flex items-center gap-2 px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-xl transition-colors shadow-lg shadow-blue-600/20">
        <i data-lucide="user-plus" class="w-4 h-4"></i>
        Nuevo Usuario
    </button>
    <?php endif; ?>
</div>

<!-- Tabla -->
<div class="bg-slate-900 border border-slate-800/80 rounded-2xl overflow-hidden shadow-xl">
    <div class="overflow-x-auto">
        <table class="w-full text-left text-sm border-collapse">
            <thead>
                <tr class="bg-slate-950 border-b border-slate-800 text-slate-400 uppercase text-xs tracking-wider">
                    <th class="px-6 py-4 font-semibold">Usuario</th>
                    <th class="px-6 py-4 font-semibold">Email</th>
                    <th class="px-6 py-4 font-semibold">Empresa / Franquicia</th>
                    <th class="px-6 py-4 font-semibold">Rol</th>
                    <th class="px-6 py-4 font-semibold">Último Acceso</th>
                    <th class="px-6 py-4 font-semibold">Estado</th>
                    <th class="px-6 py-4 font-semibold text-right">Acciones</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-800/60 text-slate-300">
                <?php if (empty($usuarios)): ?>
                    <tr>
                        <td colspan="7" class="px-6 py-14 text-center text-slate-500">
                            <i data-lucide="users" class="w-10 h-10 mx-auto mb-3 opacity-30"></i>
                            <p class="font-medium">No hay usuarios registrados.</p>
                            <?php if ($esAdmin): ?>
                            <button onclick="abrirModalCrear()" class="mt-3 text-blue-400 hover:text-blue-300 text-sm underline">Crear el primero</button>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($usuarios as $u): ?>
                    <?php $esSelf = ($u['id'] == SessionHelper::getUsuarioId()); ?>
                    <tr class="hover:bg-slate-800/30 transition-colors" id="fila-u-<?php echo $u['id']; ?>">
                        <td class="px-6 py-4">
                            <div class="flex items-center gap-2.5">
                                <div class="w-8 h-8 rounded-full bg-gradient-to-tr from-blue-600 to-indigo-500 flex items-center justify-center text-white font-bold text-xs shrink-0">
                                    <?php echo strtoupper(substr($u['nombre'], 0, 2)); ?>
                                </div>
                                <div>
                                    <div class="font-semibold text-slate-100"><?php echo htmlspecialchars($u['nombre']); ?></div>
                                    <?php if ($u['telefono']): ?>
                                    <div class="text-xs text-slate-500"><?php echo htmlspecialchars($u['telefono']); ?></div>
                                    <?php endif; ?>
                                </div>
                                <?php if ($esSelf): ?>
                                <span class="text-xs bg-blue-500/10 text-blue-400 border border-blue-500/20 px-1.5 py-0.5 rounded-md font-medium">Tú</span>
                                <?php endif; ?>
                            </div>
                        </td>
                        <td class="px-6 py-4 font-mono text-xs text-slate-400"><?php echo htmlspecialchars($u['email']); ?></td>
                        <td class="px-6 py-4 text-xs text-slate-400"><?php echo htmlspecialchars($u['empresa_nombre']); ?></td>
                        <td class="px-6 py-4">
                            <span class="inline-flex items-center rounded-md bg-slate-800 px-2 py-0.5 text-xs font-semibold text-slate-300 border border-slate-700 capitalize">
                                <?php $_roles = arr_roles(); echo htmlspecialchars(isset($_roles[$u['rol']]) ? $_roles[$u['rol']] : $u['rol']); ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 text-xs text-slate-500 font-mono">
                            <?php echo $u['ultimo_login'] ? date('d-m-Y H:i', strtotime($u['ultimo_login'])) : 'Nunca'; ?>
                        </td>
                        <td class="px-6 py-4">
                            <span id="badge-u-<?php echo $u['id']; ?>"
                                  class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold border
                                         <?php echo $u['activo'] ? 'bg-green-500/10 text-green-400 border-green-500/20' : 'bg-slate-500/10 text-slate-400 border-slate-500/20'; ?>">
                                <?php echo $u['activo'] ? 'Activo' : 'Inactivo'; ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 text-right">
                            <div class="flex items-center justify-end gap-1.5">
                                <button onclick="abrirModalEditar(<?php echo $u['id']; ?>)"
                                        class="p-1.5 rounded-lg text-slate-400 hover:text-blue-400 hover:bg-blue-500/10 transition-colors" title="Editar">
                                    <i data-lucide="pencil" class="w-4 h-4"></i>
                                </button>
                                <button onclick="abrirModalPassword(<?php echo $u['id']; ?>, '<?php echo htmlspecialchars($u['nombre']); ?>')"
                                        class="p-1.5 rounded-lg text-slate-400 hover:text-purple-400 hover:bg-purple-500/10 transition-colors" title="Cambiar contraseña">
                                    <i data-lucide="key" class="w-4 h-4"></i>
                                </button>
                                <?php if (!$esSelf): ?>
                                <button onclick="toggleActivo(<?php echo $u['id']; ?>)"
                                        id="btn-toggle-u-<?php echo $u['id']; ?>"
                                        class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-amber-500/10 transition-colors"
                                        title="<?php echo $u['activo'] ? 'Desactivar' : 'Activar'; ?>">
                                    <i data-lucide="<?php echo $u['activo'] ? 'user-x' : 'user-check'; ?>" class="w-4 h-4"></i>
                                </button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- ===================== MODAL CREAR / EDITAR USUARIO ===================== -->
<div id="modalUsuario" class="fixed inset-0 z-50 hidden flex items-center justify-center p-4">
    <div class="absolute inset-0 bg-slate-950/80 backdrop-blur-sm" onclick="cerrarModalUsuario()"></div>
    <div class="relative w-full max-w-2xl bg-slate-900 border border-slate-700 rounded-2xl shadow-2xl overflow-hidden">
        <div class="flex items-center justify-between px-6 py-4 border-b border-slate-800">
            <h2 id="usuarioModalTitulo" class="text-lg font-bold text-white">Nuevo Usuario</h2>
            <button onclick="cerrarModalUsuario()" class="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800 transition-colors">
                <i data-lucide="x" class="w-5 h-5"></i>
            </button>
        </div>

        <form id="formUsuario" onsubmit="submitUsuario(event)" class="p-6 space-y-5 overflow-y-auto max-h-[78vh]">
            <input type="hidden" id="usuarioId" name="id" value="">

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <!-- Nombre -->
                <div class="sm:col-span-2">
                    <label class="block text-xs font-medium text-slate-400 mb-1.5">Nombre completo <span class="text-red-400">*</span></label>
                    <input type="text" name="nombre" id="uNombre" required
                           class="w-full bg-slate-800 border border-slate-700 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500/30">
                </div>
                <!-- Email -->
                <div>
                    <label class="block text-xs font-medium text-slate-400 mb-1.5">Email <span class="text-red-400">*</span></label>
                    <input type="email" name="email" id="uEmail" required
                           class="w-full bg-slate-800 border border-slate-700 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500/30">
                </div>
                <!-- Teléfono -->
                <div>
                    <label class="block text-xs font-medium text-slate-400 mb-1.5">Teléfono</label>
                    <input type="text" name="telefono" id="uTelefono"
                           class="w-full bg-slate-800 border border-slate-700 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500/30">
                </div>
                <!-- Password (solo en crear) -->
                <div id="passwordField" class="sm:col-span-2">
                    <label class="block text-xs font-medium text-slate-400 mb-1.5">Contraseña <span class="text-red-400">*</span></label>
                    <input type="password" name="password" id="uPassword" minlength="8"
                           pattern="<?php echo ClaveHelper::patronHtml(); ?>" title="<?php echo ClaveHelper::DESCRIPCION; ?>"
                           class="w-full bg-slate-800 border border-slate-700 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500/30">
                    <div id="medidorClaveCrear"></div>
                    <p class="text-[11px] text-slate-500 mt-1"><?php echo ClaveHelper::DESCRIPCION; ?></p>
                </div>
                <!-- Rol -->
                <div>
                    <label class="block text-xs font-medium text-slate-400 mb-1.5">Rol <span class="text-red-400">*</span></label>
                    <?php if ($esFranquiciado): ?>
                        <input type="hidden" name="rol" id="uRol" value="<?php echo ROL_VENDEDOR; ?>">
                        <div class="w-full bg-slate-800/50 border border-slate-700 text-slate-400 rounded-lg px-3 py-2.5 text-sm">
                            Vendedor / Ejecutivo
                        </div>
                    <?php else: ?>
                        <select name="rol" id="uRol" onchange="onRolChange()" required
                                class="w-full bg-slate-800 border border-slate-700 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-blue-500">
                            <?php foreach ($roles as $key => $label): ?>
                                <option value="<?php echo $key; ?>"><?php echo htmlspecialchars($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                    <?php endif; ?>
                </div>
                <!-- Empresa -->
                <div <?php echo $esFranquiciado ? 'style="display:none"' : ''; ?>>
                    <label class="block text-xs font-medium text-slate-400 mb-1.5">Empresa Asociada <span class="text-red-400">*</span></label>
                    <select name="empresa_id" id="uEmpresa" <?php echo $esFranquiciado ? '' : 'required'; ?>
                            class="w-full bg-slate-800 border border-slate-700 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-blue-500">
                        <option value="">Seleccionar...</option>
                        <?php foreach ($empresas as $emp): ?>
                            <option value="<?php echo $emp['id']; ?>" <?php echo $esFranquiciado ? 'selected' : ''; ?>><?php echo htmlspecialchars($emp['nombre_fantasia']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <!-- Franquiciado -->
                <div id="franqField" class="sm:col-span-2" <?php echo $esFranquiciado ? 'style="display:none"' : ''; ?>>
                    <label class="block text-xs font-medium text-slate-400 mb-1.5">Franquiciado Asignado</label>
                    <select name="franquiciado_id" id="uFranquiciado"
                            class="w-full bg-slate-800 border border-slate-700 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-blue-500">
                        <option value="">Sin franquicia especifica</option>
                        <?php foreach ($franquiciados as $fq): ?>
                            <option value="<?php echo $fq['id']; ?>" <?php echo $esFranquiciado ? 'selected' : ''; ?>><?php echo htmlspecialchars($fq['nombre_fantasia']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <!-- Permisos por módulo (se oculta si rol es admin) -->
            <div id="permisosSection">
                <h3 class="text-xs font-semibold uppercase tracking-wider text-slate-500 mb-3">Permisos por Módulo</h3>
                <div class="grid grid-cols-2 sm:grid-cols-3 gap-2">
                    <?php foreach ($modulos as $modKey => $modLabel): ?>
                    <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-slate-800/50 cursor-pointer">
                        <input type="checkbox" name="permisos[]" value="<?php echo $modKey; ?>"
                               class="w-4 h-4 rounded border-slate-600 bg-slate-800 text-blue-500 focus:ring-blue-500/30 perm-check">
                        <span class="text-xs text-slate-300"><?php echo htmlspecialchars($modLabel); ?></span>
                    </label>
                    <?php endforeach; ?>
                </div>
                <p class="text-xs text-slate-500 mt-2">* El rol Administrador tiene acceso total sin importar estos permisos.</p>
            </div>

            <!-- Error -->
            <div id="usuarioError" class="hidden text-sm text-red-400 bg-red-500/10 border border-red-500/20 rounded-lg px-4 py-3"></div>

            <!-- Footer -->
            <div class="flex items-center justify-end gap-4 pt-2 border-t border-slate-800">
                <button type="button" onclick="cerrarModalUsuario()"
                        class="px-4 py-2 text-sm text-red-400 border border-red-500/40 hover:border-red-500/70 hover:bg-red-500/10 rounded-lg transition-colors">
                    Cancelar
                </button>
                <button type="submit" id="btnGuardarUsuario"
                        class="px-5 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-lg transition-colors flex items-center gap-2">
                    <i data-lucide="save" class="w-4 h-4"></i>
                    <span>Guardar</span>
                </button>
            </div>
        </form>
    </div>
</div>

<!-- ===================== MODAL RESET PASSWORD ===================== -->
<div id="modalPassword" class="fixed inset-0 z-50 hidden flex items-center justify-center p-4">
    <div class="absolute inset-0 bg-slate-950/80 backdrop-blur-sm" onclick="cerrarModalPassword()"></div>
    <div class="relative w-full max-w-md bg-slate-900 border border-slate-700 rounded-2xl shadow-2xl p-6">
        <div class="flex items-center justify-between mb-5">
            <h2 class="text-lg font-bold text-white">Cambiar Contraseña</h2>
            <button onclick="cerrarModalPassword()" class="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800 transition-colors">
                <i data-lucide="x" class="w-5 h-5"></i>
            </button>
        </div>
        <p id="pwdUserNombre" class="text-sm text-slate-400 mb-4"></p>
        <form id="formPassword" onsubmit="submitPassword(event)" class="space-y-4">
            <input type="hidden" id="pwdUserId" name="id" value="">
            <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">Nueva contraseña <span class="text-red-400">*</span></label>
                <input type="password" name="new_password" id="pwdNueva" minlength="8" required
                       pattern="<?php echo ClaveHelper::patronHtml(); ?>" title="<?php echo ClaveHelper::DESCRIPCION; ?>"
                       placeholder="Nueva contraseña"
                       class="w-full bg-slate-800 border border-slate-700 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-purple-500 focus:ring-1 focus:ring-purple-500/30">
                <div id="medidorClaveReset"></div>
                <p class="text-[11px] text-slate-500 mt-1"><?php echo ClaveHelper::DESCRIPCION; ?></p>
            </div>
            <div id="pwdError" class="hidden text-sm text-red-400 bg-red-500/10 border border-red-500/20 rounded-lg px-4 py-3"></div>
            <div class="flex items-center justify-end gap-4 pt-2">
                <button type="button" onclick="cerrarModalPassword()"
                        class="px-4 py-2 text-sm text-red-400 border border-red-500/40 hover:border-red-500/70 hover:bg-red-500/10 rounded-lg transition-colors">
                    Cancelar
                </button>
                <button type="submit" id="btnGuardarPwd"
                        class="px-5 py-2 bg-purple-600 hover:bg-purple-700 text-white text-sm font-semibold rounded-lg transition-colors flex items-center gap-2">
                    <i data-lucide="key" class="w-4 h-4"></i>
                    <span>Actualizar</span>
                </button>
            </div>
        </form>
    </div>
</div>

<script src="<?php echo APP_URL; ?>/public/assets/js/medidor_clave.js"></script>
<script>
const APP_URL = '<?php echo APP_URL; ?>';

const PERMISOS_POR_ROL = {
    'admin':         [],  // admin tiene todo, se maneja aparte
    'franquiciado':  ['dashboard','leads','cotizaciones','empresas','contactos','whatsapp','operaciones','reportes','configuracion','verticales','marcas','productos','usuarios'],
    'vendedor':      ['dashboard','leads','cotizaciones','empresas','contactos','whatsapp','productos'],
    'marca':         ['dashboard','operaciones'],
};

function onRolChange() {
    const rolEl = document.getElementById('uRol');
    if (!rolEl) return;
    const rol = rolEl.value;
    const isAdmin = rol === 'admin';
    const permsSection = document.getElementById('permisosSection');
    const franqField = document.getElementById('franqField');

    if (franqField) {
        franqField.style.display = (isAdmin || rol === 'marca') ? 'none' : '';
    }

    const checks = document.querySelectorAll('.perm-check');
    if (isAdmin) {
        permsSection.style.opacity = '0.4';
        checks.forEach(c => { c.checked = true; c.disabled = true; });
    } else {
        permsSection.style.opacity = '1';
        const permitidos = PERMISOS_POR_ROL[rol] || [];
        checks.forEach(c => {
            c.checked  = permitidos.indexOf(c.value) !== -1;
            c.disabled = true;
        });
    }
}

function abrirModalCrear() {
    document.getElementById('usuarioModalTitulo').textContent = 'Nuevo Usuario';
    document.getElementById('formUsuario').reset();
    document.getElementById('usuarioId').value = '';
    document.getElementById('usuarioError').classList.add('hidden');
    document.getElementById('passwordField').style.display = '';
    document.getElementById('uPassword').required = true;
    refrescarMedidorClave('uPassword');
    onRolChange();
    document.getElementById('modalUsuario').classList.remove('hidden');
    lucide.createIcons();
}

async function abrirModalEditar(id) {
    document.getElementById('usuarioModalTitulo').textContent = 'Editar Usuario';
    document.getElementById('usuarioError').classList.add('hidden');
    document.getElementById('passwordField').style.display = 'none';
    document.getElementById('uPassword').required = false;

    const res = await fetch(APP_URL + '/usuarios/data?id=' + id);
    const json = await res.json();
    if (!json.success) { alert('Error al cargar usuario.'); return; }

    const d = json.data;
    document.getElementById('usuarioId').value   = d.id;
    document.getElementById('uNombre').value     = d.nombre;
    document.getElementById('uEmail').value      = d.email;
    document.getElementById('uTelefono').value   = d.telefono || '';
    document.getElementById('uRol').value        = d.rol;
    document.getElementById('uEmpresa').value    = d.empresa_id;
    document.getElementById('uFranquiciado').value = d.franquiciado_id || '';

    onRolChange();
    document.getElementById('modalUsuario').classList.remove('hidden');
    lucide.createIcons();
}

function cerrarModalUsuario() {
    document.getElementById('modalUsuario').classList.add('hidden');
}

async function submitUsuario(e) {
    e.preventDefault();
    const btn = document.getElementById('btnGuardarUsuario');
    const errDiv = document.getElementById('usuarioError');
    btn.disabled = true;
    btn.querySelector('span').textContent = 'Guardando...';
    errDiv.classList.add('hidden');

    const id = document.getElementById('usuarioId').value;
    const url = APP_URL + (id ? '/usuarios/editar' : '/usuarios/crear');
    const formData = new FormData(document.getElementById('formUsuario'));

    try {
        const res = await fetch(url, { method: 'POST', body: formData });
        const json = await res.json();
        if (json.success) {
            cerrarModalUsuario();
            window.location.reload();
        } else {
            errDiv.textContent = json.message;
            errDiv.classList.remove('hidden');
        }
    } catch (err) {
        errDiv.textContent = 'Error de conexión.';
        errDiv.classList.remove('hidden');
    }

    btn.disabled = false;
    btn.querySelector('span').textContent = 'Guardar';
}

async function toggleActivo(id) {
    const res = await fetch(APP_URL + '/usuarios/toggle', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'id=' + id
    });
    const json = await res.json();

    if (json.success) {
        const badge = document.getElementById('badge-u-' + id);
        const btn = document.getElementById('btn-toggle-u-' + id);
        if (json.activo) {
            badge.className = 'inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold border bg-green-500/10 text-green-400 border-green-500/20';
            badge.textContent = 'Activo';
            btn.setAttribute('title', 'Desactivar');
            btn.innerHTML = '<i data-lucide="user-x" class="w-4 h-4"></i>';
        } else {
            badge.className = 'inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold border bg-slate-500/10 text-slate-400 border-slate-500/20';
            badge.textContent = 'Inactivo';
            btn.setAttribute('title', 'Activar');
            btn.innerHTML = '<i data-lucide="user-check" class="w-4 h-4"></i>';
        }
        lucide.createIcons();
    } else {
        alert(json.message);
    }
}

function abrirModalPassword(id, nombre) {
    document.getElementById('pwdUserId').value = id;
    document.getElementById('pwdUserNombre').textContent = 'Usuario: ' + nombre;
    document.getElementById('pwdNueva').value = '';
    refrescarMedidorClave('pwdNueva');
    document.getElementById('pwdError').classList.add('hidden');
    document.getElementById('modalPassword').classList.remove('hidden');
    lucide.createIcons();
}

function cerrarModalPassword() {
    document.getElementById('modalPassword').classList.add('hidden');
}

async function submitPassword(e) {
    e.preventDefault();
    const btn = document.getElementById('btnGuardarPwd');
    const errDiv = document.getElementById('pwdError');
    btn.disabled = true;
    btn.querySelector('span').textContent = 'Actualizando...';
    errDiv.classList.add('hidden');

    const formData = new FormData(document.getElementById('formPassword'));

    try {
        const res = await fetch(APP_URL + '/usuarios/reset-password', { method: 'POST', body: formData });
        const json = await res.json();
        if (json.success) {
            cerrarModalPassword();
            // Toast de éxito
            const toast = document.createElement('div');
            toast.className = 'fixed bottom-6 right-6 z-50 bg-green-600 text-white text-sm font-semibold px-5 py-3 rounded-xl shadow-xl';
            toast.textContent = 'Contraseña actualizada correctamente.';
            document.body.appendChild(toast);
            setTimeout(() => toast.remove(), 3000);
        } else {
            errDiv.textContent = json.message;
            errDiv.classList.remove('hidden');
        }
    } catch (err) {
        errDiv.textContent = 'Error de conexión.';
        errDiv.classList.remove('hidden');
    }

    btn.disabled = false;
    btn.querySelector('span').textContent = 'Actualizar';
}

iniciarMedidorClave('uPassword', 'medidorClaveCrear');
iniciarMedidorClave('pwdNueva', 'medidorClaveReset');
</script>
