<?php
require_once __DIR__ . '/../../includes/layout.php';
$pdo = getDBConnection();
renderHeader('Auditoría', 'auditoria');
?>
<style>
.aud-wrap { max-width: 1200px; margin: 0 auto; padding: 1.5rem; }
.aud-section { background: var(--surface-card); border: 1px solid var(--border-color); border-radius: 1rem; padding: 1.5rem; margin-bottom: 1.5rem; }
.aud-section > h2 { font-size: 1.05rem; font-weight: 700; margin: 0 0 1rem 0; display: flex; align-items: center; gap: 0.5rem; }
.aud-section > p.section-desc { font-size: 0.8rem; color: var(--text-secondary); margin: -0.5rem 0 1rem 0; }
.filter-row { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: end; margin-bottom: 1rem; }
.filter-row label { font-size: 0.75rem; font-weight: 600; color: var(--text-secondary); display: block; margin-bottom: 0.2rem; }
.filter-row input, .filter-row select { padding: 0.45rem 0.6rem; border-radius: 0.65rem; border: 1px solid var(--border-color); background: var(--surface-card); color: var(--text-primary); font-size: 0.82rem; }
.filter-row input:focus, .filter-row select:focus { outline: none; border-color: var(--accent-color); }
.aud-table { width: 100%; border-collapse: collapse; font-size: 0.82rem; }
.aud-table th { text-align: left; padding: 0.65rem; border-bottom: 2px solid var(--border-color); font-size: 0.72rem; font-weight: 700; color: var(--text-secondary); text-transform: uppercase; white-space: nowrap; }
.aud-table td { padding: 0.55rem 0.65rem; border-bottom: 1px solid var(--border-color); vertical-align: top; }
.aud-table tr:hover td { background: rgba(99,102,241,0.03); }
.badge-mod { display: inline-block; padding: 0.2rem 0.5rem; border-radius: 0.5rem; font-size: 0.7rem; font-weight: 600; }
.badge-accion { display: inline-block; padding: 0.15rem 0.4rem; border-radius: 0.35rem; font-size: 0.7rem; font-weight: 600; }
.pagination { display: flex; gap: 0.25rem; justify-content: center; margin-top: 1rem; flex-wrap: wrap; }
.pagination button { padding: 0.35rem 0.75rem; border: 1px solid var(--border-color); border-radius: 0.5rem; background: var(--surface-card); color: var(--text-primary); cursor: pointer; font-size: 0.8rem; }
.pagination button.active { background: var(--accent-color); color: #fff; border-color: var(--accent-color); }
.pagination button:disabled { opacity: 0.4; cursor: default; }
</style>

<div class="aud-wrap">
    <div style="display:flex;align-items:center;gap:0.75rem;margin-bottom:0.25rem">
        <div style="width:40px;height:40px;border-radius:12px;background:linear-gradient(135deg,#6366f1,#8b5cf6);display:flex;align-items:center;justify-content:center;color:#fff;font-size:1.2rem"><i class="bi bi-shield-check"></i></div>
        <div>
            <h1 style="font-size:1.35rem;font-weight:800;margin:0">Auditoría del Sistema</h1>
            <p style="font-size:0.8rem;color:var(--text-secondary);margin:0">Registro detallado de todas las acciones de los usuarios</p>
        </div>
    </div>

    <div class="aud-section">
        <h2><i class="bi bi-funnel"></i> Filtros</h2>
        <div class="filter-row">
            <div>
                <label>Usuario</label>
                <select id="filtroUsuario"><option value="">Todos</option></select>
            </div>
            <div>
                <label>Módulo</label>
                <select id="filtroModulo"><option value="">Todos</option></select>
            </div>
            <div>
                <label>Desde</label>
                <input type="date" id="filtroDesde">
            </div>
            <div>
                <label>Hasta</label>
                <input type="date" id="filtroHasta">
            </div>
            <div>
                <label>Buscar</label>
                <input type="text" id="filtroSearch" placeholder="accion, detalle..." style="width:140px">
            </div>
            <div>
                <button onclick="cargarAuditoria(1)" style="padding:0.45rem 1rem;border-radius:0.65rem;background:var(--accent-color);color:#fff;border:none;font-weight:600;cursor:pointer;font-size:0.82rem"><i class="bi bi-search"></i> Filtrar</button>
            </div>
        </div>
    </div>

    <div class="aud-section">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:0.75rem">
            <h2 style="margin:0"><i class="bi bi-list-check"></i> Registros <span id="audCount" style="font-weight:400;font-size:0.85rem;color:var(--text-secondary)"></span></h2>
            <button onclick="exportAuditoria()" style="padding:0.4rem 0.85rem;border-radius:0.65rem;background:var(--surface-card);border:1px solid var(--border-color);color:var(--text-primary);cursor:pointer;font-size:0.78rem"><i class="bi bi-download"></i> Exportar</button>
        </div>
        <div style="overflow-x:auto">
            <table class="aud-table">
                <thead><tr>
                    <th>Fecha</th><th>Usuario</th><th>Módulo</th><th>Acción</th><th>Detalle</th><th>IP</th>
                </tr></thead>
                <tbody id="audBody"><tr><td colspan="6" style="text-align:center;padding:2rem;color:var(--text-muted)">Cargando...</td></tr></tbody>
            </table>
        </div>
        <div class="pagination" id="audPagination"></div>
    </div>
</div>

<script>
var audPagina = 1;
var audTotalPages = 1;

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('filtroDesde').value = new Date(Date.now() - 7*86400000).toISOString().slice(0,10);
    document.getElementById('filtroHasta').value = new Date().toISOString().slice(0,10);
    cargarAuditoria(1);
});

