<?php
// admin/email.php — Email invites with ticket image attached
require_once __DIR__ . '/../config.php';
adminGuard();
requireCsrf();  // reject POSTs without a valid CSRF token
require_once __DIR__ . '/_layout.php';

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

// Load admin (inc. SMTP)
$adminRow = $db->prepare('SELECT * FROM admins WHERE id=?');
$adminRow->execute([$adminId]);
$adminData = $adminRow->fetch();

// ── Save SMTP settings ───────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_smtp'])) {
    $newPass  = trim($_POST['smtp_pass'] ?? '');
    $passCol  = $newPass ? ',smtp_pass=?' : '';
    $params   = [
        trim($_POST['smtp_host']   ?? '') ?: null,
        (int)($_POST['smtp_port']  ?? 587),
        trim($_POST['smtp_user']   ?? '') ?: null,
        trim($_POST['smtp_from']   ?? '') ?: null,
        trim($_POST['smtp_name']   ?? '') ?: null,
        in_array($_POST['smtp_secure'] ?? '', ['tls','ssl','none'])
            ? $_POST['smtp_secure'] : 'tls',
    ];
    if ($newPass) $params[] = $newPass;
    $params[] = $adminId;
    $db->prepare("UPDATE admins SET smtp_host=?,smtp_port=?,smtp_user=?,
                  smtp_from=?,smtp_name=?,smtp_secure=?{$passCol} WHERE id=?")
       ->execute($params);
    $adminRow->execute([$adminId]);
    $adminData = $adminRow->fetch();
    $msg = 'SMTP settings saved.';
}

// ── Test SMTP ────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['test_smtp'])) {
    $testTo = trim($_POST['test_to'] ?? $adminData['email']);
    $html   = buildEmailHtml('Test User', 'RSVP System', 'Your SMTP configuration is working correctly. Tickets will be sent from this address.');
    $ok     = sendMail($adminData, $testTo, 'RSVP System — SMTP Test ✓', $html);
    if ($ok) $msg   = "✓ Test email sent to {$testTo}";
    else     $error = "✕ Test failed. Check SMTP settings below.";
}

// ── Save email template ──────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_template']) && $eventId) {
    // email_subject / email_message live in schema.sql (see migration_v3.sql)
    $db->prepare('UPDATE events SET email_subject=?,email_message=? WHERE id=? AND admin_id=?')
       ->execute([
           trim($_POST['email_subject'] ?? ''),
           trim($_POST['email_message'] ?? ''),
           $eventId, $adminId,
       ]);
    $msg = 'Email template saved.';
}

