<?php
/**
 * ASISMA CRM - Bitácora de Auditoría (solo admin matriz)
 * Todos los movimientos: navegación, envíos de datos y acciones de negocio.
 */
?>
<!-- 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">Bitácora de Auditoría</h1>
        <p class="text-slate-400 text-sm mt-1">Todos los movimientos de los usuarios en el CRM: navegación, envíos de datos y acciones de negocio.</p>
    </div>
    <div class="text-sm text-slate-400 font-mono bg-slate-900 border border-slate-800 rounded-xl px-4 py-2">
        <?php echo number_format($total); ?> registro(s)
    </div>
</div>

<!-- Filtros -->
<div class="bg-slate-900 border border-slate-800 rounded-2xl p-6 shadow-xl mb-8">
    <form method="GET" action="<?php echo APP_URL; ?>/auditoria" class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-7 gap-4">
        <div>
            <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Usuario</label>
            <select name="usuario_id" class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-800 rounded-xl text-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                <option value="">-- Todos --</option>
                <?php foreach ($usuarios as $u): ?>
                    <option value="<?php echo $u['id']; ?>" <?php echo $filtros['usuario_id'] == $u['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($u['nombre']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Franquicia</label>
            <select name="franquiciado_id" class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-800 rounded-xl text-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                <option value="">-- Todas --</option>
                <?php foreach ($franquiciados as $fr): ?>
                    <option value="<?php echo $fr['id']; ?>" <?php echo $filtros['franquiciado_id'] == $fr['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($fr['nombre_fantasia']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Acción</label>
            <select name="accion" class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-800 rounded-xl text-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                <option value="">-- Todas --</option>
                <?php foreach ($acciones as $a): ?>
                    <option value="<?php echo htmlspecialchars($a['accion']); ?>" <?php echo $filtros['accion'] === $a['accion'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($a['accion']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Desde</label>
            <input type="date" name="desde" value="<?php echo htmlspecialchars($filtros['desde']); ?>"
                   class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-800 rounded-xl text-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <div>
            <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Hasta</label>
            <input type="date" name="hasta" value="<?php echo htmlspecialchars($filtros['hasta']); ?>"
                   class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-800 rounded-xl text-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <div>
            <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Buscar</label>
            <input type="text" name="q" value="<?php echo htmlspecialchars($filtros['q']); ?>" placeholder="Ruta, datos, IP..."
                   class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-800 rounded-xl text-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <div class="flex items-end gap-2">
            <button type="submit" class="flex-1 py-2.5 bg-slate-800 hover:bg-slate-700 text-slate-200 font-semibold rounded-xl text-sm transition-colors border border-slate-700">Filtrar</button>
            <a href="<?php echo APP_URL; ?>/auditoria" class="flex-1 py-2.5 bg-slate-950 hover:bg-slate-900 text-slate-400 text-center font-medium rounded-xl text-sm transition-colors border border-slate-800/80">Limpiar</a>
        </div>
    </form>
</div>

<!-- Table Card -->
<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-5 py-4 font-semibold w-20">ID</th>
                    <th class="px-5 py-4 font-semibold">Usuario</th>
                    <th class="px-5 py-4 font-semibold">Acción</th>
                    <th class="px-5 py-4 font-semibold">Entidad / Ruta</th>
                    <th class="px-5 py-4 font-semibold">IP</th>
                    <th class="px-5 py-4 font-semibold">Fecha / Hora</th>
                    <th class="px-5 py-4 font-semibold text-right">Detalle</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-850 text-slate-300">
                <?php if (empty($logs)): ?>
                    <tr>
                        <td colspan="7" class="px-6 py-12 text-center text-slate-500 font-semibold">No hay registros con esos filtros.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($logs as $log):
                        $esNavegacion = $log['accion'] === 'navegacion';
                        $esEnvio      = $log['accion'] === 'envio_datos';
                        $colorAccion  = $esNavegacion ? 'text-slate-400 border-slate-800'
                                       : ($esEnvio ? 'text-sky-300 border-sky-500/30' : 'text-amber-300 border-amber-500/30');
                        $tieneDetalle = !empty($log['datos_antes']) || !empty($log['datos_despues']);
                    ?>
                        <tr class="hover:bg-slate-800/30 transition-colors">
                            <td class="px-5 py-3 font-mono text-xs text-slate-500">#<?php echo $log['id']; ?></td>
                            <td class="px-5 py-3 text-xs">
                                <div class="font-bold text-slate-200"><?php echo htmlspecialchars(isset($log['usuario_nombre']) && $log['usuario_nombre'] !== null ? $log['usuario_nombre'] : 'Sistema / Webhook'); ?></div>
                                <div class="text-[10px] text-slate-500 mt-0.5">
                                    <?php echo htmlspecialchars(isset($log['franquiciado_nombre']) && $log['franquiciado_nombre'] !== null ? $log['franquiciado_nombre'] : 'ASISMA Matriz'); ?>
                                    <?php if (!empty($log['usuario_rol'])): ?> · <?php echo htmlspecialchars($log['usuario_rol']); ?><?php endif; ?>
                                </div>
                            </td>
                            <td class="px-5 py-3 text-xs">
                                <span class="px-2 py-1 rounded bg-slate-950 border font-mono <?php echo $colorAccion; ?>"><?php echo htmlspecialchars($log['accion']); ?></span>
                            </td>
                            <td class="px-5 py-3 text-xs font-mono text-slate-400">
                                <?php echo htmlspecialchars($log['entidad']); ?><?php echo $log['entidad_id'] ? ' (ID: ' . (int)$log['entidad_id'] . ')' : ''; ?>
                            </td>
                            <td class="px-5 py-3 font-mono text-xs text-slate-400"><?php echo htmlspecialchars($log['ip']); ?></td>
                            <td class="px-5 py-3 font-mono text-xs text-slate-400"><?php echo date('d-m-Y H:i:s', strtotime($log['created_at'])); ?></td>
                            <td class="px-5 py-3 text-right">
                                <?php if ($tieneDetalle): ?>
                                <button onclick='verDetalle(<?php echo json_encode(array(
                                    'id'      => (int)$log['id'],
                                    'accion'  => $log['accion'],
                                    'antes'   => $log['datos_antes'],
                                    'despues' => $log['datos_despues']
                                )); ?>)' class="px-2.5 py-1 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg text-[11px] font-semibold border border-slate-700 transition-colors">Ver</button>
                                <?php else: ?>
                                <span class="text-slate-600 text-xs">—</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPaginas > 1): ?>
    <div class="flex items-center justify-between px-6 py-4 border-t border-slate-800">
        <span class="text-xs text-slate-500">Página <?php echo $pagina; ?> de <?php echo $totalPaginas; ?> (<?php echo number_format($total); ?> registros)</span>
        <div class="flex gap-2">
            <a href="<?php echo $pagina > 1 ? APP_URL . '/auditoria?' . http_build_query(array_merge($_GET, array('page' => $pagina - 1))) : '#'; ?>"
               class="px-3 py-1.5 bg-slate-950 border border-slate-800 text-slate-400 hover:text-white text-xs font-semibold rounded-lg transition-colors <?php echo $pagina <= 1 ? 'opacity-50 pointer-events-none' : ''; ?>">← Anterior</a>
            <a href="<?php echo $pagina < $totalPaginas ? APP_URL . '/auditoria?' . http_build_query(array_merge($_GET, array('page' => $pagina + 1))) : '#'; ?>"
               class="px-3 py-1.5 bg-slate-950 border border-slate-800 text-slate-400 hover:text-white text-xs font-semibold rounded-lg transition-colors <?php echo $pagina >= $totalPaginas ? 'opacity-50 pointer-events-none' : ''; ?>">Siguiente →</a>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Modal de detalle -->
