<?php
// ============================================================
//  users.php — All Users List
//  Place in: /admin/users.php
// ============================================================
require_once 'includes/auth_check.php';

$page_title = 'User Management';

// ── Flash messages from redirects ─────────────────────────────
$flash_success = $_SESSION['flash_success'] ?? '';
$flash_error   = $_SESSION['flash_error']   ?? '';
unset($_SESSION['flash_success'], $_SESSION['flash_error']);

// ── Handle bulk actions (POST) ───────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['bulk_action'])) {

    if (empty($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['flash_error'] = 'Invalid request token.';
        header('Location: users.php');
        exit;
    }

    $bulk_action  = $_POST['bulk_action'];
    $selected_ids = array_map('intval', $_POST['selected_ids'] ?? []);

    if (!empty($selected_ids)) {
        $placeholders = implode(',', array_fill(0, count($selected_ids), '?'));

        $allowed_statuses = ['active', 'inactive', 'banned'];

        if (in_array($bulk_action, $allowed_statuses)) {
            db_execute(
                "UPDATE users SET status = ? WHERE id IN ($placeholders)",
                array_merge([$bulk_action], $selected_ids)
            );
            db_execute(
                "INSERT INTO activity_log (admin_id, action, target_type, details, ip_address)
                 VALUES (?, ?, 'user', ?, ?)",
                [
                    $current_admin['id'],
                    'bulk_status_change',
                    "Set " . count($selected_ids) . " user(s) to {$bulk_action}",
                    $_SERVER['REMOTE_ADDR']
                ]
            );
            $_SESSION['flash_success'] = count($selected_ids) . ' user(s) updated to ' . ucfirst($bulk_action) . '.';

        } elseif ($bulk_action === 'delete') {
            // Get names for logging
            $names = db_fetch_all("SELECT full_name FROM users WHERE id IN ($placeholders)", $selected_ids);
            $name_list = implode(', ', array_column($names, 'full_name'));

            db_execute("DELETE FROM users WHERE id IN ($placeholders)", $selected_ids);
            db_execute(
                "INSERT INTO activity_log (admin_id, action, target_type, details, ip_address)
                 VALUES (?, 'bulk_delete_users', 'user', ?, ?)",
                [$current_admin['id'], "Deleted: {$name_list}", $_SERVER['REMOTE_ADDR']]
            );
            $_SESSION['flash_success'] = count($selected_ids) . ' user(s) permanently deleted.';
        }
    }

    header('Location: users.php?' . http_build_query(array_filter([
        'search' => $_POST['search'] ?? '',
        'status' => $_POST['status_filter'] ?? '',
        'page'   => $_POST['current_page'] ?? 1,
    ])));
    exit;
}

// ── Query params ─────────────────────────────────────────────
$search        = trim($_GET['search'] ?? '');
$status_filter = $_GET['status'] ?? '';
$sort_by       = in_array($_GET['sort'] ?? '', ['id','full_name','email','created_at','last_login','status'])
                 ? $_GET['sort'] : 'created_at';
$sort_dir      = strtoupper($_GET['dir'] ?? 'DESC') === 'ASC' ? 'ASC' : 'DESC';
$per_page      = 15;
$current_page  = max(1, (int)($_GET['page'] ?? 1));
$offset        = ($current_page - 1) * $per_page;

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

if ($search !== '') {
    $where[]  = '(full_name LIKE ? OR username LIKE ? OR email LIKE ?)';
    $like     = "%{$search}%";
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}

if ($status_filter !== '') {
    $where[]  = 'status = ?';
    $params[] = $status_filter;
}

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

// ── Count total for pagination ───────────────────────────────
$total_count = db_fetch_one(
    "SELECT COUNT(*) AS c FROM users $where_sql", $params
)['c'] ?? 0;

$total_pages = max(1, (int)ceil($total_count / $per_page));
$current_page = min($current_page, $total_pages);

// ── Fetch users ──────────────────────────────────────────────
$users = db_fetch_all(
    "SELECT id, full_name, username, email, avatar, status,
            email_verified, phone, last_login, created_at
     FROM users
     $where_sql
     ORDER BY $sort_by $sort_dir
     LIMIT $per_page OFFSET $offset",
    $params
);

