<ul class="nav ab-tabs mb-3">
  <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tabActivity">System Activity</a></li>
  <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tabLoginHistory">Login History</a></li>
</ul>

<div class="tab-content">
  <div class="tab-pane fade show active" id="tabActivity">
    <div class="ab-table-card">
      <div class="ab-table-toolbar">
        <div class="ab-search"><i class="bi bi-search"></i><input type="text" id="abLogSearch" placeholder="Search actions..."></div>
        <div class="ab-chip active" data-cat="all">All</div>
        <div class="ab-chip" data-cat="user_action">User Action</div>
        <div class="ab-chip" data-cat="system">System</div>
        <div class="ab-chip" data-cat="security">Security</div>
        <div class="ab-chip" data-cat="admin">Admin</div>
      </div>
      <div class="table-responsive">
        <table class="table ab-table align-middle">
          <thead><tr><th>Timestamp</th><th>User</th><th>Action</th><th>Category</th><th>IP Address</th></tr></thead>
          <tbody>
          <?php foreach ($rows as $row): ?>
            <tr>
              <td class="ab-cell-sub ab-mono"><?= e(date('M j, g:i A', strtotime($row['created_at']))) ?></td>
              <td><?= e($row['user_name'] ?? 'System') ?></td>
              <td><?= e($row['action']) ?></td>
              <td><span class="ab-badge <?= match($row['category']) { 'security' => 'bg-warning-soft', 'admin' => 'bg-danger-soft', 'system' => 'bg-primary-soft', default => 'bg-secondary-soft' } ?>"><?= e(ucwords(str_replace('_',' ',$row['category']))) ?></span></td>
              <td class="ab-mono ab-cell-sub"><?= e($row['ip_address'] ?? '—') ?></td>
            </tr>
          <?php endforeach; ?>
          <?php if (empty($rows)): ?><tr><td colspan="5" class="text-center p-4 ab-text-muted">No activity recorded yet.</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
      <div class="ab-table-pagination">
        <div>Showing <strong><?= (int) $meta['from'] ?>–<?= (int) $meta['to'] ?></strong> of <strong><?= (int) $meta['total'] ?></strong> events</div>
        <?php if ((int) $meta['total_pages'] > 1): ?>
        <nav aria-label="Activity log pagination">
          <ul class="pagination pagination-sm mb-0">
            <?php
              $currentPage = (int) $meta['page'];
              $lastPage = (int) $meta['total_pages'];
              $pageUrl = function (int $page) {
                  $params = $_GET;
                  $params['page'] = $page;
                  return base_url('activity-logs') . '?' . http_build_query($params);
              };
              $pagesToShow = array_unique(array_filter(
                  range(max(1, $currentPage - 2), min($lastPage, $currentPage + 2)) + [1, $lastPage],
                  fn ($p) => $p >= 1 && $p <= $lastPage
              ));
              sort($pagesToShow);
            ?>
            <li class="page-item <?= !$meta['has_previous'] ? 'disabled' : '' ?>">
              <a class="page-link" href="<?= $meta['has_previous'] ? e($pageUrl($currentPage - 1)) : '#' ?>" aria-label="Previous">&laquo;</a>
            </li>
            <?php $previousPage = 0; foreach ($pagesToShow as $p): ?>
              <?php if ($p - $previousPage > 1): ?>
                <li class="page-item disabled"><span class="page-link">&hellip;</span></li>
              <?php endif; ?>
              <li class="page-item <?= $p === $currentPage ? 'active' : '' ?>">
                <a class="page-link" href="<?= e($pageUrl($p)) ?>"><?= $p ?></a>
              </li>
              <?php $previousPage = $p; ?>
            <?php endforeach; ?>
            <li class="page-item <?= !$meta['has_next'] ? 'disabled' : '' ?>">
              <a class="page-link" href="<?= $meta['has_next'] ? e($pageUrl($currentPage + 1)) : '#' ?>" aria-label="Next">&raquo;</a>
            </li>
          </ul>
        </nav>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <div class="tab-pane fade" id="tabLoginHistory">
    <div class="ab-table-card">
      <div class="table-responsive">
        <table class="table ab-table align-middle" id="abLoginHistoryTable">
          <thead><tr><th>Timestamp</th><th>Email</th><th>IP Address</th><th>Result</th></tr></thead>
          <tbody><tr><td colspan="4" class="text-center p-4 ab-text-muted">Loading…</td></tr></tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<script>
document.querySelectorAll('[data-cat]').forEach(function (chip) {
  chip.addEventListener('click', function () {
    var params = new URLSearchParams(window.location.search);
    params.set('category', this.dataset.cat);
    window.location.search = params.toString();
  });
});
document.getElementById('abLogSearch').addEventListener('keydown', function (e) {
  if (e.key !== 'Enter') return;
  var params = new URLSearchParams(window.location.search);
  params.set('search', this.value);
  window.location.search = params.toString();
});

document.querySelector('[href="#tabLoginHistory"]').addEventListener('shown.bs.tab', function () {
  abFetch('<?= base_url('login-history') ?>').then(function (res) {
    var tbody = document.querySelector('#abLoginHistoryTable tbody');
    if (!res.data.rows.length) { tbody.innerHTML = '<tr><td colspan="4" class="text-center p-4 ab-text-muted">No login attempts recorded.</td></tr>'; return; }
    tbody.innerHTML = res.data.rows.map(function (r) {
      var badge = r.was_successful == 1 ? '<span class="ab-badge bg-success-soft">Success</span>' : '<span class="ab-badge bg-danger-soft">Failed</span>';
      return '<tr><td class="ab-cell-sub ab-mono">' + r.attempted_at + '</td><td>' + r.email + '</td><td class="ab-mono ab-cell-sub">' + r.ip_address + '</td><td>' + badge + '</td></tr>';
    }).join('');
  });
}, { once: true });
</script>
