<?php
require_once __DIR__ . '/../config.php';
adminGuard();
requireCsrf();  // reject POSTs without a valid CSRF token
require_once __DIR__ . '/_layout.php';
require_once BASE_PATH . '/lib/qr_invite.php';

$db      = db();
$eventId = (int)($_GET['event_id'] ?? $_POST['event_id'] ?? 0);
$msg     = '';
$error   = '';

// Load event
$stmtEv = $db->prepare('SELECT * FROM events WHERE id=? AND admin_id=?');
$stmtEv->execute([$eventId, $_SESSION['admin_id']]);
$event = $stmtEv->fetch();
if (!$event) { header('Location: ' . BASE_URL . '/admin/events.php'); exit; }

// ── Load admin limits ────────────────────────────────────────
$adminData = $db->prepare('SELECT * FROM admins WHERE id=?');
$adminData->execute([$_SESSION['admin_id']]);
$limits = planLimits($adminData->fetch());
$maxGuests = $limits['max_guests']; // null = unlimited

// ── Handle CSV upload ────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_guests'])) {
    if (empty($_FILES['csv_file']['name'])) {
        $error = 'Please select a CSV file.';
    } else {
        $allowDuplicates = isset($_POST['allow_duplicates']);
        $file = $_FILES['csv_file']['tmp_name'];
        $handle = fopen($file, 'r');
        $headers = array_map('strtolower', array_map('trim', fgetcsv($handle)));

        $col = fn(string $k) => array_search($k, $headers);
        $nameIdx  = $col('name');
        $emailIdx = $col('email');
        $phoneIdx = $col('phone');
        $tableIdx = $col('table');
        $seatIdx  = $col('seat');
        $catIdx   = $col('category');

        if ($nameIdx === false) {
            $error = 'CSV must have a "name" column.';
        } else {
            // ── Count guests once (not per row) for limit checks ──
            $curCount = $db->prepare('SELECT COUNT(*) FROM guests WHERE event_id=?');
            $curCount->execute([$eventId]);
            $liveCount = (int)$curCount->fetchColumn();

            // ── Preload existing keys for de-duplication ──
            $seen = [];   // normalized "name|email" => true
            if (!$allowDuplicates) {
                $ex = $db->prepare('SELECT name, email FROM guests WHERE event_id=?');
                $ex->execute([$eventId]);
                foreach ($ex->fetchAll() as $r) {
                    $seen[dedupKey($r['name'], $r['email'])] = true;
                }
            }

            $ins = $db->prepare(
                'INSERT INTO guests (event_id,name,email,phone,table_number,seat_number,category,token)
                 VALUES (?,?,?,?,?,?,?,?)'
            );
            $count = $skippedLimit = $skippedDup = $badEmail = 0;

            while (($row = fgetcsv($handle)) !== false) {
                $name = trim($row[$nameIdx] ?? '');
                if ($name === '') continue;

                // Guest-limit check (no query — use local counter)
                if ($maxGuests !== null && $liveCount >= $maxGuests) { $skippedLimit++; continue; }

                // Validate + normalize email
                $email = $emailIdx !== false ? trim($row[$emailIdx] ?? '') : '';
                if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $badEmail++;   // keep the guest but drop the invalid address
                    $email = '';
                }

                // De-duplication (against DB + earlier rows in this file)
                if (!$allowDuplicates) {
                    $k = dedupKey($name, $email);
                    if (isset($seen[$k])) { $skippedDup++; continue; }
                    $seen[$k] = true;
                }

                // Normalize phone to a sane character set
                $phone = $phoneIdx !== false ? trim($row[$phoneIdx] ?? '') : '';
                if ($phone !== '') $phone = preg_replace('/[^0-9+()\-\s]/', '', $phone);

                $ins->execute([
                    $eventId,
                    $name,
                    $email !== '' ? $email : null,
                    $phone !== '' ? $phone : null,
                    $tableIdx !== false ? trim($row[$tableIdx] ?? '') : null,
                    $seatIdx  !== false ? trim($row[$seatIdx]  ?? '') : null,
                    $catIdx   !== false ? trim($row[$catIdx]   ?? '') : null,
                    generateToken(),
                ]);
                $count++;
                $liveCount++;
            }
            fclose($handle);

            $msg = "{$count} guest(s) imported" . ($allowDuplicates ? ' (duplicates allowed).' : '.');
            $notes = [];
            if ($skippedDup)   $notes[] = "{$skippedDup} duplicate(s) skipped";
            if ($badEmail)     $notes[] = "{$badEmail} invalid email(s) cleared";
            if ($skippedLimit) $notes[] = "{$skippedLimit} skipped — guest limit of {$maxGuests} reached";
            if ($notes) $error = ucfirst(implode('; ', $notes)) . '.';
        }
    }
}