// ── Status counts for filter tabs ───────────────────────────
$status_counts = [];
foreach (['active','inactive','banned','pending'] as $s) {
    $status_counts[$s] = db_fetch_one(
        "SELECT COUNT(*) AS c FROM users WHERE status = ?", [$s]
    )['c'] ?? 0;
}
$total_all = db_fetch_one("SELECT COUNT(*) AS c FROM users")['c'] ?? 0;

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

// ── Sort helper ──────────────────────────────────────────────
function sort_url(string $col): string {
    global $sort_by, $sort_dir, $search, $status_filter, $current_page;
    $dir = ($sort_by === $col && $sort_dir === 'ASC') ? 'DESC' : 'ASC';
    return '?' . http_build_query(array_filter([
        'search' => $search,
        'status' => $status_filter,
        'sort'   => $col,
        'dir'    => $dir,
        'page'   => $current_page,
    ]));
}

function sort_icon(string $col): string {
    global $sort_by, $sort_dir;
    if ($sort_by !== $col) return '<i class="fas fa-sort sort-icon inactive"></i>';
    return $sort_dir === 'ASC'
        ? '<i class="fas fa-sort-up sort-icon active"></i>'
        : '<i class="fas fa-sort-down sort-icon active"></i>';
}

// ── Pagination URL helper ────────────────────────────────────
function page_url(int $p): string {
    global $search, $status_filter, $sort_by, $sort_dir;
    return '?' . http_build_query(array_filter([
        'search' => $search,
        'status' => $status_filter,
        'sort'   => $sort_by,
        'dir'    => $sort_dir,
        'page'   => $p,
    ]));
}

require_once 'includes/header.php';
?>

<!-- ── Page Styles ──────────────────────────────────────────── -->
<style>
.filter-tabs        { display:flex; gap:8px; flex-wrap:wrap; margin-bottom:22px; }
.filter-tab         { display:flex; align-items:center; gap:7px; padding:7px 14px; border-radius:30px;
                      font-size:12.5px; font-weight:600; border:1px solid var(--glass-border);
                      background:var(--glass-bg); color:var(--text-secondary); cursor:pointer;
                      text-decoration:none; transition:all var(--transition); }
.filter-tab:hover   { background:var(--glass-bg-hover); color:var(--text-primary); }
.filter-tab.active  { background:rgba(108,99,255,0.18); border-color:rgba(205, 162, 19, 0.8);
                      color:var(--accent-2); }
.filter-tab .fc     { background:rgba(255,255,255,0.1); border-radius:20px; padding:1px 7px;
                      font-size:11px; }
.filter-tab.active .fc { background:rgba(108,99,255,0.3); }

.toolbar            { display:flex; align-items:center; gap:10px; flex-wrap:wrap;
                      padding:16px 20px; border-bottom:1px solid var(--glass-border); }
.search-box         { display:flex; align-items:center; gap:8px; background:var(--glass-bg);
                      border:1px solid var(--glass-border); border-radius:var(--radius-sm);
                      padding:0 14px; height:38px; flex:1; min-width:200px; max-width:340px;
                      transition:all var(--transition); }
.search-box:focus-within { border-color:var(--accent); background:rgba(108,99,255,0.07);
                           box-shadow:0 0 0 3px var(--accent-glow); }
.search-box i       { color:var(--text-muted); font-size:13px; flex-shrink:0; }
.search-box input   { background:none; border:none; outline:none; color:var(--text-primary);
                      font-family:'DM Sans',sans-serif; font-size:13.5px; width:100%; }
.search-box input::placeholder { color:var(--text-muted); }

.toolbar-spacer     { flex:1; }

.bulk-bar           { display:none; align-items:center; gap:10px; padding:10px 20px;
                      background:rgba(108,99,255,0.1); border-bottom:1px solid rgba(108,99,255,0.2); }
.bulk-bar.show      { display:flex; }
.bulk-count         { font-size:13px; font-weight:600; color:var(--accent-2); }

.sort-icon          { margin-left:5px; font-size:10px; }
.sort-icon.inactive { color:var(--text-muted); }
.sort-icon.active   { color:var(--accent-2); }
th a                { color:inherit; text-decoration:none; display:flex; align-items:center; }

.user-cell          { display:flex; align-items:center; gap:12px; }
.user-cell-info strong { font-size:13.5px; font-weight:600; color:var(--text-primary); display:block; }
.user-cell-info span   { font-size:11px; color:var(--text-muted); }

