<?php

declare(strict_types=1);

/**
 * APO-197 Card 7 — Audit Log surface (read-only).
 *
 * Paginated list of audit events with filters: integrationId, action verb,
 * outcome, date range. Detail view shows full sanitised input/output for a
 * single event.
 */

require_once dirname(__DIR__, 3) . '/system/bootstrap.php';

$currentUser  = myronRequireAdministrationAccess();
$auditRepo    = myronAuditLogRepository();
$integrationRepo = myronAiIntegrationRepository();

$filters = [
    'integrationId' => trim((string) ($_GET['integration'] ?? '')),
    'actionVerb'    => trim((string) ($_GET['verb'] ?? '')),
    'outcome'       => trim((string) ($_GET['outcome'] ?? '')),
    'fromDate'      => trim((string) ($_GET['from'] ?? '')),
    'toDate'        => trim((string) ($_GET['to'] ?? '')),
];
$page  = max(1, (int) ($_GET['page'] ?? 1));
$limit = 50;
$offset = ($page - 1) * $limit;

$detailEventId = trim((string) ($_GET['event'] ?? ''));
$detailEvent = $detailEventId !== '' ? $auditRepo->findByAuditEventId($detailEventId) : null;

$events = $auditRepo->list($limit, $offset, array_filter($filters, static fn ($v) => $v !== ''));
$integrations = $integrationRepo->listAll();
$integrationsById = [];
foreach ($integrations as $int) {
    $integrationsById[$int->id] = $int;
}

myronRenderAdminShellStart($currentUser, [
    'title' => 'Audit Log',
    'titleContext' => 'Administration',
    'activeItem' => 'audit-log',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Administration', 'href' => myronBuildAdminUrl('identity.users')],
      ['label' => 'System', 'href' => myronBuildAdminUrl('administration.siteSetup')],
      ['label' => 'Audit Log'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Audit Log</h1>
  </div>
  <p class="mc-workspace__subtitle">Every API call writes one row. Append-only. Use this to monitor what AI integrations did.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">

    <section class="sg-section">
      <h2 class="sg-section__title">Filters</h2>
      <form method="get" class="sg-form-grid">
        <label class="sg-field"><span class="sg-field__label">Integration</span>
          <select class="sg-field__control" name="integration">
            <option value="">— All —</option>
            <?php foreach ($integrations as $int): ?>
            <option value="<?= myronEscape($int->id) ?>" <?= $filters['integrationId'] === $int->id ? 'selected' : '' ?>><?= myronEscape($int->label) ?></option>
            <?php endforeach; ?>
          </select>
        </label>
        <label class="sg-field"><span class="sg-field__label">Action verb</span>
          <input class="sg-field__control" type="text" name="verb" value="<?= myronEscape($filters['actionVerb']) ?>" placeholder="e.g. set-default">
        </label>
        <label class="sg-field"><span class="sg-field__label">Outcome</span>
          <select class="sg-field__control" name="outcome">
            <option value="">— All —</option>
            <?php foreach (['ok', 'error', 'authz_denied', 'rate_limited'] as $o): ?>
            <option value="<?= myronEscape($o) ?>" <?= $filters['outcome'] === $o ? 'selected' : '' ?>><?= myronEscape($o) ?></option>
            <?php endforeach; ?>
          </select>
        </label>
        <label class="sg-field"><span class="sg-field__label">From</span>
          <input class="sg-field__control" type="text" name="from" value="<?= myronEscape($filters['fromDate']) ?>" placeholder="2026-05-01">
        </label>
        <label class="sg-field"><span class="sg-field__label">To</span>
          <input class="sg-field__control" type="text" name="to" value="<?= myronEscape($filters['toDate']) ?>" placeholder="2026-05-31">
        </label>
        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit">Apply</button>
          <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('administration.auditLog')) ?>">Clear</a>
        </div>
      </form>
    </section>

    <section class="sg-section">
      <h2 class="sg-section__title">Events (page <?= $page ?>)</h2>
      <table class="mc-page-grid">
        <thead><tr><th>When</th><th>Integration</th><th>Action</th><th>Outcome</th><th>Status</th><th>Latency</th><th></th></tr></thead>
        <tbody>
        <?php foreach ($events as $event): ?>
        <?php $intLabel = $event->integrationId !== null && isset($integrationsById[$event->integrationId]) ? $integrationsById[$event->integrationId]->label : ($event->integrationId ?? 'anonymous'); ?>
        <tr>
          <td><?= myronEscape($event->createdAt) ?></td>
          <td><?= myronEscape($intLabel) ?></td>
          <td><code><?= myronEscape($event->actionDomain . '.' . $event->actionVerb) ?></code></td>
          <td><?= myronEscape($event->outcome) ?></td>
          <td><?= (int) $event->httpStatus ?></td>
          <td><?= (int) $event->latencyMs ?>ms</td>
          <td><a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('administration.auditLog', ['event' => $event->auditEventId])) ?>">Detail</a></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
      <?php if (count($events) === $limit): ?>
      <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('administration.auditLog', array_merge($filters, ['page' => $page + 1]))) ?>">Next page</a>
      <?php endif; ?>
    </section>

    <?php if ($detailEvent !== null): ?>
    <section class="sg-section">
      <h2 class="sg-section__title">Event Detail</h2>
      <dl class="sg-define-list">
        <dt>Audit event ID</dt><dd><code><?= myronEscape($detailEvent->auditEventId) ?></code></dd>
        <dt>Action ID</dt><dd><code><?= myronEscape($detailEvent->actionId) ?></code></dd>
        <dt>Integration</dt><dd><?= myronEscape($detailEvent->integrationId ?? 'anonymous') ?></dd>
        <dt>URI</dt><dd><code><?= myronEscape($detailEvent->requestMethod . ' ' . $detailEvent->requestUri) ?></code></dd>
        <dt>Outcome / Status</dt><dd><?= myronEscape($detailEvent->outcome) ?> / <?= (int) $detailEvent->httpStatus ?> <?= $detailEvent->errorCode ? ' (' . myronEscape($detailEvent->errorCode) . ')' : '' ?></dd>
        <dt>Latency</dt><dd><?= (int) $detailEvent->latencyMs ?>ms</dd>
        <dt>Client</dt><dd><?= myronEscape($detailEvent->clientIp) ?> · <?= myronEscape($detailEvent->userAgent) ?></dd>
        <dt>Sanitised input</dt><dd><pre class="sg-code-block"><code><?= myronEscape(json_encode($detailEvent->inputSanitised, JSON_PRETTY_PRINT)) ?></code></pre></dd>
        <dt>Sanitised output</dt><dd><pre class="sg-code-block"><code><?= myronEscape(json_encode($detailEvent->outputSanitised, JSON_PRETTY_PRINT)) ?></code></pre></dd>
      </dl>
    </section>
    <?php endif; ?>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
