<?php
// admin/whatsapp.php  —  Batch ticket generation + WhatsApp invite sender
require_once __DIR__ . '/../config.php';
adminGuard();
requireCsrf();  // reject POSTs without a valid CSRF token
require_once __DIR__ . '/_layout.php';

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

// ── Load all events ──────────────────────────────────────────
$allEvents = $db->prepare('SELECT id, title, slug FROM events WHERE admin_id=? ORDER BY title');
$allEvents->execute([$_SESSION['admin_id']]);
$allEvents = $allEvents->fetchAll();

// WhatsApp delivery mode (manual wa.me links vs Cloud API auto-send)
$waProvider = $db->prepare('SELECT wa_provider FROM admins WHERE id=?');
$waProvider->execute([$_SESSION['admin_id']]);
$waProvider = $waProvider->fetchColumn() ?: 'manual';

// ── Load selected event ──────────────────────────────────────
$event = null;
if ($eventId) {
    $s = $db->prepare('SELECT * FROM events WHERE id=? AND admin_id=?');
    $s->execute([$eventId, $_SESSION['admin_id']]);
    $event = $s->fetch();
}

// ── Save WhatsApp message template ──────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_message']) && $event) {
    $waMsg = trim($_POST['wa_message'] ?? '');
    $db->prepare('UPDATE events SET wa_message=? WHERE id=?')->execute([$waMsg, $eventId]);
    $s->execute([$eventId, $_SESSION['admin_id']]);
    $event = $s->fetch();
    $msg = 'Message template saved.';
}

// ── Generate batch of invites ────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_batch']) && $event) {
    require_once BASE_PATH . '/lib/qr_invite.php';
    $batchSize  = max(1, min(50, (int)($_POST['batch_size'] ?? 15)));
    $filterSent = isset($_POST['unsent_only']);

    $sql = 'SELECT * FROM guests WHERE event_id=?';
    if ($filterSent) $sql .= ' AND (invite_path IS NULL OR invite_path = "")';
    $sql .= ' ORDER BY name ASC LIMIT ?';
    $stmt = $db->prepare($sql);
    $stmt->execute([$eventId, $batchSize]);
    $batch = $stmt->fetchAll();

    $count = 0;
    foreach ($batch as $g) {
        // Delete old so it's regenerated fresh
        $old = INVITE_PATH . '/' . $event['slug'] . '/' . $g['token'] . '.png';
        if (file_exists($old)) unlink($old);
        $path = buildInvite($g, $event);
        $db->prepare('UPDATE guests SET invite_path=? WHERE id=?')
           ->execute([str_replace(BASE_PATH_FINAL . '/', '', $path), $g['id']]);
        $count++;
    }
    $msg = "Generated {$count} ticket" . ($count !== 1 ? 's' : '') . '.';
}

// ── Mark invite as sent (AJAX) ───────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_MARK_SENT'])) {
    $body    = json_decode(file_get_contents('php://input'), true) ?? [];
    $guestId = (int)($body['guest_id'] ?? 0);
    $action  = $body['action'] ?? 'sent'; // 'sent' or 'unsent'

    if ($guestId) {
        if ($action === 'sent') {
            $db->prepare('UPDATE guests SET invite_sent=1, invite_sent_at=NOW(), invite_sent_by=? WHERE id=? AND event_id=?')
               ->execute([$_SESSION['admin_id'], $guestId, $eventId]);
        } else {
            $db->prepare('UPDATE guests SET invite_sent=0, invite_sent_at=NULL, invite_sent_by=NULL WHERE id=? AND event_id=?')
               ->execute([$guestId, $eventId]);
        }
        jsonOut(['ok' => true]);
    }
    jsonOut(['ok' => false], 400);
}