.action-btns        { display:flex; gap:5px; }

.empty-state        { text-align:center; padding:60px 20px; }
.empty-state i      { font-size:40px; color:var(--text-muted); opacity:0.3; margin-bottom:14px; display:block; }
.empty-state h3     { font-family:'Syne',sans-serif; font-size:18px; color:var(--text-secondary); }
.empty-state p      { font-size:13px; color:var(--text-muted); margin-top:6px; }

.pagination-wrap    { display:flex; align-items:center; justify-content:space-between;
                      padding:16px 20px; border-top:1px solid var(--glass-border); flex-wrap:wrap; gap:12px; }
.pagination-info    { font-size:12.5px; color:var(--text-muted); }

/* Checkbox custom */
.cb { appearance:none; -webkit-appearance:none; width:16px; height:16px;
      border:1.5px solid var(--glass-border); border-radius:5px; background:var(--glass-bg);
      cursor:pointer; display:grid; place-items:center; transition:all 0.2s; flex-shrink:0; }
.cb:checked { background:var(--accent); border-color:var(--accent); }
.cb:checked::before { content:''; width:9px; height:9px;
  background:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12'%3E%3Cpath d='M2 6l3 3 5-5' stroke='white' stroke-width='2' fill='none' stroke-linecap='round'/%3E%3C/svg%3E") center/contain no-repeat; }

/* Verified icon */
.verified-yes { color:var(--success); font-size:13px; }
.verified-no  { color:var(--text-muted); font-size:13px; }

@media (max-width:768px) {
  .toolbar { flex-wrap:wrap; }
  .search-box { max-width:100%; }
  .col-phone, .col-verified, .col-last-login { display:none; }
}
</style>

<!-- ── Flash Messages ──────────────────────────────────────── -->
<?php if ($flash_success): ?>
  <div class="flash-alert flash-success">
    <i class="fas fa-circle-check"></i>
    <span><?= htmlspecialchars($flash_success) ?></span>
  </div>
<?php endif; ?>
<?php if ($flash_error): ?>
  <div class="flash-alert flash-error">
    <i class="fas fa-circle-exclamation"></i>
    <span><?= htmlspecialchars($flash_error) ?></span>
  </div>
<?php endif; ?>

<!-- ── Page Header ─────────────────────────────────────────── -->
<div class="page-header">
  <div class="page-header-left">
    <h1>User <span style="color:#F48340">Management</span></h1>
    <p><?= number_format($total_all) ?> total registered users in the system</p>
  </div>
  <div class="page-header-right">
    <a href="users.php" class="btn btn-glass btn-sm">
      <i class="fas fa-rotate"></i> Refresh
    </a>
    <a href="export_users.php<?= $search || $status_filter ? '?search='.urlencode($search).'&status='.urlencode($status_filter) : '' ?>" class="btn btn-glass btn-sm">
      <i class="fas fa-file-arrow-down"></i> Export CSV
    </a>
  </div>
</div>

<!-- ── Filter Tabs ─────────────────────────────────────────── -->
<div class="filter-tabs">
  <a href="users.php" class="filter-tab <?= $status_filter === '' ? 'active' : '' ?>">
    <i class="fas fa-users"></i> All <span class="fc"><?= $total_all ?></span>
  </a>
  <a href="?status=active" class="filter-tab <?= $status_filter === 'active' ? 'active' : '' ?>">
    <i class="fas fa-circle-check" style="color:var(--success)"></i> Active <span class="fc"><?= $status_counts['active'] ?></span>
  </a>
  <a href="?status=inactive" class="filter-tab <?= $status_filter === 'inactive' ? 'active' : '' ?>">
    <i class="fas fa-circle-minus" style="color:var(--text-muted)"></i> Inactive <span class="fc"><?= $status_counts['inactive'] ?></span>
  </a>
  <a href="?status=pending" class="filter-tab <?= $status_filter === 'pending' ? 'active' : '' ?>">
    <i class="fas fa-clock" style="color:var(--warning)"></i> Pending <span class="fc"><?= $status_counts['pending'] ?></span>
  </a>
  <a href="?status=banned" class="filter-tab <?= $status_filter === 'banned' ? 'active' : '' ?>">
    <i class="fas fa-ban" style="color:var(--danger)"></i> Banned <span class="fc"><?= $status_counts['banned'] ?></span>
  </a>
</div>

<!-- ── Main Users Table Card ───────────────────────────────── -->
<div class="glass-card" style="padding:0;overflow:hidden;animation:fadeUp 0.5s ease both;">

  <form method="POST" action="users.php" id="bulkForm">
    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf_token) ?>" />
    <input type="hidden" name="search" value="<?= htmlspecialchars($search) ?>" />
    <input type="hidden" name="status_filter" value="<?= htmlspecialchars($status_filter) ?>" />
    <input type="hidden" name="current_page" value="<?= $current_page ?>" />
    <input type="hidden" name="bulk_action" id="bulkActionInput" value="" />

    <!-- Toolbar -->
    <div class="toolbar">
      <!-- Search -->
      <form method="GET" action="users.php" style="display:contents;">
        <?php if ($status_filter): ?>
          <input type="hidden" name="status" value="<?= htmlspecialchars($status_filter) ?>" />
        <?php endif; ?>
        <div class="search-box">
          <i class="fas fa-magnifying-glass"></i>
          <input type="text" name="search" placeholder="Search by name, email or username…"
                 value="<?= htmlspecialchars($search) ?>" id="searchInput" />
        </div>
        <?php if ($search): ?>
          <a href="?<?= $status_filter ? 'status='.urlencode($status_filter) : '' ?>" class="btn btn-glass btn-sm">
            <i class="fas fa-xmark"></i> Clear
          </a>
        <?php endif; ?>
      </form>

      <div class="toolbar-spacer"></div>

      <!-- Sort select -->
      <select class="form-control" style="width:auto;height:38px;font-size:13px;"
              onchange="window.location='?sort='+this.value+'&dir=<?= $sort_dir ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status_filter) ?>'">
        <option value="created_at" <?= $sort_by==='created_at'?'selected':'' ?>>Sort: Joined</option>
        <option value="full_name"  <?= $sort_by==='full_name' ?'selected':'' ?>>Sort: Name</option>
        <option value="email"      <?= $sort_by==='email'     ?'selected':'' ?>>Sort: Email</option>
        <option value="status"     <?= $sort_by==='status'    ?'selected':'' ?>>Sort: Status</option>
        <option value="last_login" <?= $sort_by==='last_login'?'selected':'' ?>>Sort: Last Login</option>
      </select>

      <a href="<?= sort_url($sort_by) ?>" class="btn btn-glass btn-sm btn-icon" title="Toggle direction">
        <i class="fas fa-arrow-<?= $sort_dir==='ASC' ? 'up' : 'down' ?>"></i>
      </a>
    </div>

    <!-- Bulk action bar (shows when rows selected) -->
    <div class="bulk-bar" id="bulkBar">
      <i class="fas fa-check-square" style="color:#F48340"></i>
      <span class="bulk-count" id="bulkCount">0</span> <span style="font-size:13px;color:var(--text-secondary)">users selected</span>
      <div style="display:flex;gap:6px;margin-left:8px;">
        <button type="button" onclick="bulkAction('active')" class="btn btn-success btn-sm">
          <i class="fas fa-circle-check"></i> Set Active
        </button>
        <button type="button" onclick="bulkAction('inactive')" class="btn btn-glass btn-sm">
          <i class="fas fa-circle-minus"></i> Set Inactive
        </button>
        <button type="button" onclick="bulkAction('banned')" class="btn btn-danger btn-sm">
          <i class="fas fa-ban"></i> Ban
        </button>
        <button type="button" onclick="bulkAction('delete')" class="btn btn-danger btn-sm">
          <i class="fas fa-trash"></i> Delete
        </button>
      </div>
      <button type="button" onclick="clearSelection()" class="btn btn-glass btn-sm btn-icon" style="margin-left:auto;" title="Clear selection">
        <i class="fas fa-xmark"></i>
      </button>
    </div>

    <!-- Table -->
    <div class="table-wrap" style="border:none;border-radius:0;">
      <table class="admin-table" id="usersTable">
        <thead>
          <tr>
            <th style="width:44px;">
              <input type="checkbox" class="cb" id="selectAll" title="Select all" />
            </th>
            <th><a href="<?= sort_url('full_name') ?>">User <?= sort_icon('full_name') ?></a></th>
            <th><a href="<?= sort_url('email') ?>">Email <?= sort_icon('email') ?></a></th>
            <th class="col-phone">Phone</th>
            <th class="col-verified">Verified</th>
            <th><a href="<?= sort_url('status') ?>">Status <?= sort_icon('status') ?></a></th>
            <th class="col-last-login"><a href="<?= sort_url('last_login') ?>">Last Login <?= sort_icon('last_login') ?></a></th>
            <th><a href="<?= sort_url('created_at') ?>">Joined <?= sort_icon('created_at') ?></a></th>
            <th style="width:120px;text-align:center;">Actions</th>
          </tr>
        </thead>
        <tbody>

          <?php if (empty($users)): ?>
            <tr>
              <td colspan="9">
                <div class="empty-state">
                  <i class="fas fa-users-slash"></i>
                  <h3>No users found</h3>
                  <p>
                    <?= $search
                        ? 'No results for "' . htmlspecialchars($search) . '". Try a different search.'
                        : 'No ' . ($status_filter ? $status_filter . ' ' : '') . 'users in the system yet.' ?>
                  </p>
                  <?php if ($search || $status_filter): ?>
                    <a href="users.php" class="btn btn-glass btn-sm" style="margin-top:16px;display:inline-flex;">
                      <i class="fas fa-rotate"></i> Clear filters
                    </a>
                  <?php endif; ?>
                </div>
              </td>
            </tr>

          <?php else: foreach ($users as $u): ?>
            <tr>
              <td>
                <input type="checkbox" name="selected_ids[]" value="<?= $u['id'] ?>"
                       class="cb row-cb" />
              </td>
              <td>
                <div class="user-cell">
                  <img src="assets/images/avatars/<?= htmlspecialchars($u['avatar'] ?? 'Avatar.png') ?>"
                       onerror="this.src='assets/images/Avatar.png'"
                       class="avatar avatar-sm" alt="" />
                  <div class="user-cell-info">
                    <strong><?= htmlspecialchars($u['full_name']) ?></strong>
                    <span>@<?= htmlspecialchars($u['username']) ?></span>
                  </div>
                </div>
              </td>
              <td style="font-size:13px;color:var(--text-secondary);">
                <?= htmlspecialchars($u['email']) ?>
              </td>
              <td class="col-phone" style="font-size:13px;color:var(--text-secondary);">
                <?= $u['phone'] ? htmlspecialchars($u['phone']) : '<span class="text-muted">—</span>' ?>
              </td>
              <td class="col-verified">
                <?php if ($u['email_verified']): ?>
                  <i class="fas fa-circle-check verified-yes" title="Email verified"></i>
                <?php else: ?>
                  <i class="fas fa-circle-xmark verified-no" title="Not verified"></i>
                <?php endif; ?>
              </td>
              <td>
                <span class="badge badge-<?= htmlspecialchars($u['status']) ?>">
                  <?= ucfirst($u['status']) ?>
                </span>
              </td>
              <td class="col-last-login" style="font-size:12px;color:var(--text-muted);">
                <?= $u['last_login']
                    ? date('d M Y, H:i', strtotime($u['last_login']))
                    : '<span style="color:var(--text-muted)">Never</span>' ?>
              </td>
              <td style="font-size:12px;color:var(--text-muted);">
                <?= date('d M Y', strtotime($u['created_at'])) ?>
              </td>
              <td>
                <div class="action-btns" style="justify-content:center;">
                  <a href="user_view.php?id=<?= $u['id'] ?>" class="btn btn-glass btn-sm btn-icon" title="View Profile">
                    <i class="fas fa-eye"></i>
                  </a>
                  <a href="user_edit.php?id=<?= $u['id'] ?>" class="btn btn-glass btn-sm btn-icon" title="Edit User">
                    <i class="fas fa-pen-to-square"></i>
                  </a>
                  <a href="user_delete.php?id=<?= $u['id'] ?>&csrf=<?= urlencode($csrf_token) ?>"
                     class="btn btn-danger btn-sm btn-icon"
                     title="Delete User"
                     onclick="return confirm('Permanently delete <?= addslashes(htmlspecialchars($u['full_name'])) ?>? This cannot be undone.')">
                    <i class="fas fa-trash"></i>
                  </a>
                </div>
              </td>
            </tr>
          <?php endforeach; endif; ?>

        </tbody>
      </table>
    </div>

    <!-- Pagination -->
    <?php if ($total_pages > 1 || $total_count > 0): ?>
    <div class="pagination-wrap">
      <div class="pagination-info">
        Showing <strong><?= number_format($offset + 1) ?>–<?= number_format(min($offset + $per_page, $total_count)) ?></strong>
        of <strong><?= number_format($total_count) ?></strong> users
        <?= $search ? ' for <em>"' . htmlspecialchars($search) . '"</em>' : '' ?>
      </div>

      <div class="pagination">
        <?php if ($current_page > 1): ?>
          <a href="<?= page_url(1) ?>" class="page-link" title="First"><i class="fas fa-angles-left"></i></a>
          <a href="<?= page_url($current_page - 1) ?>" class="page-link" title="Previous"><i class="fas fa-angle-left"></i></a>
        <?php endif; ?>

        <?php
        $range = 2;
        $start = max(1, $current_page - $range);
        $end   = min($total_pages, $current_page + $range);
        if ($start > 1) echo '<span class="page-link" style="border:none;background:none;color:var(--text-muted);">…</span>';
        for ($i = $start; $i <= $end; $i++): ?>
          <a href="<?= page_url($i) ?>" class="page-link <?= $i === $current_page ? 'active' : '' ?>">
            <?= $i ?>
          </a>
        <?php endfor;
        if ($end < $total_pages) echo '<span class="page-link" style="border:none;background:none;color:var(--text-muted);">…</span>';
        ?>

        <?php if ($current_page < $total_pages): ?>
          <a href="<?= page_url($current_page + 1) ?>" class="page-link" title="Next"><i class="fas fa-angle-right"></i></a>
          <a href="<?= page_url($total_pages) ?>" class="page-link" title="Last"><i class="fas fa-angles-right"></i></a>
        <?php endif; ?>
      </div>
    </div>
    <?php endif; ?>

  </form><!-- /#bulkForm -->
