<?php
require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/_helpers.php';
require_admin();

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

$total = (int) DB::fetchValue("SELECT COUNT(*) FROM admin_log");
$logs = DB::fetchAll(
    "SELECT al.*, u.name AS admin_name, t.name AS target_name
     FROM admin_log al
     LEFT JOIN users u ON al.admin_id = u.id
     LEFT JOIN users t ON al.target_id = t.id
     ORDER BY al.created_at DESC
     LIMIT {$perPage} OFFSET {$offset}"
);
$totalPages = (int) ceil($total / $perPage);

$page_title = __('admin_logs');
require __DIR__ . '/_header.php';
?>

<h1>📜 <?= e(__('admin_logs')) ?></h1>

<table class="tbl">
    <thead>
        <tr>
            <th>Date</th>
            <th>Admin</th>
            <th>Action</th>
            <th>Target</th>
            <th>Details</th>
            <th>IP</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($logs as $log): ?>
        <tr>
            <td class="text-muted"><?= format_datetime((int)$log['created_at']) ?></td>
            <td><?= e($log['admin_name'] ?? '-') ?></td>
            <td><strong><?= e($log['action']) ?></strong></td>
            <td><?= e($log['target_name'] ?? '-') ?></td>
            <td class="text-muted"><?= e($log['details'] ?? '-') ?></td>
            <td class="text-muted"><?= e($log['ip'] ?? '-') ?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<?php if ($totalPages > 1): ?>
<div class="text-center mt-1">
    <?php for ($i = max(1, $page-3); $i <= min($totalPages, $page+3); $i++): ?>
        <a href="?page=<?= $i ?>" class="btn btn-sm <?= $i === $page ? '' : 'btn-secondary' ?>"><?= $i ?></a>
    <?php endfor; ?>
</div>
<?php endif; ?>

<?php require __DIR__ . '/_footer.php'; ?>
