<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireAdminLogin();

$page = max(1,(int)($_GET['page']??1)); $perPage = 50;
$total=(int)$pdo->query("SELECT COUNT(*) FROM activity_logs")->fetchColumn();
$pages=(int)ceil($total/$perPage); $offset=($page-1)*$perPage;
$logs=$pdo->query("SELECT l.*, CONCAT(COALESCE(u.first_name,''),' ',COALESCE(u.last_name,'')) AS user_name, COALESCE(a.display_name,a.username,'—') AS admin_name FROM activity_logs l LEFT JOIN users u ON l.user_id=u.id LEFT JOIN admin_users a ON l.admin_id=a.id ORDER BY l.created_at DESC LIMIT $perPage OFFSET $offset")->fetchAll();
$pageTitle = 'Activity Log';
?>
<?php include '../includes/header.php'; ?>
<div class="page-title"><i class="fa fa-history me-2 text-danger"></i>Activity Log</div>
<div class="card">
  <div class="table-responsive">
    <table class="table table-hover mb-0 small">
      <thead><tr><th>Time</th><th>User</th><th>Admin</th><th>Action</th><th>Description</th><th>IP</th></tr></thead>
      <tbody>
      <?php foreach ($logs as $l): ?>
      <tr>
        <td><?= formatDate($l['created_at'],'M j g:i A') ?></td>
        <td><?= sanitize(trim($l['user_name'])?:($l['user_id']?'User #'.$l['user_id']:'—')) ?></td>
        <td><?= sanitize($l['admin_name']??'—') ?></td>
        <td><code><?= sanitize($l['action']) ?></code></td>
        <td><?= sanitize(substr($l['description'],0,60)) ?></td>
        <td><code><?= sanitize($l['ip_address']??'') ?></code></td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php if ($pages > 1): ?>
  <div class="card-footer d-flex justify-content-between">
    <small>Page <?= $page ?>/<?= $pages ?></small>
    <nav><ul class="pagination pagination-sm mb-0"><?php for ($i=max(1,$page-2);$i<=min($pages,$page+2);$i++): ?><li class="page-item <?= $i==$page?'active':'' ?>"><a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a></li><?php endfor; ?></ul></nav>
  </div>
  <?php endif; ?>
</div>
<?php include '../includes/footer.php'; ?>
