<?php
// ============================================================
//  activity_log.php — Full Activity Log Viewer
//  Place in: /admin/activity_log.php
// ============================================================
require_once 'includes/auth_check.php';

$page_title = 'Activity Log';

// ── CSRF ──────────────────────────────────────────────────────
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

// ── Filters ───────────────────────────────────────────────────
$search       = trim($_GET['search']      ?? '');
$filter_admin = (int)($_GET['admin_id']   ?? 0);
$filter_type  = $_GET['target_type']      ?? '';
$per_page     = 25;
$current_page = max(1, (int)($_GET['page'] ?? 1));
$offset       = ($current_page - 1) * $per_page;

// ── Build WHERE ───────────────────────────────────────────────
$where  = [];
$params = [];

if ($search !== '') {
    $where[]  = '(al.action LIKE ? OR al.details LIKE ? OR al.target_name LIKE ? OR a.full_name LIKE ?)';
    $like     = "%{$search}%";
    $params   = array_merge($params, [$like, $like, $like, $like]);
}
if ($filter_admin > 0) {
    $where[]  = 'al.admin_id = ?';
    $params[] = $filter_admin;
}
if (in_array($filter_type, ['user','admin','system'])) {
    $where[]  = 'al.target_type = ?';
    $params[] = $filter_type;
}

$where_sql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

// ── Count ─────────────────────────────────────────────────────
$total = db_fetch_one(
    "SELECT COUNT(*) AS c FROM activity_log al
     JOIN admins a ON a.id = al.admin_id $where_sql",
    $params
)['c'] ?? 0;

$total_pages  = max(1, (int)ceil($total / $per_page));
$current_page = min($current_page, $total_pages);
$offset       = ($current_page - 1) * $per_page;

// ── Fetch logs ────────────────────────────────────────────────
$logs = db_fetch_all(
    "SELECT al.*, a.full_name AS admin_name, a.username AS admin_username, a.avatar AS admin_avatar
     FROM activity_log al
     JOIN admins a ON a.id = al.admin_id
     $where_sql
     ORDER BY al.created_at DESC
     LIMIT $per_page OFFSET $offset",
    $params
);

// ── All admins for filter dropdown ────────────────────────────
$all_admins = db_fetch_all("SELECT id, full_name FROM admins ORDER BY full_name ASC");

// ── Pagination url ────────────────────────────────────────────
function log_page_url(int $p): string {
    global $search, $filter_admin, $filter_type;
    return '?' . http_build_query(array_filter([
        'search'      => $search,
        'admin_id'    => $filter_admin ?: '',
        'target_type' => $filter_type,
        'page'        => $p,
    ]));
}

// ── Action icon/colour ────────────────────────────────────────
function log_icon(string $action): array {
    if (str_contains($action,'login'))    return ['fa-right-to-bracket',  'rgba(52,211,153,.15)',  '#34d399'];
    if (str_contains($action,'logout'))   return ['fa-right-from-bracket','rgba(248,113,113,.12)', '#f87171'];
    if (str_contains($action,'delete'))   return ['fa-trash',             'rgba(248,113,113,.12)', '#f87171'];
    if (str_contains($action,'password')) return ['fa-key',               'rgba(251,191,36,.12)',  '#fbbf24'];
    if (str_contains($action,'avatar'))   return ['fa-image',             'rgba(45,212,191,.12)',  '#2dd4bf'];
    if (str_contains($action,'export'))   return ['fa-file-arrow-down',   'rgba(56,189,248,.12)',  '#38bdf8'];
    if (str_contains($action,'setting'))  return ['fa-sliders',           'rgba(167,139,250,.12)', '#a78bfa'];
    if (str_contains($action,'ban'))      return ['fa-ban',               'rgba(248,113,113,.12)', '#f87171'];
    if (str_contains($action,'status'))   return ['fa-toggle-on',         'rgba(108,99,255,.12)',  '#6c63ff'];
    if (str_contains($action,'create'))   return ['fa-circle-plus',       'rgba(52,211,153,.12)',  '#34d399'];
    if (str_contains($action,'edit'))     return ['fa-pen-to-square',     'rgba(108,99,255,.12)',  '#a78bfa'];
    return ['fa-circle-dot', 'rgba(255,255,255,.06)', '#8a8aab'];
}

require_once 'includes/header.php';
?>

<style>
.log-toolbar {
  display: flex; gap: 10px; flex-wrap: wrap;
  padding: 16px 20px;
  border-bottom: 1px solid var(--glass-border);
}