// ── SHARED: run actual send ──────────────────────────────────
function doSendBatch(PDO $db, array $adminData, array $event, array $guests,
                     int $adminId, int $eventId): array {
    require_once BASE_PATH . '/lib/qr_invite.php';

    // email_sent / email_sent_at live in schema.sql (see migration_v3.sql).
    // Still guard defensively so un-migrated installs degrade gracefully.
    $guestCols    = $db->query("SHOW COLUMNS FROM guests")->fetchAll(PDO::FETCH_COLUMN);
    $hasEmailSent = in_array('email_sent', $guestCols);

    $subject   = ($event['email_subject'] ?? '') ?: 'Your invitation to ' . $event['title'];
    $bodyTpl   = ($event['email_message'] ?? '')
        ?: "Dear {name},\n\nWe are delighted to invite you to *{event}*.\n\nYour personal ticket is attached to this email. Please download and present it at the entrance.\n\nWe look forward to celebrating with you.";
    $eventDate = $event['event_date'] ? date('l, F j Y · g:i A', strtotime($event['event_date'])) : '';

    $sent = $fail = 0;
    foreach ($guests as $g) {

        // 1. Ensure ticket image exists
        if (empty($g['invite_path']) || !resolveUploadPath($g['invite_path'])) {
            $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']]);
                $g['invite_path'] = $rel;
            }
        }

        $absImg    = $g['invite_path'] ? resolveUploadPath($g['invite_path']) : false;
        $ticketUrl = $g['invite_path'] ? BASE_URL . '/' . ltrim($g['invite_path'], '/') : '';

        // 2. Build message body
        $body = str_replace(
            ['{name}', '{event}', '{date}', '{venue}'],
            [$g['name'], $event['title'], $eventDate, $event['venue'] ?? ''],
            $bodyTpl
        );

        // 3. Build HTML email — ticket rendered via CID inline image
        $html = buildEmailHtmlWithTicket(
            $g['name'], $event['title'], $body,
            $ticketUrl, $eventDate, $event['venue'] ?? '', $absImg,
            $adminData['org_name'] ?? ($adminData['name'] ?? 'RSVP System')
        );

        // 4. Send — image embedded as CID + attached as PNG file
        $ok      = sendMail($adminData, $g['email'], $subject, $html, $absImg ?: '');
        $errNote = $ok ? null : 'sendMail returned false — check SMTP or server mail() config';

        // 6. Log
        $db->prepare(
            'INSERT INTO email_log (guest_id,event_id,admin_id,recipient,subject,status,error_msg,sent_at)
             VALUES (?,?,?,?,?,?,?,NOW())'
        )->execute([$g['id'], $eventId, $adminId, $g['email'], $subject,
                    $ok ? 'sent' : 'failed', $errNote]);

        // 7. Update guest record (only if columns exist)
        if ($ok && $hasEmailSent) {
            $db->prepare('UPDATE guests SET email_sent=1, email_sent_at=NOW() WHERE id=?')
               ->execute([$g['id']]);
            $sent++;
        } elseif ($ok) {
            $sent++;
        } else {
            $fail++;
        }
    }
    return [$sent, $fail];
}

// ── Send batch ───────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_emails']) && $eventId) {
    $evStmt = $db->prepare('SELECT * FROM events WHERE id=? AND admin_id=?');
    $evStmt->execute([$eventId, $adminId]);
    $ev = $evStmt->fetch();
    if (!$ev) { $error = 'Event not found.'; goto doneEmail; }

    $batchSize  = max(1, min(200, (int)($_POST['batch_size'] ?? 20)));
    $unsentOnly = isset($_POST['unsent_only']);
    $retryFailed = isset($_POST['retry_failed']);

    $sql = 'SELECT * FROM guests WHERE event_id=? AND email IS NOT NULL AND email!=""';
    if ($retryFailed) {
        // Guests who appear in email_log as failed but never sent
        $sql .= ' AND EXISTS (SELECT 1 FROM email_log el WHERE el.guest_id=guests.id AND el.status="failed")
                  AND (email_sent IS NULL OR email_sent=0)';
    } elseif ($unsentOnly) {
        $sql .= ' AND (email_sent IS NULL OR email_sent=0)';
    }
    $sql .= ' ORDER BY name ASC LIMIT ?';
    $gStmt = $db->prepare($sql);
    $gStmt->execute([$eventId, $batchSize]);
    $guests = $gStmt->fetchAll();

    if (empty($guests)) { $msg = 'No eligible guests found for this filter.'; goto doneEmail; }

    [$sent, $fail] = doSendBatch($db, $adminData, $ev, $guests, $adminId, $eventId);
    $msg = "Sent: {$sent} · Failed: {$fail}";
    if ($fail) $msg .= ' — See send log below for details.';
    doneEmail:
}