// ── Handle single guest add ──────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_guest'])) {
    $name = trim($_POST['name'] ?? '');
    if ($name) {
        // Check guest limit
        if ($maxGuests !== null) {
            $cur = $db->prepare('SELECT COUNT(*) FROM guests WHERE event_id=?');
            $cur->execute([$eventId]);
            if ((int)$cur->fetchColumn() >= $maxGuests) {
                $error = "Guest limit of {$maxGuests} reached for this event. Contact the super admin to increase your limit.";
                $name  = ''; // prevent insert below
            }
        }
        if ($name) {
            $token = generateToken();
            $db->prepare(
                'INSERT INTO guests (event_id,name,email,phone,table_number,seat_number,category,token)
                 VALUES (?,?,?,?,?,?,?,?)'
            )->execute([
                $eventId, $name,
                trim($_POST['email'] ?? '') ?: null,
                trim($_POST['phone'] ?? '') ?: null,
                trim($_POST['table_number'] ?? '') ?: null,
                trim($_POST['seat_number'] ?? '') ?: null,
                trim($_POST['category'] ?? '') ?: null,
                $token
            ]);
            $msg = "Guest '{$name}' added.";
        }
    }
}

// ── Generate invites (only for guests without one) ──────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_invites'])) {
    // Only fetch guests with no invite_path yet
    $gStmt = $db->prepare(
        'SELECT * FROM guests WHERE event_id=?
         AND (invite_path IS NULL OR invite_path="")'
    );
    $gStmt->execute([$eventId]);
    $pending = $gStmt->fetchAll();
    $count = 0;
    foreach ($pending as $g) {
        $path = buildInvite($g, $event);
        if ($path) {
            $rel = str_replace(BASE_PATH_FINAL . '/', '', $path);
            $db->prepare('UPDATE guests SET invite_path=? WHERE id=?')
               ->execute([$rel, $g['id']]);
            $count++;
        }
    }
    $msg = $count
        ? "Generated {$count} ticket(s) for new guests."
        : "All guests already have tickets — nothing to generate.";
}

// ── Regenerate ALL invites (force overwrite) ─────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['regenerate_all'])) {
    $gStmt = $db->prepare('SELECT * FROM guests WHERE event_id=?');
    $gStmt->execute([$eventId]);
    $count = 0;
    foreach ($gStmt->fetchAll() as $g) {
        // Delete old file if exists
        if (!empty($g['invite_path'])) {
            $old = resolveUploadPath($g['invite_path']);
            if ($old && file_exists($old)) @unlink($old);
        }
        $path = buildInvite($g, $event);
        if ($path) {
            $rel = str_replace(BASE_PATH_FINAL . '/', '', $path);
            $db->prepare('UPDATE guests SET invite_path=? WHERE id=?')
               ->execute([$rel, $g['id']]);
            $count++;
        }
    }
    $msg = "Regenerated {$count} ticket(s).";
}


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_guest'])) {
    $gid = (int)$_POST['guest_id'];
    $db->prepare('DELETE FROM guests WHERE id=? AND event_id=?')->execute([$gid, $eventId]);
    adminLog('guest.delete', 'guest', $gid, 'event #' . $eventId);
    $msg = 'Guest removed.';
}