// ── Mark batch as sent ───────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mark_batch_sent']) && $event) {
    $ids = array_map('intval', $_POST['guest_ids'] ?? []);
    if ($ids) {
        $in   = implode(',', $ids);
        $db->prepare("UPDATE guests SET invite_sent=1, invite_sent_at=NOW(), invite_sent_by=?
                      WHERE event_id=? AND id IN ({$in})")
           ->execute([$_SESSION['admin_id'], $eventId]);
        $msg = count($ids) . ' guest(s) marked as sent.';
    }
}

// ── Fetch guests ─────────────────────────────────────────────
$filter    = $_GET['filter'] ?? 'all'; // all | sent | unsent | no_ticket
$search    = trim($_GET['q'] ?? '');
$batchSize = (int)($_GET['batch'] ?? 15);
$page      = max(1, (int)($_GET['page'] ?? 1));
$perPage   = $batchSize;

// Sort — whitelisted only (never interpolate raw input into ORDER BY).
// id is the tiebreaker so paging stays stable when timestamps/names collide.
$sortMap = [
    'name'         => ['Name (A–Z)',        'g.name ASC, g.id ASC'],
    'name_desc'    => ['Name (Z–A)',        'g.name DESC, g.id DESC'],
    'created_desc' => ['Newest added',      'g.created_at DESC, g.id DESC'],
    'created_asc'  => ['Oldest added',      'g.created_at ASC, g.id ASC'],
];
$sort = $_GET['sort'] ?? 'name';
if (!isset($sortMap[$sort])) $sort = 'name';
$orderBy = $sortMap[$sort][1];

$where  = 'WHERE g.event_id=?';
$params = [$eventId];

if ($filter === 'sent')      { $where .= ' AND g.invite_sent=1'; }
if ($filter === 'unsent')    { $where .= ' AND g.invite_sent=0 AND g.invite_path IS NOT NULL AND g.invite_path != ""'; }
if ($filter === 'no_ticket') { $where .= ' AND (g.invite_path IS NULL OR g.invite_path="")'; }
if ($search) {
    $where  .= ' AND (g.name LIKE ? OR g.phone LIKE ?)';
    $params[] = "%{$search}%"; $params[] = "%{$search}%";
}

$countStmt = $db->prepare("SELECT COUNT(*) FROM guests g {$where}");
$countStmt->execute($params);
$totalCount = (int)$countStmt->fetchColumn();
$totalPages = max(1, ceil($totalCount / $perPage));
$page       = min($page, $totalPages);
$offset     = ($page - 1) * $perPage;

$guestStmt = $db->prepare("SELECT g.* FROM guests g {$where} ORDER BY {$orderBy} LIMIT {$perPage} OFFSET {$offset}");
$guestStmt->execute($params);
$guests = $guestStmt->fetchAll();