async function cargarAuditoria(page) {
    audPagina = page;
    var p = new URLSearchParams();
    p.append('page', page);
    p.append('limit', 100);
    var u = document.getElementById('filtroUsuario').value;
    if (u) p.append('usuario_id', u);
    var m = document.getElementById('filtroModulo').value;
    if (m) p.append('modulo', m);
    var fd = document.getElementById('filtroDesde').value;
    if (fd) p.append('fecha_desde', fd);
    var fh = document.getElementById('filtroHasta').value;
    if (fh) p.append('fecha_hasta', fh);
    var s = document.getElementById('filtroSearch').value.trim();
    if (s) p.append('search', s);

    try {
        var r = await fetch('api/auditoria/listar.php?' + p.toString());
        var d = await r.json();
        if (!d.success) throw new Error(d.message);

        var data = d.data;
        audTotalPages = data.pages;

        // Poblar filtros (solo primera vez)
        if (page === 1 && data.modulos) {
            var selM = document.getElementById('filtroModulo');
            if (selM.options.length === 1) {
                data.modulos.forEach(function(m) {
                    var o = document.createElement('option');
                    o.value = m; o.textContent = m;
                    selM.appendChild(o);
                });
            }
            var selU = document.getElementById('filtroUsuario');
            if (selU.options.length === 1 && data.usuarios) {
                data.usuarios.forEach(function(u) {
                    var o = document.createElement('option');
                    o.value = u.usuario_id; o.textContent = u.usuario_nombre || 'ID ' + u.usuario_id;
                    selU.appendChild(o);
                });
            }
        }

        document.getElementById('audCount').textContent = '(' + data.total + ' registros)';
        var tb = document.getElementById('audBody');
        if (data.rows.length === 0) {
            tb.innerHTML = '<tr><td colspan="6" style="text-align:center;padding:2rem;color:var(--text-muted)">Sin registros</td></tr>';
        } else {
            var html = '';
            data.rows.forEach(function(r) {
                var fecha = r.created_at.slice(0,16).replace('T', ' ');
                var modColor = colorsMod(r.modulo);
                var accColor = colorsAcc(r.accion);
                var det = r.detalle ? (r.detalle.length > 120 ? r.detalle.slice(0,120) + '...' : r.detalle) : '-';
                html += '<tr>' +
                    '<td style="white-space:nowrap">' + fecha + '</td>' +
                    '<td><strong>' + esc(r.usuario_nombre || ('ID ' + r.usuario_id)) + '</strong></td>' +
                    '<td><span class="badge-mod" style="background:' + modColor.bg + ';color:' + modColor.fg + '">' + esc(r.modulo) + '</span></td>' +
                    '<td><span class="badge-accion" style="background:' + accColor.bg + ';color:' + accColor.fg + '">' + esc(r.accion) + '</span></td>' +
                    '<td style="font-size:0.78rem;max-width:300px;word-break:break-word">' + esc(det) + (r.tabla_afectada ? ' <span style="color:var(--text-muted)">[' + esc(r.tabla_afectada) + '#' + r.registro_id + ']</span>' : '') + '</td>' +
                    '<td style="font-size:0.75rem;color:var(--text-muted)">' + r.ip_address + '</td>' +
                    '</tr>';
            });
            tb.innerHTML = html;
        }

        // Paginación
        var pg = document.getElementById('audPagination');
        var ph = '';
        if (audTotalPages > 1) {
            ph += '<button onclick="cargarAuditoria(1)"' + (audPagina <= 1 ? ' disabled' : '') + '><i class="bi bi-chevron-double-left"></i></button>';
            ph += '<button onclick="cargarAuditoria(' + (audPagina - 1) + ')"' + (audPagina <= 1 ? ' disabled' : '') + '><i class="bi bi-chevron-left"></i></button>';
            for (var i = Math.max(1, audPagina - 2); i <= Math.min(audTotalPages, audPagina + 2); i++) {
                ph += '<button class="' + (i === audPagina ? 'active' : '') + '" onclick="cargarAuditoria(' + i + ')">' + i + '</button>';
            }
            ph += '<button onclick="cargarAuditoria(' + (audPagina + 1) + ')"' + (audPagina >= audTotalPages ? ' disabled' : '') + '><i class="bi bi-chevron-right"></i></button>';
            ph += '<button onclick="cargarAuditoria(' + audTotalPages + ')"' + (audPagina >= audTotalPages ? ' disabled' : '') + '><i class="bi bi-chevron-double-right"></i></button>';
        }
        pg.innerHTML = ph;
    } catch(e) {
        document.getElementById('audBody').innerHTML = '<tr><td colspan="6" style="text-align:center;padding:2rem;color:#ef4444">Error: ' + e.message + '</td></tr>';
    }
}

