<?= $this->extend('layouts/panel') ?>
<?= $this->section('sidebar') ?>
<?= $this->include('panel/_sidebar') ?>
<?= $this->endSection() ?>

<?= $this->section('content') ?>

<h5 class="mb-3">Audit Log</h5>

<div class="li-card mb-3">
    <div class="li-card-body">
        <div class="row g-2">
            <div class="col-md-2">
                <label class="form-label small text-muted mb-1">From</label>
                <input type="date" id="dateFromFilter" class="form-control form-control-sm">
            </div>
            <div class="col-md-2">
                <label class="form-label small text-muted mb-1">To</label>
                <input type="date" id="dateToFilter" class="form-control form-control-sm">
            </div>
            <div class="col-md-2">
                <label class="form-label small text-muted mb-1">Role</label>
                <select id="roleFilter" class="form-select form-select-sm">
                    <option value="">All roles</option>
                    <option value="candidate">Candidate</option>
                    <option value="agency_owner">Agency Owner</option>
                    <option value="recruiter">Recruiter</option>
                    <option value="super_admin">Super Admin</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label small text-muted mb-1">Action Type</label>
                <select id="actionFilter" class="form-select form-select-sm">
                    <option value="">All actions</option>
                </select>
            </div>
            <div class="col-md-3 d-flex align-items-end gap-2">
                <button class="btn btn-li-primary btn-sm" onclick="loadLog(1)">Apply Filters</button>
                <button class="btn btn-li-ghost btn-sm" onclick="clearFilters()">Clear</button>
            </div>
        </div>
    </div>
</div>

<div class="li-card">
    <div class="table-responsive">
        <table class="table li-table mb-0">
            <thead><tr><th>Date &amp; Time</th><th>User</th><th>Role</th><th>Action</th><th>Details</th><th>IP Address</th></tr></thead>
            <tbody id="logTable"></tbody>
        </table>
    </div>
    <div id="logEmpty" class="text-center text-muted py-5 d-none">No activity matches your filters.</div>
</div>

<div class="d-flex justify-content-between align-items-center mt-3">
    <span class="text-muted small" id="pageInfo"></span>
    <div>
        <button class="btn btn-li-ghost btn-sm" id="prevPageBtn" onclick="changePage(-1)">← Previous</button>
        <button class="btn btn-li-ghost btn-sm" id="nextPageBtn" onclick="changePage(1)">Next →</button>
    </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
let currentPage = 1;
let totalRows = 0;
const PER_PAGE = 50;

function roleBadge(role) {
    const map = { candidate: 'blue', agency_owner: 'green', recruiter: 'blue', super_admin: 'red' };
    return role ? `<span class="li-pill li-pill-${map[role] || 'gray'}">${role.replace(/_/g,' ')}</span>` : '<span class="text-muted small">—</span>';
}

function actionLabel(action) {
    return action.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
}

function buildDetails(row) {
    const parts = [];
    if (row.company_name) parts.push(escapeHtml(row.company_name));
    if (row.metadata) {
        try {
            const meta = typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata;
            const kv = Object.entries(meta).map(([k, v]) => `${k}: ${v}`).join(', ');
            if (kv) parts.push(`<span class="text-muted">${escapeHtml(kv)}</span>`);
        } catch (e) {}
    }
    return parts.join(' · ') || '—';
}

async function loadLog(page) {
    currentPage = page || currentPage;
    const params = new URLSearchParams();
    params.set('page', currentPage);
    const dateFrom = document.getElementById('dateFromFilter').value;
    const dateTo = document.getElementById('dateToFilter').value;
    const role = document.getElementById('roleFilter').value;
    const action = document.getElementById('actionFilter').value;
    if (dateFrom) params.set('date_from', dateFrom);
    if (dateTo) params.set('date_to', dateTo);
    if (role) params.set('role', role);
    if (action) params.set('action', action);

    try {
        const res = await apiFetch(`/admin/audit-log?${params.toString()}`);
        const rows = res.data || [];
        totalRows = res.meta.total || 0;

        const actionSelect = document.getElementById('actionFilter');
        if (actionSelect.options.length === 1 && res.meta.action_types) {
            res.meta.action_types.forEach(a => {
                const opt = document.createElement('option');
                opt.value = a;
                opt.textContent = actionLabel(a);
                actionSelect.appendChild(opt);
            });
        }

        const tbody = document.getElementById('logTable');
        const empty = document.getElementById('logEmpty');
        if (rows.length === 0) { tbody.innerHTML = ''; empty.classList.remove('d-none'); }
        else {
            empty.classList.add('d-none');
            tbody.innerHTML = rows.map(r => `
                <tr>
                    <td class="small">${formatDateTime(r.created_at)}</td>
                    <td class="small">${escapeHtml(r.user_name || 'System')}</td>
                    <td>${roleBadge(r.role)}</td>
                    <td class="small fw-semibold">${actionLabel(r.action)}</td>
                    <td class="small">${buildDetails(r)}</td>
                    <td class="text-muted small">${escapeHtml(r.ip_address || '—')}</td>
                </tr>
            `).join('');
        }

        const totalPages = Math.max(1, Math.ceil(totalRows / PER_PAGE));
        document.getElementById('pageInfo').textContent = `Page ${currentPage} of ${totalPages} (${totalRows} total)`;
        document.getElementById('prevPageBtn').disabled = currentPage <= 1;
        document.getElementById('nextPageBtn').disabled = currentPage >= totalPages;
    } catch (e) { showToast(e.message, true); }
}

function changePage(delta) {
    loadLog(currentPage + delta);
}

function clearFilters() {
    document.getElementById('dateFromFilter').value = '';
    document.getElementById('dateToFilter').value = '';
    document.getElementById('roleFilter').value = '';
    document.getElementById('actionFilter').value = '';
    loadLog(1);
}

loadLog(1);
</script>
<?= $this->endSection() ?>