// ── Send to single guest ─────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_single']) && $eventId) {
    $gid    = (int)($_POST['guest_id'] ?? 0);
    $evStmt = $db->prepare('SELECT * FROM events WHERE id=? AND admin_id=?');
    $evStmt->execute([$eventId, $adminId]);
    $ev = $evStmt->fetch();
    $gStmt = $db->prepare('SELECT * FROM guests WHERE id=? AND event_id=?');
    $gStmt->execute([$gid, $eventId]);
    $g = $gStmt->fetch();
    if ($ev && $g) {
        [$sent, $fail] = doSendBatch($db, $adminData, $ev, [$g], $adminId, $eventId);
        $msg = $sent ? "✓ Email sent to {$g['name']} ({$g['email']})" : "✕ Failed to send to {$g['email']} — check SMTP";
        if ($fail) $error = $msg;
    }
}

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

$event = null;
if ($eventId) {
    $es = $db->prepare('SELECT * FROM events WHERE id=? AND admin_id=?');
    $es->execute([$eventId, $adminId]);
    $event = $es->fetch();
}

$stats   = null;
$guests  = [];
$log     = [];
$filter  = $_GET['filter'] ?? 'all';
$search  = trim($_GET['q'] ?? '');
$page    = max(1, (int)($_GET['page'] ?? 1));
$perPage = 25;

// 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];

