<?php $title = 'Admin: Auditoria'; ?>

<div class="card">
    <h1>Auditoria Administrativa</h1>
    <p class="muted" style="color:#555;">Logs de ações administrativas e autenticação.</p>

    <div style="display:grid;grid-template-columns:repeat(6, minmax(140px, 1fr));gap:0.5rem;margin:0.5rem 0;">
        <input id="filterAction" type="text" placeholder="Ação (ex.: login_success)">
        <input id="filterEmail" type="text" placeholder="E-mail contém">
        <input id="filterIp" type="text" placeholder="IP">
        <input id="filterAdminId" type="number" placeholder="Admin ID">
        <input id="filterStart" type="datetime-local" placeholder="Início">
        <input id="filterEnd" type="datetime-local" placeholder="Fim">
    </div>
    <div style="display:flex;gap:0.5rem;margin-bottom:0.75rem;align-items:center;">
        <button id="applyFilters" class="btn">Aplicar filtros</button>
        <button id="clearFilters" class="btn btn-secondary">Limpar</button>
    </div>

    <div class="table-responsive">
        <table class="table" id="auditTable">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Ação</th>
                    <th>Recurso</th>
                    <th>IP</th>
                    <th>Admin ID</th>
                    <th>Metadata</th>
                    <th>Data</th>
                </tr>
            </thead>
            <tbody id="auditBody"></tbody>
        </table>
    </div>

    <div class="footer" style="margin-top:1rem;">
        <strong>Resultado</strong>
        <pre id="result" style="background:#f9fafb;border:1px solid #e5e7eb;border-radius:4px;padding:0.75rem;max-height:280px;overflow:auto;"></pre>
    </div>
</div>

<script>
function getAdminToken() {
    const m = document.cookie.match(/(?:^|; )admin_token=([^;]+)/);
    return m ? decodeURIComponent(m[1]) : null;
}

async function callAdminApi(url) {
    const token = getAdminToken();
    if (!token) { alert('Faça login admin.'); window.location.href = '/admin/login'; return null; }
    const resp = await fetch(url, { headers: { 'Authorization': 'Bearer ' + token } });
    return resp;
}

function setResult(obj) {
    const pre = document.getElementById('result');
    try { pre.textContent = typeof obj === 'string' ? obj : JSON.stringify(obj, null, 2); }
    catch (_) { pre.textContent = String(obj); }
}

function renderRows(rows) {
    const tbody = document.getElementById('auditBody');
    tbody.innerHTML = '';
    for (const row of rows) {
        const tr = document.createElement('tr');
        const tdId = document.createElement('td'); tdId.textContent = row.id;
        const tdAction = document.createElement('td'); tdAction.textContent = row.action;
        const tdRes = document.createElement('td'); tdRes.textContent = row.resource;
        const tdIp = document.createElement('td'); tdIp.textContent = row.ip_address || '';
        const tdAdmin = document.createElement('td'); tdAdmin.textContent = row.admin_user_id ?? '';
        const tdMeta = document.createElement('td'); tdMeta.textContent = typeof row.metadata === 'object' ? JSON.stringify(row.metadata) : (row.metadata || '');
        const tdDate = document.createElement('td'); tdDate.textContent = row.created_at;
        tr.appendChild(tdId); tr.appendChild(tdAction); tr.appendChild(tdRes); tr.appendChild(tdIp); tr.appendChild(tdAdmin); tr.appendChild(tdMeta); tr.appendChild(tdDate);
        tbody.appendChild(tr);
    }
}

async function loadAudit() {
    const q = new URLSearchParams();
    const action = document.getElementById('filterAction').value.trim();
    const email = document.getElementById('filterEmail').value.trim();
    const ip = document.getElementById('filterIp').value.trim();
    const adminId = document.getElementById('filterAdminId').value.trim();
    const start = document.getElementById('filterStart').value.trim();
    const end = document.getElementById('filterEnd').value.trim();
    if (action) q.set('action', action);
    if (email) q.set('email', email);
    if (ip) q.set('ip', ip);
    if (adminId) q.set('admin_user_id', adminId);
    if (start) q.set('start', start.replace('T', ' ') + ':00');
    if (end) q.set('end', end.replace('T', ' ') + ':00');
    const resp = await callAdminApi('/api/admin/audit/logs?' + q.toString());
    if (!resp) return;
    const json = await resp.json().catch(() => ({}));
    setResult(json);
    if (resp.ok && json.ok) {
        renderRows(json.data || []);
    } else {
        alert(json.error || 'Falha ao carregar auditoria');
    }
}

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('applyFilters').addEventListener('click', loadAudit);
    document.getElementById('clearFilters').addEventListener('click', () => {
        for (const id of ['filterAction','filterEmail','filterIp','filterAdminId','filterStart','filterEnd']) {
            document.getElementById(id).value = '';
        }
        loadAudit();
    });
    loadAudit();
});
</script>