<?php
require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/middleware/auth.php';
require_once __DIR__ . '/../app/models/AuditLog.php';

require_login();

$user = $_SESSION['user'] ?? [];
$isAdmin = (!empty($user['is_admin']) || (($user['role'] ?? '') === 'admin'));

if (!$isAdmin) {
    http_response_code(403);
    echo "Forbidden";
    exit;
}

$logs = AuditLog::recent(200);

require_once __DIR__ . '/../app/views/partials/header.php';
?>

<h1>Audit Logs</h1>
<p class="muted">Latest 200 actions.</p>

<table class="table">
  <thead>
    <tr>
      <th>Date</th>
      <th>User</th>
      <th>Action</th>
      <th>Details</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($logs as $l): ?>
      <tr>
        <td><?= htmlspecialchars($l['created_at'] ?? '') ?></td>
        <td>
          <?= htmlspecialchars($l['full_name'] ?? 'Unknown') ?>
          <?php if (!empty($l['email'])): ?>
            <div class="muted" style="font-size:12px;"><?= htmlspecialchars($l['email']) ?></div>
          <?php endif; ?>
        </td>
        <td><code><?= htmlspecialchars($l['action'] ?? '') ?></code></td>
        <td style="max-width:520px; white-space:pre-wrap; word-break:break-word;">
          <?= htmlspecialchars($l['details'] ?? '') ?>
        </td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

<?php require_once __DIR__ . '/../app/views/partials/footer.php'; ?>
