<?php
require_once __DIR__.'/../../config/app.php';
require_once __DIR__.'/../../app/Models/ActivityLog.php';

$user = requireAuth(['admin']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    if (($_POST['action'] ?? '')==='clear') {
        $n = ActivityLog::clearOlderThan(90);
        flash('dash', t('success').' ('.$n.')');
    }
    redirect(BASE_URL.'/admin/logs.php');
}

$logs = ActivityLog::recent(200);
$pageTitle  = t('activity_logs');
$activePage = BASE_URL.'/admin/logs.php';
require __DIR__.'/../../app/Views/shared/layout.php';
?>
<div class="page-header" style="display:flex;justify-content:space-between;align-items:center">
  <h2>📜 <?= t('activity_logs') ?></h2>
  <form method="POST" onsubmit="return confirm('<?= e(t('confirm')) ?>?')">
    <?= csrfField() ?>
    <input type="hidden" name="action" value="clear">
    <button class="btn btn-sm btn-secondary">🧹 90+ <?= t('date') ?></button>
  </form>
</div>

<div class="card"><div style="overflow-x:auto">
  <table class="table" style="width:100%;border-collapse:collapse">
    <thead><tr style="border-bottom:1px solid var(--border)">
      <th style="padding:12px"><?= t('date') ?></th>
      <th style="padding:12px"><?= t('admin_role') ?></th>
      <th style="padding:12px"><?= t('action') ?></th>
      <th style="padding:12px">entity</th>
      <th style="padding:12px">details</th>
      <th style="padding:12px">IP</th>
    </tr></thead>
    <tbody>
    <?php if(empty($logs)): ?>
      <tr><td colspan="6" style="padding:24px;text-align:center;color:var(--text-muted)"><?= t('no_data') ?></td></tr>
    <?php else: foreach($logs as $l): ?>
      <tr style="border-bottom:1px solid var(--border)">
        <td style="padding:10px;font-size:13px;color:var(--text-muted);white-space:nowrap"><?= e($l['created_at']) ?></td>
        <td style="padding:10px"><?= e($l['admin_name'] ?: '—') ?></td>
        <td style="padding:10px"><code><?= e($l['action']) ?></code></td>
        <td style="padding:10px"><?= e($l['entity'] ?: '—') ?><?= $l['entity_id']?' #'.(int)$l['entity_id']:'' ?></td>
        <td style="padding:10px;font-size:13px"><?= e($l['details'] ?: '—') ?></td>
        <td style="padding:10px;font-size:12px;color:var(--text-muted)"><?= e($l['ip'] ?: '—') ?></td>
      </tr>
    <?php endforeach; endif; ?>
    </tbody>
  </table>
</div></div>
<?php require __DIR__.'/../../app/Views/shared/layout_end.php'; ?>