// ── Bulk guest actions ───────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'])) {
    $ids = array_values(array_filter(array_map('intval', $_POST['guest_ids'] ?? [])));
    $bulk = $_POST['bulk_action'];
    if (!$ids) {
        $error = 'No guests selected.';
    } else {
        $place = implode(',', array_fill(0, count($ids), '?'));
        if ($bulk === 'delete') {
            $db->prepare("DELETE FROM guests WHERE event_id=? AND id IN ($place)")
               ->execute(array_merge([$eventId], $ids));
            adminLog('guest.bulk_delete', 'event', $eventId, count($ids) . ' guests');
            $msg = count($ids) . ' guest(s) deleted.';
        } elseif ($bulk === 'category') {
            $cat = trim($_POST['bulk_category'] ?? '');
            $db->prepare("UPDATE guests SET category=? WHERE event_id=? AND id IN ($place)")
               ->execute(array_merge([$cat !== '' ? $cat : null, $eventId], $ids));
            adminLog('guest.bulk_category', 'event', $eventId, count($ids) . " → " . $cat);
            $msg = count($ids) . ' guest(s) updated to category "' . htmlspecialchars($cat) . '".';
        } elseif ($bulk === 'mark_sent') {
            $db->prepare("UPDATE guests SET invite_sent=1, invite_sent_at=NOW(), invite_sent_by=?
                          WHERE event_id=? AND id IN ($place)")
               ->execute(array_merge([$_SESSION['admin_id'], $eventId], $ids));
            adminLog('guest.bulk_mark_sent', 'event', $eventId, count($ids) . ' guests');
            $msg = count($ids) . ' guest(s) marked as sent.';
        }
    }
}

// ── Fetch guests (paginated) ─────────────────────────────────
$search   = trim($_GET['q'] ?? '');
$where    = 'WHERE g.event_id = ?';
$params   = [$eventId];
if ($search) {
    $where   .= ' AND (g.name LIKE ? OR g.email LIKE ? OR g.phone LIKE ?)';
    $params[] = "%{$search}%";
    $params[] = "%{$search}%";
    $params[] = "%{$search}%";
}

// Count rows matching the current filter (for page navigation)
$countStmt = $db->prepare("SELECT COUNT(*) FROM guests g {$where}");
$countStmt->execute($params);
$matchCount = (int)$countStmt->fetchColumn();

$perPage = 50;
$pageCount = max(1, (int)ceil($matchCount / $perPage));
$page      = max(1, min($pageCount, (int)($_GET['page'] ?? 1)));
$offset    = ($page - 1) * $perPage;

$sql  = "SELECT g.*, c.name AS checker_name FROM guests g
         LEFT JOIN checkers c ON c.id = g.checked_by
         {$where}
         ORDER BY g.name ASC
         LIMIT {$perPage} OFFSET {$offset}";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$guests = $stmt->fetchAll();

$totalGuests  = $db->prepare('SELECT COUNT(*) FROM guests WHERE event_id=?');
$totalGuests->execute([$eventId]);
$totalGuests = (int)$totalGuests->fetchColumn();

$totalChecked = $db->prepare('SELECT COUNT(*) FROM guests WHERE event_id=? AND checked_in=1');
$totalChecked->execute([$eventId]);
$totalChecked = (int)$totalChecked->fetchColumn();

layout_start('Guests — ' . $event['title'], 'guests');
event_tabs($eventId, 'guests', $event['title']);
?>

<div class="page-header">
  <div><h1>Guest List</h1></div>
  <a href="<?= BASE_URL ?>/admin/guests_edit.php?event_id=<?= $eventId ?>" class="btn btn-outline btn-sm">✏️ Edit inline</a>
</div>