</div><!-- /.glass-card -->

<?php
$extra_scripts = <<<JS
<script>
// ── Select All ──────────────────────────────────────────────
const selectAll = document.getElementById('selectAll');
const rowCbs    = document.querySelectorAll('.row-cb');
const bulkBar   = document.getElementById('bulkBar');
const bulkCount = document.getElementById('bulkCount');

function updateBulkBar() {
  const checked = document.querySelectorAll('.row-cb:checked');
  const n = checked.length;
  bulkCount.textContent = n;
  bulkBar.classList.toggle('show', n > 0);
  selectAll.indeterminate = n > 0 && n < rowCbs.length;
  selectAll.checked = n === rowCbs.length && n > 0;
}

selectAll.addEventListener('change', () => {
  rowCbs.forEach(cb => cb.checked = selectAll.checked);
  updateBulkBar();
});

rowCbs.forEach(cb => cb.addEventListener('change', updateBulkBar));

function bulkAction(action) {
  const checked = document.querySelectorAll('.row-cb:checked');
  if (checked.length === 0) return;
  const confirmMsgs = {
    delete:   `Permanently delete \${checked.length} user(s)? This cannot be undone.`,
    banned:   `Ban \${checked.length} user(s)?`,
    inactive: `Deactivate \${checked.length} user(s)?`,
    active:   `Activate \${checked.length} user(s)?`,
  };
  if (!confirm(confirmMsgs[action] || 'Apply action to selected users?')) return;
  document.getElementById('bulkActionInput').value = action;
  document.getElementById('bulkForm').submit();
}

function clearSelection() {
  rowCbs.forEach(cb => cb.checked = false);
  selectAll.checked = false;
  updateBulkBar();
}

// ── Live search (debounced) ─────────────────────────────────
const searchInput = document.getElementById('searchInput');
let searchTimer;
searchInput?.addEventListener('input', () => {
  clearTimeout(searchTimer);
  searchTimer = setTimeout(() => {
    searchInput.closest('form').submit();
  }, 500);
});

// ── Row hover highlight ─────────────────────────────────────
document.querySelectorAll('#usersTable tbody tr').forEach(row => {
  row.addEventListener('click', function(e) {
    if (e.target.closest('a,button,input')) return;
    const cb = this.querySelector('.row-cb');
    if (cb) { cb.checked = !cb.checked; updateBulkBar(); }
  });
});
</script>
JS;

require_once 'includes/footer.php';
?>