.log-table .log-action-icon {
  width: 32px; height: 32px;
  border-radius: 9px;
  display: grid; place-items: center;
  font-size: 12px;
  flex-shrink: 0;
}

.log-admin-cell {
  display: flex; align-items: center; gap: 9px;
}

.log-admin-cell img {
  width: 28px; height: 28px;
  border-radius: 50%;
  object-fit: cover;
  border: 1.5px solid var(--glass-border);
  flex-shrink: 0;
}

.log-type-badge {
  display: inline-flex;
  align-items: center;
  padding: 2px 9px;
  border-radius: 20px;
  font-size: 10.5px;
  font-weight: 700;
  letter-spacing: .3px;
  text-transform: capitalize;
}

.type-user   { background:rgba(108,99,255,.12); border:1px solid rgba(108,99,255,.25); color:var(--accent-2); }
.type-admin  { background:rgba(244,114,182,.1);  border:1px solid rgba(244,114,182,.25); color:var(--pink); }
.type-system { background:rgba(56,189,248,.1);   border:1px solid rgba(56,189,248,.25);  color:var(--info); }

.log-empty {
  text-align: center; padding: 60px 20px;
}
.log-empty i { font-size: 38px; opacity: .2; display: block; margin-bottom: 14px; color: var(--text-muted); }
.log-empty h3{ font-family:'Syne',sans-serif; font-size:18px; color:var(--text-secondary); }

@media (max-width: 768px) {
  .col-type, .col-ip, .col-target { display: none; }
}
</style>

<!-- Page Header -->
<div class="page-header">
  <div class="page-header-left">
    <h1>Activity <span style="color:var(--accent-2)">Log</span></h1>
    <p><?= number_format($total) ?> total action<?= $total !== 1 ? 's' : '' ?> recorded</p>
  </div>
  <div class="page-header-right">
    <?php if ($current_admin['role'] === 'super_admin'): ?>
      <a href="clear_log.php?csrf=<?= urlencode($csrf) ?>"
         class="btn btn-danger btn-sm"
         onclick="return confirm('PERMANENTLY delete ALL log entries? This cannot be undone.')">
        <i class="fas fa-trash"></i> Clear Log
      </a>
    <?php endif; ?>
  </div>
</div>