<?php if ($msg): ?><div class="alert alert-success"><?= htmlspecialchars($msg) ?></div><?php endif; ?>
<?php if ($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>

<?php $atGuestLimit = $maxGuests !== null && $totalGuests >= $maxGuests; ?>
<div class="stats-grid">
  <div class="stat-card <?= $atGuestLimit ? 'danger' : '' ?>">
    <div class="stat-value"><?= $totalGuests ?><?= $maxGuests !== null ? '<span style="font-size:.9rem;opacity:.6"> / ' . $maxGuests . '</span>' : '' ?></div>
    <div class="stat-label">Total Guests<?= $maxGuests !== null ? ' (limit)' : '' ?></div>
  </div>
  <div class="stat-card success">
    <div class="stat-value"><?= $totalChecked ?></div>
    <div class="stat-label">Checked In</div>
  </div>
  <div class="stat-card danger">
    <div class="stat-value"><?= $totalGuests - $totalChecked ?></div>
    <div class="stat-label">Pending</div>
  </div>
  <div class="stat-card info">
    <div class="stat-value"><?= $totalGuests > 0 ? round($totalChecked/$totalGuests*100) : 0 ?>%</div>
    <div class="stat-label">Attendance Rate</div>
  </div>
</div>
<?php if ($atGuestLimit): ?>
  <div class="alert alert-danger" style="margin-bottom:16px">
    Guest limit of <?= $maxGuests ?> reached for this event. New guests cannot be added until the super admin increases your limit.
  </div>
<?php endif; ?>

<!-- Export (single menu — pick scope + format) -->
<div class="card card-sm mb-3" style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px">
  <div>
    <div class="label-ui mb-1">Export guest list</div>
    <div class="text-muted text-sm">Choose who to include and a format.</div>
  </div>
  <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
    <select class="form-control" id="exp-scope" style="width:auto;padding:8px 12px;font-size:.82rem">
      <option value="all">Everyone</option>
      <option value="checked_in">Attended (checked in)</option>
      <option value="sent">WhatsApp sent</option>
      <option value="unsent">WhatsApp pending</option>
      <option value="no_ticket">No ticket yet</option>
    </select>
    <div style="display:inline-flex;border:1px solid var(--gold-dim);border-radius:var(--radius);overflow:hidden">
      <label style="cursor:pointer"><input type="radio" name="exp-fmt" value="csv" checked hidden>
        <span class="exp-seg" data-fmt="csv" style="display:inline-block;padding:9px 14px;font-family:var(--font-ui);font-size:.72rem;font-weight:700;letter-spacing:.06em">CSV</span></label>
      <label style="cursor:pointer"><input type="radio" name="exp-fmt" value="excel" hidden>
        <span class="exp-seg" data-fmt="excel" style="display:inline-block;padding:9px 14px;font-family:var(--font-ui);font-size:.72rem;font-weight:700;letter-spacing:.06em">Excel</span></label>
    </div>
    <button class="btn btn-gold btn-sm" type="button" onclick="doExport()" data-no-loader>↓ Download</button>
  </div>
</div>
<script>
(function(){
  const segs = document.querySelectorAll('.exp-seg');
  function paint(){ segs.forEach(s=>{ const on = s.previousElementSibling ? false : false;
    const input = s.parentElement.querySelector('input'); const active = input.checked;
    s.style.background = active ? 'var(--gold)' : 'transparent';
    s.style.color = active ? 'var(--obsidian)' : 'var(--gold)'; }); }
  segs.forEach(s=> s.addEventListener('click', ()=>{ s.parentElement.querySelector('input').checked = true; paint(); }));
  paint();
  window.doExport = function(){
    const scope = document.getElementById('exp-scope').value;
    const fmt = document.querySelector('input[name=exp-fmt]:checked').value;
    window.location = '<?= BASE_URL ?>/api/guests_export.php?event_id=<?= $eventId ?>&filter=' + scope + '&format=' + fmt;
  };
})();
</script>

<!-- Actions row -->
<div class="flex gap-2 mb-3" style="flex-wrap:wrap">
  <form method="POST" enctype="multipart/form-data" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
    <input type="hidden" name="event_id" value="<?= $eventId ?>">
    <input type="hidden" name="upload_guests" value="1">
    <input class="form-control" type="file" name="csv_file" accept=".csv"
           style="width:220px;padding:8px 10px;font-size:.8rem"
           <?= $atGuestLimit ? 'disabled' : '' ?>>
    <label class="text-muted text-sm" style="display:flex;align-items:center;gap:5px;user-select:none;cursor:pointer"
           title="When off, guests already in this list (matched by name + email) are skipped">
      <input type="checkbox" name="allow_duplicates" value="1"> Allow duplicates
    </label>
    <button class="btn btn-outline" type="submit" <?= $atGuestLimit ? 'disabled title="Guest limit reached"' : '' ?>>Upload CSV</button>
  </form>

  <!-- Generate invites — new guests only -->
  <form method="POST">
    <input type="hidden" name="event_id" value="<?= $eventId ?>">
    <input type="hidden" name="generate_invites" value="1">
    <?php
    $pending = $db->prepare('SELECT COUNT(*) FROM guests WHERE event_id=? AND (invite_path IS NULL OR invite_path="")');
    $pending->execute([$eventId]);
    $pendingCount = (int)$pending->fetchColumn();
    ?>
    <button class="btn btn-gold" type="submit" data-loader-text="Generating tickets…">
      ⚡ Generate New Tickets
      <?php if ($pendingCount): ?>
        <span style="background:rgba(0,0,0,.3);border-radius:10px;padding:1px 7px;font-size:.7rem;margin-left:4px"><?= $pendingCount ?></span>
      <?php endif; ?>
    </button>
  </form>

  <!-- Regenerate all (force rebuild) -->
  <form method="POST" onsubmit="return confirm('Regenerate ALL tickets including existing ones? This will overwrite current ticket images.')">
    <input type="hidden" name="event_id" value="<?= $eventId ?>">
    <input type="hidden" name="regenerate_all" value="1">
    <button class="btn btn-outline btn-sm" type="submit" data-loader-text="Regenerating all tickets…">
      ↺ Regenerate All
    </button>
  </form>

  <!-- Download generated tickets as batched ZIP files -->
  <a href="<?= BASE_URL ?>/admin/tickets_download.php?event_id=<?= $eventId ?>"
     class="btn btn-outline btn-sm"
     title="Download generated tickets as ZIP files">
    ⬇ Download Tickets
  </a>

  <!-- Download CSV template -->
  <a href="<?= BASE_URL ?>/api/csv_template.php" class="btn btn-outline btn-sm">↓ CSV Template</a>

</div>

<!-- CSV format hint -->
<div class="alert alert-info" style="font-size:.8rem;margin-bottom:20px">
  <strong>CSV columns:</strong> name (required), email, phone, table, seat, category
</div>

<!-- Search + add guest -->
<div class="card mb-3">
  <details <?= $atGuestLimit ? '' : '' ?>>
    <summary style="cursor:pointer;font-family:var(--font-ui);font-size:.75rem;font-weight:700;
                    letter-spacing:.1em;text-transform:uppercase;color:<?= $atGuestLimit ? 'var(--muted)' : 'var(--gold)' ?>;user-select:none">
      + Add Single Guest<?= $atGuestLimit ? ' — limit reached' : '' ?>
    </summary>
    <?php if ($atGuestLimit): ?>
      <p class="text-muted text-sm" style="margin-top:12px">Guest limit reached. Contact the super admin to increase your limit.</p>
    <?php else: ?>
    <form method="POST" style="margin-top:20px">
      <input type="hidden" name="event_id" value="<?= $eventId ?>">
      <input type="hidden" name="add_guest" value="1">
      <div class="grid-2">
        <div class="form-group">
          <label class="form-label">Name *</label>
          <input class="form-control" type="text" name="name" required>
        </div>
        <div class="form-group">
          <label class="form-label">Email</label>
          <input class="form-control" type="email" name="email">
        </div>
        <div class="form-group">
          <label class="form-label">Phone</label>
          <input class="form-control" type="text" name="phone">
        </div>
        <div class="form-group">
          <label class="form-label">Category</label>
          <input class="form-control" type="text" name="category" placeholder="VIP, Regular…">
        </div>
        <div class="form-group">
          <label class="form-label">Table</label>
          <input class="form-control" type="text" name="table_number">
        </div>
        <div class="form-group">
          <label class="form-label">Seat</label>
          <input class="form-control" type="text" name="seat_number">
        </div>
      </div>
      <button class="btn btn-gold" name="add_guest" type="submit">Add Guest</button>
    </form>
    <?php endif; ?>
  </details>
</div>

<!-- Bulk action bar (shown when rows are selected) -->
<div id="bulk-bar" class="card card-sm mb-2" style="display:none;align-items:center;gap:10px;flex-wrap:wrap">
  <strong class="text-sm"><span id="bulk-count">0</span> selected</strong>
  <select id="bulk-action" class="form-control" style="width:auto;padding:6px 10px;font-size:.8rem">
    <option value="">— Bulk action —</option>
    <option value="mark_sent">Mark WhatsApp sent</option>
    <option value="category">Set category…</option>
    <option value="delete">Delete selected</option>
  </select>
  <input id="bulk-category" class="form-control" type="text" placeholder="Category"
         style="width:150px;padding:6px 10px;font-size:.8rem;display:none">
  <button class="btn btn-gold btn-sm" type="button" onclick="applyBulk()">Apply</button>
  <button class="btn btn-outline btn-sm" type="button" onclick="clearBulk()">Clear</button>
</div>

<!-- Guest table -->
<div class="card">
  <div class="card-header">
    <span class="card-title">
      <?= $search ? 'Search Results' : 'All Guests' ?>
      <span class="badge badge-muted" style="margin-left:8px"><?= $matchCount ?></span>
    </span>
    <form method="GET" style="display:flex;gap:8px">
      <input type="hidden" name="event_id" value="<?= $eventId ?>">
      <input class="form-control" type="text" name="q" value="<?= htmlspecialchars($search) ?>"
             placeholder="Search name, email, phone…" style="width:220px;padding:7px 12px">
      <button class="btn btn-outline btn-sm" type="submit">Search</button>
      <?php if ($search): ?>
        <a href="?event_id=<?= $eventId ?>" class="btn btn-outline btn-sm">Clear</a>
      <?php endif; ?>
    </form>
  </div>
  <div class="table-wrap">
    <table>
      <thead>
        <tr>
          <th style="width:28px"><input type="checkbox" id="chk-all" title="Select all"></th>
          <th>#</th>
          <th>Name</th>
          <th>Contact</th>
          <th>Table / Category</th>
          <th>Invite</th>
          <th>Check-in</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($guests)): ?>
          <tr><td colspan="8" class="text-muted" style="padding:32px;text-align:center">No guests. Upload a CSV or add manually.</td></tr>
        <?php endif; ?>
        <?php foreach ($guests as $i => $g): ?>
        <tr>
          <td><input type="checkbox" class="row-chk" value="<?= $g['id'] ?>"></td>
          <td class="text-muted text-sm"><?= $offset + $i + 1 ?></td>
          <td>
            <div style="font-weight:500"><?= htmlspecialchars($g['name']) ?></div>
            <div class="text-muted text-sm"><?= htmlspecialchars($g['email'] ?? '') ?></div>
          </td>
          <td class="text-muted text-sm"><?= htmlspecialchars($g['phone'] ?? '—') ?></td>
          <td>
            <?php if ($g['table_number']): ?>
              <span class="badge badge-muted">Table <?= htmlspecialchars($g['table_number']) ?></span>
            <?php endif; ?>
            <?php if ($g['category']): ?>
              <span class="badge badge-gold"><?= htmlspecialchars($g['category']) ?></span>
            <?php endif; ?>
          </td>
          <td>
            <?php if ($g['invite_path']): ?>
              <a href="<?= BASE_URL . '/' . htmlspecialchars($g['invite_path']) ?>"
                 target="_blank" class="btn btn-outline btn-sm">View</a>
            <?php else: ?>
              <span class="text-muted text-sm">Not generated</span>
            <?php endif; ?>
          </td>
          <td>
            <?php if ($g['checked_in']): ?>
              <span class="badge badge-success">✓ Checked In</span>
              <div class="text-muted" style="font-size:.7rem;margin-top:2px">
                <?= date('H:i · M j', strtotime($g['check_in_time'])) ?>
                · <span class="badge <?= $g['check_in_method']==='qr'?'badge-info':'badge-gold' ?>" style="font-size:.6rem"><?= strtoupper($g['check_in_method'] ?? '') ?></span>
                <?php if ($g['checker_name']): ?>
                  · by <?= htmlspecialchars($g['checker_name']) ?>
                <?php endif; ?>
              </div>
            <?php else: ?>
              <span class="badge badge-muted">Pending</span>
            <?php endif; ?>
          </td>
          <td>
            <form method="POST" onsubmit="return confirm('Remove this guest?')">
              <input type="hidden" name="event_id" value="<?= $eventId ?>">
              <input type="hidden" name="guest_id" value="<?= $g['id'] ?>">
              <input type="hidden" name="delete_guest" value="1">
              <button class="btn btn-danger btn-sm" type="submit">✕</button>
            </form>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php if ($pageCount > 1): ?>
  <?php $pageUrl = fn(int $p) => '?event_id=' . $eventId . ($search ? '&q=' . urlencode($search) : '') . '&page=' . $p; ?>
  <div class="card-footer" style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;padding-top:14px">
    <span class="text-muted text-sm">
      Showing <?= $offset + 1 ?>–<?= min($offset + $perPage, $matchCount) ?> of <?= $matchCount ?>
    </span>
    <div style="display:flex;gap:6px;align-items:center">
      <?php if ($page > 1): ?>
        <a class="btn btn-outline btn-sm" href="<?= $pageUrl($page - 1) ?>">← Prev</a>
      <?php endif; ?>
      <span class="text-muted text-sm">Page <?= $page ?> / <?= $pageCount ?></span>
      <?php if ($page < $pageCount): ?>
        <a class="btn btn-outline btn-sm" href="<?= $pageUrl($page + 1) ?>">Next →</a>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>
