<?php
$db = getDB();

$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

$totalStmt = $db->query("SELECT COUNT(*) as cnt FROM audit_logs");
$total = $totalStmt->fetch()['cnt'];
$totalPages = max(1, ceil($total / $perPage));

$stmt = $db->prepare("SELECT * FROM audit_logs ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->execute([$perPage, $offset]);
$logs = $stmt->fetchAll();

include __DIR__ . '/admin_header.php';
?>

<div class="admin-topbar">
    <h2>Audit Logs</h2>
</div>

<div class="admin-card">
    <h3>Activity Log (Page <?= $page ?> of <?= $totalPages ?>)</h3>
    <table>
        <thead>
            <tr><th>Admin User</th><th>Action</th><th>Entity</th><th>Details</th><th>IP</th><th>Date</th></tr>
        </thead>
        <tbody>
        <?php foreach ($logs as $l): ?>
            <tr>
                <td><?= htmlspecialchars($l['admin_user'] ?? '') ?></td>
                <td><?= htmlspecialchars($l['action']) ?></td>
                <td><?= htmlspecialchars(($l['entity_type'] ?? '') . ($l['entity_id'] ? ' #' . $l['entity_id'] : '')) ?></td>
                <td><?= htmlspecialchars(substr($l['details'] ?? '', 0, 100)) ?></td>
                <td><?= htmlspecialchars($l['ip_address'] ?? '') ?></td>
                <td><?= htmlspecialchars($l['created_at']) ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

    <?php if ($totalPages > 1): ?>
    <div style="margin-top:20px;text-align:center;">
        <?php if ($page > 1): ?>
        <a href="/admin/audit?page=<?= $page - 1 ?>" class="btn-sm btn-sm-primary">&laquo; Previous</a>
        <?php endif; ?>
        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
        <a href="/admin/audit?page=<?= $i ?>" class="btn-sm <?= $i === $page ? 'btn-sm-success' : 'btn-sm-primary' ?>"><?= $i ?></a>
        <?php endfor; ?>
        <?php if ($page < $totalPages): ?>
        <a href="/admin/audit?page=<?= $page + 1 ?>" class="btn-sm btn-sm-primary">Next &raquo;</a>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<?php include __DIR__ . '/admin_footer.php'; ?>