<div class="glass-card" style="padding:0;overflow:hidden;animation:fadeUp .5s ease both;">

  <!-- Toolbar / Filters -->
  <form method="GET" action="activity_log.php">
    <div class="log-toolbar">

      <!-- Search -->
      <div class="search-box" style="max-width:300px;flex:1;">
        <i class="fas fa-magnifying-glass"></i>
        <input type="text" name="search" placeholder="Search actions, details, admin…"
               value="<?= htmlspecialchars($search) ?>" id="logSearch" />
      </div>

      <!-- Admin filter -->
      <select name="admin_id" class="form-control" style="width:auto;height:38px;font-size:13px;"
              onchange="this.form.submit()">
        <option value="">All Admins</option>
        <?php foreach ($all_admins as $adm): ?>
          <option value="<?= $adm['id'] ?>" <?= $filter_admin === $adm['id'] ? 'selected' : '' ?>>
            <?= htmlspecialchars($adm['full_name']) ?>
          </option>
        <?php endforeach; ?>
      </select>

      <!-- Type filter -->
      <select name="target_type" class="form-control" style="width:auto;height:38px;font-size:13px;"
              onchange="this.form.submit()">
        <option value="">All Types</option>
        <option value="user"   <?= $filter_type==='user'   ? 'selected':'' ?>>User</option>
        <option value="admin"  <?= $filter_type==='admin'  ? 'selected':'' ?>>Admin</option>
        <option value="system" <?= $filter_type==='system' ? 'selected':'' ?>>System</option>
      </select>

      <?php if ($search || $filter_admin || $filter_type): ?>
        <a href="activity_log.php" class="btn btn-glass btn-sm">
          <i class="fas fa-xmark"></i> Clear
        </a>
      <?php endif; ?>

      <button type="submit" class="btn btn-primary btn-sm">
        <i class="fas fa-magnifying-glass"></i> Search
      </button>
    </div>
  </form>

  <!-- Table -->
  <div class="table-wrap" style="border:none;border-radius:0;">
    <table class="admin-table log-table">
      <thead>
        <tr>
          <th style="width:42px;"></th>
          <th>Action</th>
          <th>Admin</th>
          <th class="col-target">Target</th>
          <th class="col-type">Type</th>
          <th class="col-ip">IP Address</th>
          <th>Time</th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($logs)): ?>
          <tr>
            <td colspan="7">
              <div class="log-empty">
                <i class="fas fa-clock-rotate-left"></i>
                <h3><?= $search || $filter_admin || $filter_type ? 'No matching log entries' : 'No activity recorded yet' ?></h3>
              </div>
            </td>
          </tr>
        <?php else: foreach ($logs as $log):
          [$icon, $bg, $color] = log_icon($log['action']);
        ?>
          <tr>
            <td>
              <div class="log-action-icon" style="background:<?= $bg ?>;color:<?= $color ?>;">
                <i class="fas <?= $icon ?>"></i>
              </div>
            </td>
            <td>
              <div style="font-size:13px;font-weight:600;color:var(--text-primary);">
                <?= htmlspecialchars(ucwords(str_replace('_',' ', $log['action']))) ?>
              </div>
              <?php if ($log['details']): ?>
                <div style="font-size:11.5px;color:var(--text-muted);margin-top:2px;max-width:320px;
                            white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"
                     title="<?= htmlspecialchars($log['details']) ?>">
                  <?= htmlspecialchars($log['details']) ?>
                </div>
              <?php endif; ?>
            </td>
            <td>
              <div class="log-admin-cell">
                <img src="assets/images/avatars/<?= htmlspecialchars($log['admin_avatar'] ?? 'logo.png') ?>"
                     onerror="this.src='assets/images/logo.png'"
                     alt="" />
                <div>
                  <div style="font-size:13px;font-weight:600;color:var(--text-primary);">
                    <?= htmlspecialchars($log['admin_name']) ?>
                  </div>
                  <div style="font-size:11px;color:var(--text-muted);">
                    @<?= htmlspecialchars($log['admin_username']) ?>
                  </div>
                </div>
              </div>
            </td>
            <td class="col-target" style="font-size:12.5px;color:var(--text-secondary);">
              <?php if ($log['target_name']): ?>
                <div style="font-weight:600;color:var(--text-primary);"><?= htmlspecialchars($log['target_name']) ?></div>
              <?php endif; ?>
              <?php if ($log['target_id']): ?>
                <div style="font-size:11px;color:var(--text-muted);">ID #<?= $log['target_id'] ?></div>
              <?php endif; ?>
              <?php if (!$log['target_name'] && !$log['target_id']): ?>
                <span class="text-muted">—</span>
              <?php endif; ?>
            </td>
            <td class="col-type">
              <span class="log-type-badge type-<?= $log['target_type'] ?>">
                <?= ucfirst($log['target_type']) ?>
              </span>
            </td>
            <td class="col-ip" style="font-size:12px;color:var(--text-muted);font-family:monospace;">
              <?= $log['ip_address'] ? htmlspecialchars($log['ip_address']) : '—' ?>
            </td>
            <td style="font-size:12px;color:var(--text-muted);white-space:nowrap;">
              <div><?= date('d M Y', strtotime($log['created_at'])) ?></div>
              <div style="color:var(--text-secondary);font-weight:600;"><?= date('H:i:s', strtotime($log['created_at'])) ?></div>
            </td>
          </tr>
        <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>

  <!-- Pagination -->
  <?php if ($total_pages > 1 || $total > 0): ?>
  <div class="pagination-wrap">
    <div class="pagination-info">
      Showing <strong><?= number_format($offset+1) ?>–<?= number_format(min($offset+$per_page,$total)) ?></strong>
      of <strong><?= number_format($total) ?></strong> entries
    </div>
    <div class="pagination">
      <?php if ($current_page > 1): ?>
        <a href="<?= log_page_url(1) ?>" class="page-link"><i class="fas fa-angles-left"></i></a>
        <a href="<?= log_page_url($current_page-1) ?>" class="page-link"><i class="fas fa-angle-left"></i></a>
      <?php endif; ?>
      <?php
      $start = max(1, $current_page-2);
      $end   = min($total_pages, $current_page+2);
      for ($i = $start; $i <= $end; $i++): ?>
        <a href="<?= log_page_url($i) ?>" class="page-link <?= $i===$current_page?'active':'' ?>"><?= $i ?></a>
      <?php endfor; ?>
      <?php if ($current_page < $total_pages): ?>
        <a href="<?= log_page_url($current_page+1) ?>" class="page-link"><i class="fas fa-angle-right"></i></a>
        <a href="<?= log_page_url($total_pages) ?>" class="page-link"><i class="fas fa-angles-right"></i></a>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>

</div>

<?php require_once 'includes/footer.php'; ?>