</div>

<script>
(function() {
  const EVENT_ID = <?= (int)$eventId ?>;
  const bar   = document.getElementById('bulk-bar');
  const count = document.getElementById('bulk-count');
  const chkAll = document.getElementById('chk-all');
  const actSel = document.getElementById('bulk-action');
  const catInp = document.getElementById('bulk-category');
  const rows = () => Array.from(document.querySelectorAll('.row-chk'));
  const selected = () => rows().filter(c => c.checked).map(c => c.value);

  function refresh() {
    const n = selected().length;
    count.textContent = n;
    bar.style.display = n ? 'flex' : 'none';
  }
  rows().forEach(c => c.addEventListener('change', refresh));
  if (chkAll) chkAll.addEventListener('change', () => { rows().forEach(c => c.checked = chkAll.checked); refresh(); });
  if (actSel) actSel.addEventListener('change', () => { catInp.style.display = actSel.value === 'category' ? 'inline-block' : 'none'; });

  window.clearBulk = function() { rows().forEach(c => c.checked = false); if (chkAll) chkAll.checked = false; refresh(); };

  window.applyBulk = async function() {
    const ids = selected(), act = actSel.value;
    if (!ids.length || !act) { showToast('Pick guests and an action.', 'error'); return; }
    if (act === 'delete') {
      const ok = window.uiConfirm
        ? await uiConfirm({ title: 'Delete ' + ids.length + ' guest(s)?', message: 'This cannot be undone.', confirmText: 'Delete', danger: true })
        : confirm('Delete ' + ids.length + ' selected guest(s)? This cannot be undone.');
      if (!ok) return;
    }
    if (act === 'category' && !catInp.value.trim()) {
      const ok = window.uiConfirm
        ? await uiConfirm({ title: 'Clear category?', message: 'The selected guests will have no category.', confirmText: 'Clear' })
        : confirm('Clear the category for the selected guests?');
      if (!ok) return;
    }

    const f = document.createElement('form');
    f.method = 'POST';
    f.style.display = 'none';
    const add = (n, v) => { const i = document.createElement('input'); i.type = 'hidden'; i.name = n; i.value = v; f.appendChild(i); };
    add('csrf_token', window.CSRF_TOKEN || '');
    add('event_id', EVENT_ID);
    add('bulk_action', act);
    if (act === 'category') add('bulk_category', catInp.value.trim());
    ids.forEach(id => add('guest_ids[]', id));
    document.body.appendChild(f);
    f.submit();
  };
})();
</script>

<?php layout_end(); ?>
