<?php

require_once __DIR__ . '/../lib/init.php';
Auth::requireLogin();

$perPage = 50;
$page    = max(1, (int)($_GET['page'] ?? 1));
$offset  = ($page - 1) * $perPage;
$total   = AuditLog::count();
$pages   = max(1, (int)ceil($total / $perPage));
$logs    = AuditLog::getRecent($perPage, $offset);

$page_title = 'Journal des actions';
require_once APP_ROOT . '/lib/layout_header.php';
?>

<div class="card">
    <div class="card-header py-3 d-flex justify-content-between align-items-center">
        <span><i class="bi bi-clock-history me-2"></i><?= number_format($total) ?> entrée<?= $total > 1 ? 's' : '' ?></span>
    </div>
    <div class="card-body p-0">
        <?php if ($logs): ?>
        <table class="table table-sm table-hover mb-0">
            <thead class="table-light">
                <tr>
                    <th style="width:160px">Date</th>
                    <th>Action</th>
                    <th>Utilisateur</th>
                    <th>Détails</th>
                    <th>IP</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($logs as $log): ?>
            <tr>
                <td><small class="text-muted font-monospace"><?= h($log['created_at']) ?></small></td>
                <td>
                    <span class="badge <?= match(true) {
                        str_contains($log['action'], 'delete') => 'bg-danger',
                        str_contains($log['action'], 'add')    => 'bg-success',
                        str_contains($log['action'], 'edit') || str_contains($log['action'], 'update') => 'bg-warning text-dark',
                        str_contains($log['action'], 'login')  => 'bg-info text-dark',
                        default => 'bg-secondary',
                    } ?>">
                        <?= h($log['action']) ?>
                    </span>
                </td>
                <td><?= h($log['username'] ?? '—') ?></td>
                <td><small class="text-muted"><?= h($log['details'] ?? '') ?></small></td>
                <td><small class="text-muted font-monospace"><?= h($log['ip_address'] ?? '') ?></small></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php else: ?>
        <div class="p-5 text-center text-muted">
            <i class="bi bi-clock-history fs-1"></i>
            <p class="mt-3 mb-0">Le journal est vide.</p>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php if ($pages > 1): ?>
<nav class="mt-3">
    <ul class="pagination pagination-sm justify-content-center">
        <?php for ($p = 1; $p <= $pages; $p++): ?>
            <li class="page-item <?= $p === $page ? 'active' : '' ?>">
                <a class="page-link" href="?page=<?= $p ?>"><?= $p ?></a>
            </li>
        <?php endfor; ?>
    </ul>
</nav>
<?php endif; ?>

<?php require_once APP_ROOT . '/lib/layout_footer.php'; ?>