function colorsMod(mod) {
    var map = {
        'Login': {bg:'#dbeafe',fg:'#1e40af'}, 'Ventas': {bg:'#d1fae5',fg:'#065f46'},
        'Compras': {bg:'#fef3c7',fg:'#92400e'}, 'Inventario': {bg:'#e0f2fe',fg:'#075985'},
        'Usuarios': {bg:'#f3e8ff',fg:'#6b21a8'}, 'Pedidos': {bg:'#ccfbf1',fg:'#0f766e'},
        'Contabilidad': {bg:'#fce7f3',fg:'#9d174d'}, 'Configuración': {bg:'#e5e7eb',fg:'#374151'}
    };
    return map[mod] || {bg:'#f1f5f9',fg:'#475569'};
}

function colorsAcc(acc) {
    if (acc.startsWith('Crear') || acc.startsWith('Login')) return {bg:'#d1fae5',fg:'#065f46'};
    if (acc.startsWith('Actualizar') || acc.startsWith('Editar')) return {bg:'#dbeafe',fg:'#1e40af'};
    if (acc.startsWith('Eliminar') || acc.startsWith('Cancelar') || acc.startsWith('Logout')) return {bg:'#fee2e2',fg:'#991b1b'};
    if (acc.startsWith('Ver') || acc.startsWith('Exportar')) return {bg:'#f1f5f9',fg:'#475569'};
    return {bg:'#fef3c7',fg:'#92400e'};
}

function exportAuditoria() {
    var table = document.querySelector('.aud-table');
    if (!table) return;
    var rows = [];
    table.querySelectorAll('tbody tr').forEach(function(tr) {
        var td = tr.querySelectorAll('td');
        if (td.length >= 6) {
            rows.push([td[0].textContent.trim(), td[1].textContent.trim(), td[2].textContent.trim(), td[3].textContent.trim(), td[4].textContent.trim(), td[5].textContent.trim()]);
        }
    });
    if (rows.length === 0) return alert('No hay datos para exportar');
    var csv = '\uFEFFFecha;Usuario;Módulo;Acción;Detalle;IP\n';
    rows.forEach(function(r) { csv += r.join(';') + '\n'; });
    var blob = new Blob([csv], {type:'text/csv;charset=utf-8;'});
    var link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'auditoria_' + new Date().toISOString().slice(0,10) + '.csv';
    link.click();
}
</script>
<?php renderFooter(); ?>

