<h1>Audit Log</h1>

<% if (forbidden) { %>
  <div class="alert alert-danger">Your role does not have permission to view the audit trail.</div>
<% } else { %>

  <form method="get" action="/audit-log" class="card" style="display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap">
    <div><label>Action contains</label><input type="text" name="action" value="<%= query.action || '' %>" placeholder="e.g. admin.login"></div>
    <div><label>From</label><input type="date" name="from" value="<%= query.from || '' %>"></div>
    <div><label>To</label><input type="date" name="to" value="<%= query.to || '' %>"></div>
    <div><button class="btn" type="submit">Filter</button></div>
    <% if (canExport) { %><div><a class="btn" style="background:#2fb35c" href="/audit-log/export?<%= new URLSearchParams(query).toString() %>">Export CSV</a></div><% } %>
  </form>

  <div class="card">
    <p style="color:var(--muted);font-size:12px"><%= total %> total entries</p>
    <table>
      <thead><tr><th>When</th><th>Actor</th><th>Action</th><th>Target</th><th>Tenant</th><th>IP</th></tr></thead>
      <tbody>
        <% for (const l of logs) { %>
        <tr>
          <td><%= new Date(l.created_at).toLocaleString() %></td>
          <td><%= l.actor_email %></td>
          <td><code class="mono"><%= l.action %></code><% if (l.impersonation) { %> <span class="badge badge-warn">impersonation</span><% } %></td>
          <td><%= l.target_type ? `${l.target_type}#${l.target_id}` : '—' %></td>
          <td><%= l.tenant_id || '—' %></td>
          <td><%= l.ip_address || '—' %></td>
        </tr>
        <% } %>
        <% if (!logs.length) { %><tr><td colspan="6" style="color:var(--muted)">No matching entries.</td></tr><% } %>
      </tbody>
    </table>
  </div>

<% } %>