<div id="modalDetalle" class="fixed inset-0 z-50 hidden items-center justify-center bg-slate-950/70 backdrop-blur-sm px-4">
    <div class="bg-slate-900 border border-slate-800 rounded-2xl w-full max-w-2xl p-6 shadow-2xl max-h-[85vh] overflow-y-auto">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-bold text-white">Detalle del movimiento <span id="detId" class="font-mono text-slate-400 text-sm"></span></h3>
            <button onclick="cerrarDetalle()" class="text-slate-500 hover:text-slate-300"><i data-lucide="x" class="w-5 h-5"></i></button>
        </div>
        <div id="detAntesWrap" class="mb-4 hidden">
            <div class="text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1.5">Datos anteriores</div>
            <pre id="detAntes" class="px-4 py-3 bg-slate-950 border border-slate-800 rounded-xl text-xs text-red-300/90 font-mono overflow-x-auto whitespace-pre-wrap"></pre>
        </div>
        <div id="detDespuesWrap" class="hidden">
            <div class="text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1.5">Datos del movimiento</div>
            <pre id="detDespues" class="px-4 py-3 bg-slate-950 border border-slate-800 rounded-xl text-xs text-emerald-300/90 font-mono overflow-x-auto whitespace-pre-wrap"></pre>
        </div>
    </div>
</div>

<script>
function formatearJson(texto) {
    if (!texto) return '';
    try { return JSON.stringify(JSON.parse(texto), null, 2); } catch (e) { return texto; }
}
function verDetalle(d) {
    document.getElementById('detId').textContent = '#' + d.id + ' · ' + d.accion;
    var antes = formatearJson(d.antes), despues = formatearJson(d.despues);
    document.getElementById('detAntesWrap').classList.toggle('hidden', !antes);
    document.getElementById('detAntes').textContent = antes;
    document.getElementById('detDespuesWrap').classList.toggle('hidden', !despues);
    document.getElementById('detDespues').textContent = despues;
    var modal = document.getElementById('modalDetalle');
    modal.classList.remove('hidden');
    modal.classList.add('flex');
    lucide.createIcons();
}
function cerrarDetalle() {
    var modal = document.getElementById('modalDetalle');
    modal.classList.add('hidden');
    modal.classList.remove('flex');
}
document.getElementById('modalDetalle').addEventListener('click', function(e) { if (e.target === this) cerrarDetalle(); });
</script>