if ($event) {
    // Stats
    $colCheck    = $db->query("SHOW COLUMNS FROM guests")->fetchAll(PDO::FETCH_COLUMN);
    $hasEmailCol = in_array('email_sent', $colCheck);
    $sentExpr    = $hasEmailCol ? 'SUM(email_sent=1)' : '0';

    $st = $db->prepare("SELECT COUNT(*) total,
        SUM(email IS NOT NULL AND email!='') has_email,
        {$sentExpr} sent,
        SUM(invite_path IS NOT NULL AND invite_path!='') has_ticket
        FROM guests WHERE event_id=?");
    $st->execute([$eventId]);
    $stats = $st->fetch();

    // Guest list with email status
    $where  = 'WHERE g.event_id=?';
    $params = [$eventId];
    if ($filter === 'sent')     { $where .= $hasEmailCol ? ' AND g.email_sent=1' : ' AND 1=0'; }
    if ($filter === 'unsent')   { $where .= $hasEmailCol ? ' AND (g.email_sent=0 OR g.email_sent IS NULL)' : ''; $where .= ' AND g.email IS NOT NULL AND g.email!=""'; }
    if ($filter === 'no_email') { $where .= ' AND (g.email IS NULL OR g.email="")'; }
    if ($filter === 'failed')   { $where .= ' AND EXISTS (SELECT 1 FROM email_log el WHERE el.guest_id=g.id AND el.status="failed")'; }
    if ($search) {
        $where .= ' AND (g.name LIKE ? OR g.email LIKE ?)';
        $params[] = "%{$search}%"; $params[] = "%{$search}%";
    }

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

    $emailSentSel = $hasEmailCol ? 'g.email_sent, g.email_sent_at,' : '0 AS email_sent, NULL AS email_sent_at,';
    $gStmt = $db->prepare("SELECT g.*, {$emailSentSel}
        (SELECT el.status FROM email_log el WHERE el.guest_id=g.id ORDER BY el.sent_at DESC LIMIT 1) last_email_status,
        (SELECT el.error_msg FROM email_log el WHERE el.guest_id=g.id AND el.status='failed' ORDER BY el.sent_at DESC LIMIT 1) last_error,
        (SELECT el.sent_at FROM email_log el WHERE el.guest_id=g.id AND el.status='sent' ORDER BY el.sent_at DESC LIMIT 1) last_sent_at
        FROM guests g {$where} ORDER BY {$orderBy} LIMIT {$perPage} OFFSET {$offset}");
    $gStmt->execute($params);
    $guests = $gStmt->fetchAll();

    // Recent log
    $ls = $db->prepare('SELECT el.*,g.name guest_name FROM email_log el
        LEFT JOIN guests g ON g.id=el.guest_id
        WHERE el.event_id=? ORDER BY el.sent_at DESC LIMIT 40');
    $ls->execute([$eventId]);
    $log = $ls->fetchAll();
}

// ── Email HTML — uses cid:TICKET_IMAGE placeholder ───────────
// PHPMailer replaces cid:TICKET_IMAGE with the embedded image CID.
// For mail() fallback the image is attached only (no inline display).
function buildEmailHtmlWithTicket(string $guestName, string $eventTitle, string $message,
                                   string $ticketUrl, string $eventDate, string $venue,
                                   string|false $imgPath, string $brand = 'RSVP System'): string {
    $msg   = richTextToHtml($message);   // supports *bold* _italic_ ~strike~ `mono`
    $brand = htmlspecialchars(strtoupper($brand ?: 'RSVP System'));

    $metaSection = ($eventDate || $venue) ? "
      <div style='background:#111118;border-radius:8px;padding:16px 20px;margin:24px 0;border:1px solid #1E1E28'>
        " . ($eventDate ? "<p style='margin:4px 0;color:#8A8A9A;font-size:13px'>📅 <strong style='color:#F0EBDC'>{$eventDate}</strong></p>" : '') . "
        " . ($venue     ? "<p style='margin:4px 0;color:#8A8A9A;font-size:13px'>📍 <strong style='color:#F0EBDC'>{$venue}</strong></p>" : '') . "
      </div>" : '';

    // Use cid: reference — PHPMailer embeds the real image here.
    // mail() fallback: cid won't render but image is still attached.
    $ticketImgSection = '';
    if ($imgPath && file_exists($imgPath)) {
        $ticketImgSection = "
      <div style='margin:28px 0;text-align:center'>
        <p style='color:#8A8A9A;font-size:12px;margin:0 0 12px;text-transform:uppercase;letter-spacing:.08em'>Your Ticket</p>
        <img src='cid:TICKET_IMAGE' alt='Your ticket for {$eventTitle}'
             style='max-width:100%;border-radius:8px;border:1px solid #1E1E28;display:block;margin:0 auto'/>
        " . ($ticketUrl ? "
        <p style='margin:14px 0 0'>
          <a href='{$ticketUrl}' style='color:#C59E59;font-size:13px;text-decoration:none'>
            ↓ Download full-size ticket
          </a>
        </p>" : '') . "
      </div>";
    } elseif ($ticketUrl) {
        $ticketImgSection = "
      <div style='margin:28px 0;text-align:center'>
        <a href='{$ticketUrl}' style='background:#C59E59;color:#0C0C12;padding:14px 32px;
           border-radius:6px;text-decoration:none;font-weight:700;font-size:15px;display:inline-block'>
          View &amp; Download Your Ticket
        </a>
      </div>";
    }

    return <<<HTML
<!DOCTYPE html>
<html><head><meta charset='UTF-8'><meta name='viewport' content='width=device-width,initial-scale=1'></head>
<body style='margin:0;padding:0;background:#0C0C12;font-family:Georgia,serif'>
<div style='max-width:600px;margin:40px auto;background:#181820;border:1px solid #1E1E28;border-radius:12px;overflow:hidden'>
  <div style='background:linear-gradient(90deg,#C59E59,#A07840);height:4px'></div>
  <div style='padding:40px 40px 32px'>
    <p style='color:#C59E59;font-size:11px;font-weight:700;letter-spacing:.14em;text-transform:uppercase;margin:0 0 20px'>{$eventTitle}</p>
    <h2 style='color:#F0EBDC;font-size:24px;font-weight:400;margin:0 0 20px;line-height:1.35'>Dear {$guestName},</h2>
    <div style='color:#9A9AAA;font-size:15px;line-height:1.85'>{$msg}</div>
    {$metaSection}
    {$ticketImgSection}
    <div style='background:#111118;border-radius:6px;padding:14px 18px;border-left:3px solid #C59E59;margin-top:16px'>
      <p style='color:#8A8A9A;font-size:12px;margin:0;line-height:1.6'>
        Your personalised ticket is also attached to this email as an image file.
        Please save it and present it at the entrance.
      </p>
    </div>
  </div>
  <div style='padding:20px 40px;border-top:1px solid #1E1E28;text-align:center'>
    <p style='color:#555566;font-size:11px;margin:0;letter-spacing:.06em'>{$brand}</p>
  </div>
</div>
</body></html>
HTML;
}

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

<style>
.filter-tabs { display:flex;gap:0;margin-bottom:16px;border:1px solid var(--border);border-radius:var(--radius);overflow:hidden }
.filter-tabs a { flex:1;padding:9px 6px;text-align:center;font-family:var(--font-ui);font-size:.68rem;font-weight:700;letter-spacing:.07em;text-transform:uppercase;color:var(--muted);text-decoration:none;border-right:1px solid var(--border);transition:all .2s }
.filter-tabs a:last-child { border-right:none }
.filter-tabs a.active,.filter-tabs a:hover { background:rgba(197,158,89,.1);color:var(--gold) }
</style>

<div class="page-header">
  <div>
    <div class="page-header-sub">Invitations</div>
    <h1>Email Invites</h1>
  </div>
</div>

<?php if ($msg && !$error): ?><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" data-no-loader style="display:flex;gap:12px;align-items:center;flex-wrap:wrap">
    <label class="label-ui" style="white-space:nowrap">Event</label>
    <select class="form-control" name="event_id" style="max-width:320px;flex:1" onchange="this.form.submit()">
      <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>
  </form>
</div>
<div class="alert alert-info">Open an event from the Events page to manage email invites.</div>
<?php else: ?>

<!-- Stats -->
<div class="stats-grid mb-4">
  <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_email']??0) ?></div><div class="stat-label">Have Email</div></div>
  <div class="stat-card success"><div class="stat-value"><?= (int)($stats['sent']??0) ?></div><div class="stat-label">Sent</div></div>
  <div class="stat-card danger"><div class="stat-value"><?= max(0,(int)($stats['has_email']??0)-(int)($stats['sent']??0)) ?></div><div class="stat-label">Pending</div></div>
</div>

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

  <!-- SMTP Config -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">SMTP Settings</span>
      <span class="badge <?= $adminData['smtp_host'] ? 'badge-success' : 'badge-muted' ?>">
        <?= $adminData['smtp_host'] ? '✓ Configured' : 'Not configured' ?>
      </span>
    </div>
    <form method="POST">
      <input type="hidden" name="save_smtp" value="1">
      <div class="form-group">
        <label class="form-label">SMTP Host</label>
        <input class="form-control" type="text" name="smtp_host"
               value="<?= htmlspecialchars($adminData['smtp_host'] ?? '') ?>"
               placeholder="smtp.gmail.com">
      </div>
      <div class="grid-2">
        <div class="form-group">
          <label class="form-label">Port</label>
          <input class="form-control" type="number" name="smtp_port"
                 value="<?= (int)($adminData['smtp_port'] ?? 587) ?>">
        </div>
        <div class="form-group">
          <label class="form-label">Security</label>
          <select class="form-control" name="smtp_secure">
            <?php foreach (['tls'=>'TLS (587)','ssl'=>'SSL (465)','none'=>'None (25)'] as $v=>$l): ?>
              <option value="<?= $v ?>" <?= ($adminData['smtp_secure']??'tls')===$v?'selected':'' ?>><?= $l ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label class="form-label">Username</label>
        <input class="form-control" type="text" name="smtp_user"
               value="<?= htmlspecialchars($adminData['smtp_user'] ?? '') ?>">
      </div>
      <div class="form-group">
        <label class="form-label">Password</label>
        <input class="form-control" type="password" name="smtp_pass"
               placeholder="<?= $adminData['smtp_pass'] ? '••••••••' : 'Enter password' ?>">
        <div class="form-hint">Leave blank to keep existing.</div>
      </div>
      <div class="grid-2">
        <div class="form-group">
          <label class="form-label">From Email</label>
          <input class="form-control" type="email" name="smtp_from"
                 value="<?= htmlspecialchars($adminData['smtp_from'] ?? '') ?>"
                 placeholder="events@yourcompany.com">
        </div>
        <div class="form-group">
          <label class="form-label">From Name</label>
          <input class="form-control" type="text" name="smtp_name"
                 value="<?= htmlspecialchars($adminData['smtp_name'] ?? '') ?>"
                 placeholder="Oaken Events">
        </div>
      </div>
      <div style="display:flex;gap:8px;flex-wrap:wrap">
        <button class="btn btn-gold" type="submit">Save Settings</button>
      </div>
    </form>

    <!-- Test email -->
    <form method="POST" style="margin-top:16px;display:flex;gap:8px">
      <input type="hidden" name="test_smtp" value="1">
      <input class="form-control" type="email" name="test_to"
             value="<?= htmlspecialchars($adminData['email']) ?>" style="flex:1">
      <button class="btn btn-outline" type="submit">Send Test</button>
    </form>
    <div class="form-hint mt-2">
      Common SMTP providers: Gmail (smtp.gmail.com:587 TLS) · Zoho (smtp.zoho.com:587) · Mailgun · Brevo
    </div>
  </div>

  <!-- Template + send -->
  <div>
    <!-- Template -->
    <div class="card mb-3">
      <div class="card-header"><span class="card-title">Email Template</span></div>
      <form method="POST">
        <input type="hidden" name="event_id" value="<?= $eventId ?>">
        <input type="hidden" name="save_template" value="1">
        <div class="form-group">
          <label class="form-label">Subject</label>
          <input class="form-control" type="text" name="email_subject"
                 value="<?= htmlspecialchars($event['email_subject'] ?? '') ?>"
                 placeholder="Your invitation to <?= htmlspecialchars($event['title']) ?>">
        </div>
        <div class="form-group">
          <label class="form-label">Message Body</label>
          <div class="fmt-toolbar">
            <button type="button" class="fmt-btn" title="Bold  *text*"          onclick="fmtWrap('email_message_ta','*')"><b>B</b></button>
            <button type="button" class="fmt-btn" title="Italic  _text_"        onclick="fmtWrap('email_message_ta','_')"><i>I</i></button>
            <button type="button" class="fmt-btn" title="Strikethrough  ~text~" onclick="fmtWrap('email_message_ta','~')"><s>S</s></button>
            <button type="button" class="fmt-btn" title="Monospace  &#96;text&#96;" onclick="fmtWrap('email_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('email_message_ta','{name}')">{name}</button>
            <button type="button" class="fmt-btn" title="Insert event title" onclick="fmtInsert('email_message_ta','{event}')">{event}</button>
          </div>
          <textarea class="form-control" id="email_message_ta" name="email_message" rows="5"
                    placeholder="We are delighted to invite you to {event}.&#10;&#10;Your personalised ticket is attached."><?= htmlspecialchars($event['email_message'] ?? '') ?></textarea>
          <div class="form-hint">
            Select text and use the buttons above —
            <strong>*bold*</strong>, <em>_italic_</em>, <s>~strike~</s>, <code>`mono`</code>.<br>
            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>
        <button class="btn btn-outline" type="submit">Save Template</button>
      </form>
    </div>

    <!-- Batch send -->
    <div class="card">
      <div class="card-header"><span class="card-title">Send Invites</span></div>
      <form method="POST">
        <input type="hidden" name="event_id" value="<?= $eventId ?>">
        <input type="hidden" name="send_emails" value="1">
        <div class="grid-2">
          <div class="form-group">
            <label class="form-label">Batch Size</label>
            <select class="form-control" name="batch_size">
              <?php foreach ([10,20,50,100,200] as $n): ?>
                <option value="<?= $n ?>" <?= $n===20?'selected':'' ?>><?= $n ?> emails</option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="form-group" style="display:flex;flex-direction:column;justify-content:flex-end;gap:6px">
            <label style="display:flex;align-items:center;gap:6px;cursor:pointer;font-size:.8rem;color:var(--muted)">
              <input type="checkbox" name="unsent_only" value="1" checked style="accent-color:var(--gold)"> Unsent only
            </label>
            <label style="display:flex;align-items:center;gap:6px;cursor:pointer;font-size:.8rem;color:var(--muted)">
              <input type="checkbox" name="retry_failed" value="1" style="accent-color:var(--gold)"> Retry failed
            </label>
          </div>
        </div>
        <button class="btn btn-gold" type="submit" data-loader-text="Sending emails…" style="width:100%;justify-content:center;padding:12px">
          📧 Send Email Invites
        </button>
        <div class="form-hint mt-2">
          Each email includes: personalised message · ticket image in body · PDF ticket attached.
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Guest list with per-guest send -->
<div class="card mb-4">
  <div class="card-header" style="flex-wrap:wrap;gap:10px">
    <span class="card-title">
      Guests
      <span class="badge badge-muted" style="margin-left:6px"><?= $totalCount ?? $stats['total'] ?></span>
    </span>
    <form method="GET" data-no-loader style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
      <input type="hidden" name="event_id" value="<?= $eventId ?>">
      <input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">
      <input class="form-control" type="text" name="q" value="<?= htmlspecialchars($search) ?>"
             placeholder="Name or email…" style="width:160px;padding:7px 10px">
      <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>
      <button class="btn btn-outline btn-sm" type="submit">Search</button>
    </form>
  </div>

  <div class="filter-tabs">
    <?php
    $tabs = ['all'=>'All','unsent'=>'Pending','sent'=>'Sent','failed'=>'Failed','no_email'=>'No Email'];
    foreach ($tabs as $fk=>$fl):
      $tabUrl = '?' . http_build_query([
          'event_id' => $eventId, 'filter' => $fk, 'q' => $search, 'sort' => $sort,
      ]);
    ?>
      <a href="<?= htmlspecialchars($tabUrl) ?>"
         class="<?= $filter===$fk?'active':'' ?>"><?= $fl ?></a>
    <?php endforeach; ?>
  </div>

  <div class="table-wrap">
    <table>
      <thead>
        <tr><th>#</th><th>Guest</th><th>Email</th><th>Added</th><th>Ticket</th><th>Status</th><th>Sent At</th><th>Action</th></tr>
      </thead>
      <tbody>
        <?php if (empty($guests)): ?>
          <tr><td colspan="8" class="text-muted" style="padding:32px;text-align:center">No guests in this filter.</td></tr>
        <?php endif; ?>
        <?php foreach ($guests as $i => $g):
          $isSent    = (bool)$g['email_sent'];
          $lastStatus = $g['last_email_status'] ?? ($isSent ? 'sent' : null);
          $lastSentAt = $g['last_sent_at']       ?? $g['email_sent_at'] ?? null;
          $lastError  = $g['last_error']          ?? null;
          $hasTicket  = !empty($g['invite_path']);
          $hasEmail   = !empty($g['email']);
        ?>
        <tr id="erow-<?= $g['id'] ?>">
          <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; ?>
            <?php if ($g['table_number']): ?><span class="badge badge-muted" style="margin-top:3px">T<?= htmlspecialchars($g['table_number']) ?></span><?php endif; ?>
          </td>
          <td class="text-muted text-sm">
            <?= $hasEmail ? htmlspecialchars($g['email']) : '<span class="badge badge-muted">No email</span>' ?>
          </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): ?>
              <span class="badge badge-success">✓ Ready</span>
            <?php else: ?>
              <span class="badge badge-muted">Not generated</span>
            <?php endif; ?>
          </td>
          <td>
            <?php if ($lastStatus === 'sent'): ?>
              <span class="badge badge-success">✓ Sent</span>
            <?php elseif ($lastStatus === 'failed'): ?>
              <span class="badge badge-danger" title="<?= htmlspecialchars($lastError ?? '') ?>">✕ Failed</span>
              <?php if ($lastError): ?>
                <div style="font-size:.65rem;color:var(--danger);max-width:140px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis" title="<?= htmlspecialchars($lastError) ?>">
                  <?= htmlspecialchars(mb_substr($lastError, 0, 35)) ?>
                </div>
              <?php endif; ?>
            <?php else: ?>
              <span class="badge badge-muted">Pending</span>
            <?php endif; ?>
          </td>
          <td class="text-muted text-sm">
            <?= $lastSentAt ? date('M j · H:i', strtotime($lastSentAt)) : '—' ?>
          </td>
          <td>
            <?php if ($hasEmail): ?>
              <form method="POST" style="display:inline">
                <input type="hidden" name="event_id" value="<?= $eventId ?>">
                <input type="hidden" name="send_single" value="1">
                <input type="hidden" name="guest_id" value="<?= $g['id'] ?>">
                <button class="btn btn-outline btn-sm" type="submit"
                        data-loader-text="Sending…">
                  <?= $isSent ? '↺ Resend' : '📧 Send' ?>
                </button>
              </form>
            <?php else: ?>
              <span class="text-muted text-sm">—</span>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <!-- Pagination -->
  <?php if (isset($totalPages) && $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">Page <?= $page ?> of <?= $totalPages ?></div>
    <?php
      // Keep every list control (filter/search/sort) across paging
      $pageUrl = fn(int $p) => '?' . http_build_query([
          'event_id' => $eventId, 'filter' => $filter, 'q' => $search,
          'sort'     => $sort,    'page'   => $p,
      ]);
    ?>
    <div style="display:flex;gap:6px">
      <?php if ($page>1): ?>
        <a href="<?= htmlspecialchars($pageUrl($page-1)) ?>" class="btn btn-outline btn-sm">‹</a>
      <?php endif; ?>
      <?php for ($p=max(1,$page-2); $p<=min($totalPages,$page+2); $p++): ?>
        <a href="<?= htmlspecialchars($pageUrl($p)) ?>"
           class="btn <?= $p===$page?'btn-gold':'btn-outline' ?> btn-sm"><?= $p ?></a>
      <?php endfor; ?>
      <?php if ($page<$totalPages): ?>
        <a href="<?= htmlspecialchars($pageUrl($page+1)) ?>" class="btn btn-outline btn-sm">›</a>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>
</div>

<!-- Send log -->
<?php if (!empty($log)): ?>
<div class="card">
  <div class="card-header">
    <span class="card-title">Send Log</span>
    <span class="badge badge-muted"><?= count($log) ?> entries</span>
  </div>
  <div class="table-wrap">
    <table>
      <thead><tr><th>Guest</th><th>To</th><th>Status</th><th>Error</th><th>Time</th></tr></thead>
      <tbody>
        <?php foreach ($log as $l): ?>
        <tr>
          <td style="font-weight:500"><?= htmlspecialchars($l['guest_name'] ?? '—') ?></td>
          <td class="text-muted text-sm"><?= htmlspecialchars($l['recipient']) ?></td>
          <td><span class="badge <?= $l['status']==='sent'?'badge-success':'badge-danger' ?>"><?= $l['status'] ?></span></td>
          <td>
            <?php if ($l['error_msg']): ?>
              <span style="color:var(--danger);font-size:.75rem" title="<?= htmlspecialchars($l['error_msg']) ?>">
                <?= htmlspecialchars(mb_substr($l['error_msg'], 0, 50)) ?>
              </span>
            <?php else: ?>—<?php endif; ?>
          </td>
          <td class="text-muted text-sm"><?= date('M j · H:i', strtotime($l['sent_at'])) ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php endif; ?>

<?php endif; ?>

<?php layout_end(); ?>