// Stats
$statStmt = $db->prepare('SELECT
    COUNT(*) total,
    SUM(invite_path IS NOT NULL AND invite_path != "") has_ticket,
    SUM(invite_sent=1) sent,
    SUM(invite_sent=0 AND invite_path IS NOT NULL AND invite_path != "") ready
    FROM guests WHERE event_id=?');
$statStmt->execute([$eventId]);
$stats = $statStmt->fetch();

// Default WA message
$defaultMsg = "Hello {name},\n\nYou are cordially invited to *{event}*.\n\nPlease find your personalised ticket attached.\n\nWe look forward to celebrating with you.";

layout_start('WhatsApp Invites', 'whatsapp');
event_tabs((int)$eventId, 'whatsapp', $event['title'] ?? '');
?>

<style>
.guest-row { transition: background .15s; }
.guest-row.is-sent { opacity: .7; }
.sent-badge { display: inline-flex; align-items: center; gap: 5px; }
.wa-btn {
    display: inline-flex; align-items: center; gap: 6px;
    padding: 7px 14px; border-radius: 6px; text-decoration: none;
    font-family: var(--font-ui); font-size: .72rem; font-weight: 700;
    letter-spacing: .06em; text-transform: uppercase;
    background: #25D366; color: #fff; border: none; cursor: pointer;
    transition: background .2s;
}
.wa-btn:hover { background: #1ebe59; }
.wa-btn svg { flex-shrink: 0; }
.wa-btn.sent { background: rgba(37,211,102,.15); color: #25D366; border: 1px solid rgba(37,211,102,.3); }

.batch-bar {
    position: sticky; bottom: 0; left: 0; right: 0;
    background: var(--surface); border-top: 1px solid var(--border);
    padding: 14px 24px; display: flex; align-items: center;
    gap: 14px; z-index: 100;
    box-shadow: 0 -4px 20px rgba(0,0,0,.4);
}
.pagination { display: flex; gap: 6px; align-items: center; }
.pagination a, .pagination span {
    display: inline-flex; align-items: center; justify-content: center;
    width: 32px; height: 32px;
    background: var(--surface-2); border: 1px solid var(--border);
    border-radius: var(--radius); color: var(--white); text-decoration: none;
    font-family: var(--font-ui); font-size: .72rem; font-weight: 700;
    transition: all .15s;
}
.pagination a:hover { border-color: var(--gold); color: var(--gold); }
.pagination span.current { background: var(--gold); color: var(--obsidian); border-color: var(--gold); }
</style>

<div class="page-header">
  <div>
    <div class="page-header-sub">Invites</div>
    <h1>WhatsApp Invites</h1>
  </div>
</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 if (!$event): ?>
<!-- Event selector (only when no event is in context) -->
<div class="card card-sm mb-4">
  <form method="GET" style="display:flex;gap:12px;align-items:center;flex-wrap:wrap">
    <label class="label-ui" style="white-space:nowrap">Select Event</label>
    <select class="form-control" name="event_id" style="max-width:320px;flex:1">
      <option value="">— Choose an event —</option>
      <?php foreach ($allEvents as $ev): ?>
        <option value="<?= $ev['id'] ?>" <?= $eventId===$ev['id']?'selected':'' ?>>
          <?= htmlspecialchars($ev['title']) ?>
        </option>
      <?php endforeach; ?>
    </select>
    <button class="btn btn-gold" type="submit">Load</button>
  </form>
</div>
<div class="alert alert-info">Open an event from the Events page to manage WhatsApp invites.</div>
<?php else: ?>

<!-- Stats -->
<div class="stats-grid">
  <div class="stat-card">
    <div class="stat-value"><?= (int)($stats['total'] ?? 0) ?></div>
    <div class="stat-label">Total Guests</div>
  </div>
  <div class="stat-card info">
    <div class="stat-value"><?= (int)($stats['has_ticket'] ?? 0) ?></div>
    <div class="stat-label">Tickets Generated</div>
  </div>
  <div class="stat-card">
    <div class="stat-value" style="color:#25D366"><?= (int)($stats['ready'] ?? 0) ?></div>
    <div class="stat-label">Ready to Send</div>
  </div>
  <div class="stat-card success">
    <div class="stat-value"><?= (int)($stats['sent'] ?? 0) ?></div>
    <div class="stat-label">Sent</div>
  </div>
</div>

<div class="grid-2 mb-4">

  <!-- Generate batch -->
  <div class="card">
    <div class="card-header"><span class="card-title">Generate Tickets</span></div>
    <form method="POST">
      <input type="hidden" name="event_id" value="<?= $eventId ?>">
      <div class="form-group">
        <label class="form-label">Batch Size</label>
        <select class="form-control" name="batch_size">
          <?php foreach ([10,15,20,25,50,100] as $n): ?>
            <option value="<?= $n ?>" <?= $n===15?'selected':'' ?>><?= $n ?> tickets</option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label style="display:flex;align-items:center;gap:8px;cursor:pointer">
          <input type="checkbox" name="unsent_only" value="1" checked
                 style="accent-color:var(--gold);width:16px;height:16px">
          <span class="text-sm" style="color:var(--muted)">Only guests without a ticket yet</span>
        </label>
      </div>
      <input type="hidden" name="generate_batch" value="1">
      <button class="btn btn-gold" type="submit"
              data-loader-text="Generating tickets…">⚡ Generate Batch</button>
    </form>
  </div>

  <!-- WA message template -->
  <div class="card">
    <div class="card-header"><span class="card-title">Message Template</span></div>
    <form method="POST">
      <input type="hidden" name="event_id" value="<?= $eventId ?>">
      <div class="form-group">
        <label class="form-label">Custom Message</label>
        <div class="fmt-toolbar">
          <button type="button" class="fmt-btn" title="Bold  *text*"          onclick="fmtWrap('wa_message_ta','*')"><b>B</b></button>
          <button type="button" class="fmt-btn" title="Italic  _text_"        onclick="fmtWrap('wa_message_ta','_')"><i>I</i></button>
          <button type="button" class="fmt-btn" title="Strikethrough  ~text~" onclick="fmtWrap('wa_message_ta','~')"><s>S</s></button>
          <button type="button" class="fmt-btn" title="Monospace  &#96;text&#96;" onclick="fmtWrap('wa_message_ta','\x60')"><code>&lt;/&gt;</code></button>
          <span class="fmt-sep"></span>
          <button type="button" class="fmt-btn" title="Insert guest name" onclick="fmtInsert('wa_message_ta','{name}')">{name}</button>
          <button type="button" class="fmt-btn" title="Insert event title" onclick="fmtInsert('wa_message_ta','{event}')">{event}</button>
        </div>
        <textarea class="form-control" id="wa_message_ta" name="wa_message" rows="5"
                  placeholder="<?= htmlspecialchars($defaultMsg) ?>"><?= htmlspecialchars($event['wa_message'] ?? '') ?></textarea>
        <div class="form-hint">
          Select text and use the buttons above — WhatsApp shows
          <strong>*bold*</strong>, <em>_italic_</em>, <s>~strike~</s> and <code>`mono`</code>.<br>
          Available placeholders: <code style="color:var(--gold)">{name}</code>,
          <code style="color:var(--gold)">{event}</code>,
          <code style="color:var(--gold)">{date}</code>,
          <code style="color:var(--gold)">{venue}</code>
        </div>
      </div>
      <input type="hidden" name="save_message" value="1">
      <button class="btn btn-outline" type="submit">Save Message</button>
    </form>
  </div>

</div>

<!-- Guest list -->
<div class="card">
  <div class="card-header" style="flex-wrap:wrap;gap:12px">
    <span class="card-title">
      Guest List
      <span class="badge badge-muted" style="margin-left:6px"><?= $totalCount ?></span>
    </span>
    <!-- Filters + search -->
    <form method="GET" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
      <input type="hidden" name="event_id" value="<?= $eventId ?>">
      <input class="form-control" type="text" name="q" value="<?= htmlspecialchars($search) ?>"
             placeholder="Name or phone…" style="width:180px;padding:7px 10px">
      <select class="form-control" name="filter" style="width:140px;padding:7px 10px">
        <option value="all"      <?= $filter==='all'      ?'selected':'' ?>>All</option>
        <option value="unsent"   <?= $filter==='unsent'   ?'selected':'' ?>>Ready (unsent)</option>
        <option value="sent"     <?= $filter==='sent'     ?'selected':'' ?>>Sent</option>
        <option value="no_ticket"<?= $filter==='no_ticket'?'selected':'' ?>>No Ticket</option>
      </select>
      <select class="form-control" name="sort" style="width:150px;padding:7px 10px"
              title="Sort the guest list" onchange="this.form.submit()">
        <?php foreach ($sortMap as $key => [$label, $_]): ?>
          <option value="<?= $key ?>" <?= $sort===$key?'selected':'' ?>><?= $label ?></option>
        <?php endforeach; ?>
      </select>
      <select class="form-control" name="batch" style="width:110px;padding:7px 10px"
              onchange="this.form.submit()">
        <?php foreach ([10,15,20,25,50] as $n): ?>
          <option value="<?= $n ?>" <?= $batchSize===$n?'selected':'' ?>><?= $n ?>/page</option>
        <?php endforeach; ?>
      </select>
      <button class="btn btn-outline btn-sm" type="submit">Filter</button>
    </form>
  </div>

  <!-- Batch mark-sent form -->
  <form method="POST" id="batch-form">
    <input type="hidden" name="event_id" value="<?= $eventId ?>">
    <input type="hidden" name="mark_batch_sent" value="1">
    <input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">

    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th style="width:32px">
              <input type="checkbox" id="select-all" style="accent-color:var(--gold)"
                     onclick="toggleAll(this)">
            </th>
            <th>#</th>
            <th>Guest</th>
            <th>Phone</th>
            <th>Added</th>
            <th>Ticket</th>
            <th>Send via WhatsApp</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($guests)): ?>
            <tr><td colspan="8" class="text-muted" style="padding:32px;text-align:center">
              No guests found<?= $filter!=='all'?' in this filter':'' ?>.
            </td></tr>
          <?php endif; ?>
          <?php
          $templateMsg = $event['wa_message'] ?? $defaultMsg;
          $eventDate   = $event['event_date'] ? date('l, F j Y', strtotime($event['event_date'])) : '';
          foreach ($guests as $i => $g):
            $isSent      = (bool)$g['invite_sent'];
            $hasTicket   = !empty($g['invite_path']);
            $phone       = preg_replace('/[^0-9+]/', '', $g['phone'] ?? '');
            // Normalise Nigerian number: 08012345678 → 2348012345678
            if (preg_match('/^0\d{10}$/', $phone)) $phone = '234' . substr($phone, 1);
            if (str_starts_with($phone, '+')) $phone = substr($phone, 1);
            // Build message
            $waMsg = str_replace(
                ['{name}','{event}','{date}','{venue}'],
                [$g['name'], $event['title'], $eventDate, $event['venue'] ?? ''],
                $templateMsg
            );
            $waUrl = 'https://wa.me/' . $phone . '?text=' . rawurlencode($waMsg);
            $rowClass = $isSent ? 'is-sent' : '';
          ?>
          <tr class="guest-row <?= $rowClass ?>" id="row-<?= $g['id'] ?>">
            <td><input type="checkbox" name="guest_ids[]" value="<?= $g['id'] ?>"
                       style="accent-color:var(--gold)"></td>
            <td class="text-muted text-sm"><?= ($page-1)*$perPage + $i + 1 ?></td>
            <td>
              <div style="font-weight:500"><?= htmlspecialchars($g['name']) ?></div>
              <?php if ($g['category']): ?>
                <span class="badge badge-gold" style="margin-top:3px"><?= htmlspecialchars($g['category']) ?></span>
              <?php endif; ?>
            </td>
            <td class="text-muted text-sm">
              <?= htmlspecialchars($g['phone'] ?? '—') ?>
              <?php if ($phone): ?>
                <div style="font-size:.65rem;color:var(--muted)">→ <?= htmlspecialchars($phone) ?></div>
              <?php endif; ?>
            </td>
            <td class="text-muted text-sm" style="white-space:nowrap">
              <?= $g['created_at']
                    ? htmlspecialchars(fmtEventTime($g['created_at'], $event, 'M j, Y'))
                    : '—' ?>
              <?php if ($g['created_at']): ?>
                <div style="font-size:.65rem;color:var(--muted)">
                  <?= htmlspecialchars(fmtEventTime($g['created_at'], $event, 'g:i A')) ?>
                </div>
              <?php endif; ?>
            </td>
            <td>
              <?php if ($hasTicket): ?>
                <a href="<?= BASE_URL . '/' . htmlspecialchars($g['invite_path']) ?>"
                   target="_blank" class="btn btn-outline btn-sm">View</a>
              <?php else: ?>
                <span class="badge badge-danger">No Ticket</span>
              <?php endif; ?>
            </td>
            <td>
              <?php if ($hasTicket && $phone): ?>
                <a href="<?= htmlspecialchars($waUrl) ?>" target="_blank"
                   class="wa-btn <?= $isSent ? 'sent' : '' ?>"
                   onclick="markSent(<?= $g['id'] ?>, this)">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z"/>
                    <path d="M12 0C5.373 0 0 5.373 0 12c0 2.138.564 4.14 1.542 5.878L0 24l6.313-1.52A11.94 11.94 0 0012 24c6.627 0 12-5.373 12-12S18.627 0 12 0zm0 21.818a9.818 9.818 0 01-5.001-1.37l-.36-.214-3.727.976.993-3.626-.233-.375A9.818 9.818 0 1112 21.818z"/>
                  </svg>
                  <?= $isSent ? 'Resend' : 'Send' ?>
                </a>
                <?php if ($waProvider !== 'manual'): ?>
                  <button type="button" class="btn btn-outline btn-sm" style="margin-left:4px"
                          onclick="sendViaApi(<?= $g['id'] ?>, this)" data-no-loader>⚡ API</button>
                <?php endif; ?>
              <?php elseif (!$phone): ?>
                <span class="badge badge-muted">No Phone</span>
              <?php elseif (!$hasTicket): ?>
                <span class="badge badge-muted">Need Ticket</span>
              <?php endif; ?>
            </td>
            <td>
              <?php if ($isSent): ?>
                <div>
                  <span class="badge badge-success">✓ Sent</span>
                  <div class="text-muted" style="font-size:.65rem;margin-top:3px">
                    <?= $g['invite_sent_at'] ? date('M j · H:i', strtotime($g['invite_sent_at'])) : '' ?>
                  </div>
                </div>
                <button class="btn btn-outline btn-sm" style="margin-top:4px;font-size:.6rem"
                        onclick="markUnsent(<?= $g['id'] ?>)">Undo</button>
              <?php else: ?>
                <span class="badge badge-muted">Pending</span>
              <?php endif; ?>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
    <div style="padding:16px 14px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px">
      <div class="text-muted text-sm">
        Showing <?= ($page-1)*$perPage+1 ?>–<?= min($page*$perPage, $totalCount) ?> of <?= $totalCount ?>
      </div>
      <?php
        // Keep every list control (filter/search/sort/page size) across paging
        $pageUrl = fn(int $p) => '?' . http_build_query([
            'event_id' => $eventId, 'filter' => $filter, 'q' => $search,
            'sort'     => $sort,    'batch'  => $batchSize, 'page' => $p,
        ]);
      ?>
      <div class="pagination">
        <?php if ($page > 1): ?>
          <a href="<?= htmlspecialchars($pageUrl($page-1)) ?>">‹</a>
        <?php endif; ?>
        <?php for ($p = max(1,$page-2); $p <= min($totalPages,$page+2); $p++): ?>
          <?php if ($p === $page): ?>
            <span class="current"><?= $p ?></span>
          <?php else: ?>
            <a href="<?= htmlspecialchars($pageUrl($p)) ?>"><?= $p ?></a>
          <?php endif; ?>
        <?php endfor; ?>
        <?php if ($page < $totalPages): ?>
          <a href="<?= htmlspecialchars($pageUrl($page+1)) ?>">›</a>
        <?php endif; ?>
      </div>
    </div>
    <?php endif; ?>

  </form><!-- /batch-form -->

</div><!-- /card -->

<!-- Sticky batch bar -->
<div class="batch-bar" id="batch-bar" style="display:none">
  <span id="batch-count" class="text-muted text-sm">0 selected</span>
  <button class="btn btn-gold" onclick="submitBatch()">✓ Mark Selected as Sent</button>
  <button class="btn btn-outline btn-sm" onclick="toggleAll(null, false)">Deselect All</button>
</div>

<?php endif; ?>

<script>
const BASE_URL = '<?= BASE_URL ?>';
const EVENT_ID = <?= (int)$eventId ?>;

// ── Checkbox select all ──────────────────────────────────────
function toggleAll(master, state) {
    const boxes = document.querySelectorAll('input[name="guest_ids[]"]');
    boxes.forEach(b => b.checked = state !== undefined ? state : (master ? master.checked : false));
    updateBatchBar();
}
document.querySelectorAll('input[name="guest_ids[]"]').forEach(b =>
    b.addEventListener('change', updateBatchBar));

function updateBatchBar() {
    const checked = document.querySelectorAll('input[name="guest_ids[]"]:checked').length;
    const bar = document.getElementById('batch-bar');
    const cnt = document.getElementById('batch-count');
    bar.style.display = checked > 0 ? 'flex' : 'none';
    cnt.textContent   = checked + ' selected';
}

function submitBatch() {
    document.getElementById('batch-form').submit();
}

// ── Mark individual sent (AJAX) ──────────────────────────────
function markSent(guestId, btn) {
    // Don't prevent default — let WhatsApp link open
    setTimeout(() => {
        fetch(window.location.href, {
            method:  'POST',
            headers: { 'Content-Type': 'application/json', 'X-Mark-Sent': '1' },
            body:    JSON.stringify({ guest_id: guestId, action: 'sent' })
        }).then(() => {
            const row = document.getElementById('row-' + guestId);
            if (row) {
                row.classList.add('is-sent');
                const statusCell = row.querySelector('td:last-child');
                if (statusCell) {
                    const now = new Date();
                    const ts  = now.toLocaleString('en-GB',{month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'});
                    statusCell.innerHTML = `
                        <div>
                            <span class="badge badge-success">✓ Sent</span>
                            <div class="text-muted" style="font-size:.65rem;margin-top:3px">${ts}</div>
                        </div>
                        <button class="btn btn-outline btn-sm" style="margin-top:4px;font-size:.6rem"
                                onclick="markUnsent(${guestId})">Undo</button>`;
                }
                if (btn) { btn.classList.add('sent'); btn.innerHTML = btn.innerHTML.replace('Send','Resend'); }
            }
        });
    }, 800); // brief delay so WA opens first
}

// ── Send via WhatsApp Cloud API (AJAX) ───────────────────────
function sendViaApi(guestId, btn) {
    if (btn) { btn.disabled = true; btn.textContent = '…'; }
    fetch('<?= BASE_URL ?>/api/wa_send.php', {
        method:  'POST',
        headers: { 'Content-Type': 'application/json' },
        body:    JSON.stringify({ event_id: <?= (int)$eventId ?>, guest_id: guestId })
    })
    .then(r => r.json())
    .then(d => {
        if (d.ok) {
            showToast('Invite sent via WhatsApp API.', 'success');
            const row = document.getElementById('row-' + guestId);
            if (row) row.classList.add('is-sent');
            if (btn) { btn.textContent = '✓ Sent'; }
        } else {
            showToast(d.error || 'Send failed.', 'error', 6000);
            if (btn) { btn.disabled = false; btn.textContent = '⚡ API'; }
        }
    })
    .catch(e => { showToast('Network error: ' + e, 'error'); if (btn) { btn.disabled = false; btn.textContent = '⚡ API'; } });
}

function markUnsent(guestId) {
    fetch(window.location.href, {
        method:  'POST',
        headers: { 'Content-Type': 'application/json', 'X-Mark-Sent': '1' },
        body:    JSON.stringify({ guest_id: guestId, action: 'unsent' })
    }).then(() => {
        const row = document.getElementById('row-' + guestId);
        if (row) {
            row.classList.remove('is-sent');
            const statusCell = row.querySelector('td:last-child');
            if (statusCell) {
                statusCell.innerHTML = '<span class="badge badge-muted">Pending</span>';
            }
        }
    });
}
</script>

<?php layout_end(); ?>
