<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/layout :: head('Audit Log')}"></head>
<body>
<nav th:replace="~{fragments/layout :: adminbar}"></nav>

<section>
    <div class="container">
        <div class="page-header">
            <h1>Activity &amp; Audit Log</h1>
            <button class="btn btn-outline btn-sm" type="button" onclick="load()">&#8635; Refresh</button>
        </div>

        <div class="cars-toolbar">
            <input class="cars-search" id="aSearch" type="text"
                   placeholder="Search user, entity, action…" oninput="renderRows()"/>
            <span style="display:flex;gap:10px;align-items:center">
                <select id="aFilter" class="cars-search" style="min-width:150px" onchange="renderRows()">
                    <option value="">All actions</option>
                    <option value="CREATE">Create</option>
                    <option value="UPDATE">Update</option>
                    <option value="DELETE">Delete</option>
                    <option value="GENERATE">Generate</option>
                    <option value="LOGIN_SUCCESS">Login success</option>
                    <option value="LOGIN_FAILURE">Login failure</option>
                </select>
                <span id="aCount" style="color:#888;font-size:13px"></span>
            </span>
        </div>

        <div class="table-wrap">
            <table>
                <thead>
                <tr>
                    <th data-sort="createdAt">When</th><th data-sort="username">User</th>
                    <th data-sort="role">Role</th><th data-sort="action">Action</th>
                    <th data-sort="entityType">Entity</th><th data-sort="entityId">ID</th>
                    <th data-sort="detail">Detail</th><th data-sort="ip">IP</th>
                </tr>
                </thead>
                <tbody id="aRows"><tr><td colspan="8" class="table-loading">Loading…</td></tr></tbody>
            </table>
        </div>
        <div class="pager" id="aPager"></div>
    </div>
</section>

<script src="/js/admin-table.js"></script>
<script>
const API='/admin/api/audit';
let ROWS=[];
const ST={sortKey:'createdAt',sortDir:-1,page:1,pageSize:20};
function esc(s){return (s==null?'':String(s)).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));}
function fmt(ts){ if(!ts)return '—'; const d=new Date(ts);
  return d.toLocaleDateString()+' '+d.toLocaleTimeString([], {hour:'2-digit',minute:'2-digit'}); }
function actionPill(a){
  const map={CREATE:'pill-confirmed',UPDATE:'pill-pending',DELETE:'pill-cancelled',
    GENERATE:'pill-pending',LOGIN_SUCCESS:'pill-confirmed',LOGIN_FAILURE:'pill-cancelled'};
  return '<span class="dash-pill '+(map[a]||'')+'">'+esc((a||'').replace('_',' '))+'</span>';
}

function load(){ fetch(API).then(r=>r.json()).then(d=>{ROWS=d;renderRows();})
  .catch(()=>{document.getElementById('aRows').innerHTML='<tr><td colspan="8" class="table-loading">Failed to load.</td></tr>';}); }

function renderRows(){
  const q=(document.getElementById('aSearch').value||'').toLowerCase();
  const f=document.getElementById('aFilter').value;
  let rows=ROWS.filter(m=>(!q||((m.username||'')+' '+(m.entityType||'')+' '+(m.action||'')+' '+(m.detail||'')).toLowerCase().includes(q)) && (!f||m.action===f));
  rows=AdminTable.sort(rows,ST.sortKey,ST.sortDir);
  document.getElementById('aCount').textContent=rows.length+' event'+(rows.length===1?'':'s');
  const tb=document.getElementById('aRows');
  if(!rows.length){tb.innerHTML='<tr><td colspan="8" class="table-loading">No activity recorded.</td></tr>';document.getElementById('aPager').innerHTML='';return;}
  const pg=AdminTable.paginate(rows,ST.page,ST.pageSize);
  tb.innerHTML=pg.slice.map(m=>`
    <tr>
      <td><small>${fmt(m.createdAt)}</small></td>
      <td>${esc(m.username)||'—'}</td>
      <td>${m.role?'<span class="badge">'+esc(m.role)+'</span>':'—'}</td>
      <td>${actionPill(m.action)}</td>
      <td>${esc(m.entityType)||'—'}</td>
      <td>${m.entityId!=null?'#'+esc(m.entityId):'—'}</td>
      <td><small style="color:#888">${esc(m.detail)||'—'}</small></td>
      <td><small style="color:#aaa">${esc(m.ip)||'—'}</small></td>
    </tr>`).join('');
  ST.page=pg.page;
  AdminTable.pager(document.getElementById('aPager'),pg.page,pg.total,p=>{ST.page=p;renderRows();});
}

AdminTable.attachSort(document.querySelector('.table-wrap thead tr'),ST,()=>{ST.page=1;renderRows();});
load();
</script>

<footer th:replace="~{fragments/layout :: footer}"></footer>
</body>
</html>
