<?php
// public/audit_logs.php
require_once __DIR__ . '/../helpers/auth.php';
require_role(['admin', 'staff']);

$pdo = db();
$title = "Audit Logs - IMS";

// ---------------------------
// Helpers
// ---------------------------
function get_str(string $k): string { return trim((string)($_GET[$k] ?? '')); }
function get_int(string $k): int { return (int)($_GET[$k] ?? 0); }

$q        = get_str('q');          // free search
$user_id  = get_int('user_id');    // filter by user
$action   = get_str('action');     // filter by action exact
$entity   = get_str('entity');     // filter by entity exact
$date_from = get_str('date_from'); // YYYY-MM-DD
$date_to   = get_str('date_to');   // YYYY-MM-DD

$page = max(1, get_int('page'));
$per_page = 25;
$offset = ($page - 1) * $per_page;

// ---------------------------
// Dropdown values
// ---------------------------

// Users dropdown (admin + staff + driver)
$users = $pdo->query("
  SELECT u.id, u.full_name, u.username, r.name AS role_name
  FROM users u
  JOIN roles r ON r.id = u.role_id
  ORDER BY u.full_name ASC
")->fetchAll();

// Distinct action list
$actions = $pdo->query("
  SELECT DISTINCT action
  FROM audit_logs
  ORDER BY action ASC
")->fetchAll();

// Distinct entity list
$entities = $pdo->query("
  SELECT DISTINCT entity
  FROM audit_logs
  ORDER BY entity ASC
")->fetchAll();

// ---------------------------
// Build WHERE
// ---------------------------
$where = "WHERE 1=1";
$params = [];

if ($user_id > 0) {
  $where .= " AND a.user_id = :user_id";
  $params[':user_id'] = $user_id;
}

if ($action !== '') {
  $where .= " AND a.action = :action";
  $params[':action'] = $action;
}

if ($entity !== '') {
  $where .= " AND a.entity = :entity";
  $params[':entity'] = $entity;
}

// Date filters (inclusive)
if ($date_from !== '') {
  $where .= " AND a.created_at >= :date_from";
  $params[':date_from'] = $date_from . " 00:00:00";
}
if ($date_to !== '') {
  $where .= " AND a.created_at <= :date_to";
  $params[':date_to'] = $date_to . " 23:59:59";
}

// Search across action/entity/entity_id/details/ip + user name/username
if ($q !== '') {
  $where .= " AND (
      a.action LIKE :q
      OR a.entity LIKE :q
      OR a.entity_id LIKE :q
      OR a.details LIKE :q
      OR a.ip_address LIKE :q
      OR u.full_name LIKE :q
      OR u.username LIKE :q
  )";
  $params[':q'] = '%' . $q . '%';
}

// ---------------------------
// Count total
// ---------------------------
$countSql = "
  SELECT COUNT(*) AS cnt
  FROM audit_logs a
  LEFT JOIN users u ON u.id = a.user_id
  $where
";
$countStmt = $pdo->prepare($countSql);
$countStmt->execute($params);
$total = (int)($countStmt->fetch()['cnt'] ?? 0);
$total_pages = max(1, (int)ceil($total / $per_page));

// Clamp page if too high
if ($page > $total_pages) {
  $page = $total_pages;
  $offset = ($page - 1) * $per_page;
}

// ---------------------------
// Fetch page rows
// ---------------------------
$listSql = "
  SELECT
    a.*,
    u.full_name,
    u.username,
    r.name AS role_name
  FROM audit_logs a
  LEFT JOIN users u ON u.id = a.user_id
  LEFT JOIN roles r ON r.id = u.role_id
  $where
  ORDER BY a.created_at DESC
  LIMIT :limit OFFSET :offset
";
$listStmt = $pdo->prepare($listSql);

// bind normal params
foreach ($params as $k => $v) {
  $listStmt->bindValue($k, $v);
}
// bind pagination params
$listStmt->bindValue(':limit', $per_page, PDO::PARAM_INT);
$listStmt->bindValue(':offset', $offset, PDO::PARAM_INT);

$listStmt->execute();
$rows = $listStmt->fetchAll();

// Build pagination URL with current filters
function build_query(array $overrides = []): string {
  $base = $_GET;
  foreach ($overrides as $k => $v) {
    if ($v === null || $v === '') unset($base[$k]);
    else $base[$k] = $v;
  }
  return http_build_query($base);
}

require_once __DIR__ . '/../templates/header.php';
require_once __DIR__ . '/../templates/sidebar.php';
?>

<main class="col-12 col-md-9 col-lg-10 p-3 p-md-4">
  <div class="d-flex flex-wrap gap-2 align-items-center justify-content-between mb-3">
    <h4 class="mb-0">Audit Logs</h4>

    <form class="d-flex gap-2" method="GET">
      <input class="form-control form-control-sm" name="q" placeholder="Search action/entity/user/details/ip..."
             value="<?= htmlspecialchars($q) ?>">
      <button class="btn btn-sm btn-outline-primary" type="submit">Search</button>
      <a class="btn btn-sm btn-outline-secondary" href="audit_logs.php">Reset</a>
    </form>
  </div>

  <div class="card shadow-sm mb-3">
    <div class="card-body">
      <form method="GET" class="row g-2 align-items-end">
        <div class="col-12 col-md-3">
          <label class="form-label mb-1">User</label>
          <select class="form-select form-select-sm" name="user_id">
            <option value="0">-- All --</option>
            <?php foreach ($users as $u): ?>
              <option value="<?= (int)$u['id'] ?>" <?= $user_id === (int)$u['id'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($u['full_name']) ?> (<?= htmlspecialchars($u['role_name']) ?>)
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-12 col-md-3">
          <label class="form-label mb-1">Action</label>
          <select class="form-select form-select-sm" name="action">
            <option value="">-- All --</option>
            <?php foreach ($actions as $a): ?>
              <?php $val = (string)$a['action']; ?>
              <option value="<?= htmlspecialchars($val) ?>" <?= $action === $val ? 'selected' : '' ?>>
                <?= htmlspecialchars($val) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-12 col-md-2">
          <label class="form-label mb-1">Entity</label>
          <select class="form-select form-select-sm" name="entity">
            <option value="">-- All --</option>
            <?php foreach ($entities as $e): ?>
              <?php $val = (string)$e['entity']; ?>
              <option value="<?= htmlspecialchars($val) ?>" <?= $entity === $val ? 'selected' : '' ?>>
                <?= htmlspecialchars($val) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-6 col-md-2">
          <label class="form-label mb-1">From</label>
          <input class="form-control form-control-sm" type="date" name="date_from"
                 value="<?= htmlspecialchars($date_from) ?>">
        </div>

        <div class="col-6 col-md-2">
          <label class="form-label mb-1">To</label>
          <input class="form-control form-control-sm" type="date" name="date_to"
                 value="<?= htmlspecialchars($date_to) ?>">
        </div>

        <div class="col-12">
          <button class="btn btn-sm btn-primary" type="submit">Apply Filters</button>
          <a class="btn btn-sm btn-outline-secondary" href="audit_logs.php">Clear</a>
        </div>
      </form>
    </div>
  </div>

  <div class="d-flex justify-content-between align-items-center mb-2">
    <div class="text-muted small">
      Showing <b><?= $total > 0 ? ($offset + 1) : 0 ?></b>–<b><?= min($offset + $per_page, $total) ?></b> of <b><?= $total ?></b>
    </div>
    <div class="text-muted small">
      Page <b><?= $page ?></b> / <b><?= $total_pages ?></b>
    </div>
  </div>

  <div class="card shadow-sm">
    <div class="card-body">
      <div class="table-responsive">
        <table class="table table-sm align-middle">
          <thead>
            <tr>
              <th style="width:170px;">Time</th>
              <th style="width:220px;">User</th>
              <th style="width:180px;">Action</th>
              <th style="width:150px;">Entity</th>
              <th style="width:120px;">Entity ID</th>
              <th style="width:160px;">IP</th>
              <th>Details</th>
            </tr>
          </thead>
          <tbody>
            <?php if (!$rows): ?>
              <tr><td colspan="7" class="text-muted">No audit logs found.</td></tr>
            <?php else: ?>
              <?php foreach ($rows as $i => $r): ?>
                <?php
                  $uid = $r['user_id'] ?? null;
                  $who = $uid ? (($r['full_name'] ?: $r['username']) . ' (' . ($r['role_name'] ?: '-') . ')') : 'System/Unknown';
                  $details = (string)($r['details'] ?? '');
                  $collapseId = "det_" . (int)$r['id'];
                ?>
                <tr>
                  <td class="text-muted"><?= htmlspecialchars($r['created_at']) ?></td>
                  <td><?= htmlspecialchars($who) ?></td>
                  <td><span class="badge text-bg-dark"><?= htmlspecialchars($r['action']) ?></span></td>
                  <td><?= htmlspecialchars($r['entity']) ?></td>
                  <td><?= htmlspecialchars((string)($r['entity_id'] ?? '-')) ?></td>
                  <td class="text-muted"><?= htmlspecialchars((string)($r['ip_address'] ?? '-')) ?></td>
                  <td>
                    <?php if ($details === ''): ?>
                      <span class="text-muted">-</span>
                    <?php else: ?>
                      <button class="btn btn-outline-secondary btn-sm" type="button"
                              data-bs-toggle="collapse" data-bs-target="#<?= $collapseId ?>">
                        View
                      </button>
                      <div class="collapse mt-2" id="<?= $collapseId ?>">
                        <pre class="small bg-light p-2 rounded mb-0" style="white-space:pre-wrap;"><?= htmlspecialchars($details) ?></pre>
                      </div>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <nav aria-label="Audit logs pages">
        <ul class="pagination pagination-sm mb-0">
          <?php
            $prev = max(1, $page - 1);
            $next = min($total_pages, $page + 1);
            $canPrev = $page > 1;
            $canNext = $page < $total_pages;
          ?>
          <li class="page-item <?= $canPrev ? '' : 'disabled' ?>">
            <a class="page-link" href="audit_logs.php?<?= build_query(['page' => $prev]) ?>">Prev</a>
          </li>

          <?php
            // show a compact range
            $start = max(1, $page - 2);
            $end   = min($total_pages, $page + 2);
            if ($start > 1) {
              echo '<li class="page-item"><a class="page-link" href="audit_logs.php?' . build_query(['page' => 1]) . '">1</a></li>';
              if ($start > 2) echo '<li class="page-item disabled"><span class="page-link">…</span></li>';
            }
            for ($p = $start; $p <= $end; $p++) {
              $active = ($p === $page) ? 'active' : '';
              echo '<li class="page-item ' . $active . '"><a class="page-link" href="audit_logs.php?' . build_query(['page' => $p]) . '">' . $p . '</a></li>';
            }
            if ($end < $total_pages) {
              if ($end < $total_pages - 1) echo '<li class="page-item disabled"><span class="page-link">…</span></li>';
              echo '<li class="page-item"><a class="page-link" href="audit_logs.php?' . build_query(['page' => $total_pages]) . '">' . $total_pages . '</a></li>';
            }
          ?>

          <li class="page-item <?= $canNext ? '' : 'disabled' ?>">
            <a class="page-link" href="audit_logs.php?<?= build_query(['page' => $next]) ?>">Next</a>
          </li>
        </ul>
      </nav>

    </div>
  </div>
</main>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
