<?php
// event/index.php
// Handles both:
//   Direct:  /event/index.php?slug=my-event  (always works)
//   Routed:  /event/my-event  (requires mod_rewrite)
require_once __DIR__ . '/../config.php';

// Get slug from multiple possible sources
$slug = '';
if (!empty($_GET['slug'])) {
    $slug = trim($_GET['slug']);
} else {
    // Try to extract from REQUEST_URI directly (fallback if .htaccess routing works differently)
    $uri  = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $base = parse_url(BASE_URL, PHP_URL_PATH) ?? '';
    $path = ltrim(str_replace($base, '', $uri), '/');
    // Path should now be like "event/my-slug"
    if (preg_match('#^event/([a-z0-9_\-]+)#i', $path, $m)) {
        $slug = $m[1];
    }
}

$slug = preg_replace('/[^a-z0-9_\-]/i', '', strtolower(trim($slug)));

if (!$slug) {
    include __DIR__ . '/not_found.php';
    exit;
}

$db   = db();
$stmt = $db->prepare('SELECT e.*, a.org_name FROM events e
                      JOIN admins a ON a.id = e.admin_id
                      WHERE e.slug=? AND e.status != "draft"');
$stmt->execute([$slug]);
$event = $stmt->fetch();
$brand = $event['org_name'] ?? '' ?: ($event['title'] ?? 'Events');

if (!$event) {
    include __DIR__ . '/not_found.php';
    exit;
}

$total = (int)$db->prepare('SELECT COUNT(*) FROM guests WHERE event_id=?')
    ->execute([$event['id']]) ?
    $db->query("SELECT COUNT(*) FROM guests WHERE event_id=".(int)$event['id'])->fetchColumn() : 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= htmlspecialchars($event['title']) ?></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" media="print" onload="this.media='all'" href="https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700;800&family=DM+Sans:wght@300;400;500&display=swap">
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/main.css">
<meta property="og:title" content="<?= htmlspecialchars($event['title']) ?>">
<meta property="og:description" content="<?= htmlspecialchars($event['description'] ?? '') ?>">
</head>
<body>
<div style="min-height:100vh;display:flex;align-items:center;justify-content:center;padding:40px 20px;
            background:radial-gradient(ellipse at 30% 20%,rgba(197,158,89,.08) 0%,transparent 60%),
                       radial-gradient(ellipse at 70% 80%,rgba(197,158,89,.05) 0%,transparent 60%),
                       var(--obsidian)">
  <div style="max-width:520px;width:100%;text-align:center">
    <div style="width:48px;height:3px;background:var(--gold);margin:0 auto 32px"></div>
    <div class="label-ui" style="color:var(--gold);margin-bottom:12px">You're Invited</div>
    <h1 style="font-family:var(--font-display);font-size:clamp(2rem,5vw,3rem);margin-bottom:16px;line-height:1.1">
      <?= htmlspecialchars($event['title']) ?>
    </h1>
    <?php if ($event['description']): ?>
    <p style="color:var(--muted);font-size:.95rem;max-width:380px;margin:0 auto 28px;line-height:1.7">
      <?= nl2br(htmlspecialchars($event['description'])) ?>
    </p>
    <?php endif; ?>
    <div style="display:flex;justify-content:center;gap:32px;margin-bottom:36px;flex-wrap:wrap">
      <?php if ($event['event_date']): ?>
      <div>
        <div class="label-ui" style="margin-bottom:4px">Date</div>
        <div style="font-family:var(--font-display);font-size:1.05rem">
          <?= htmlspecialchars(fmtEventTime($event['event_date'], $event, 'l, F j, Y')) ?>
        </div>
        <div style="color:var(--muted);font-size:.85rem">
          <?= htmlspecialchars(fmtEventTime($event['event_date'], $event, 'g:i A')) ?>
        </div>
      </div>
      <?php endif; ?>
      <?php if ($event['venue']): ?>
      <div>
        <div class="label-ui" style="margin-bottom:4px">Venue</div>
        <div style="font-family:var(--font-display);font-size:1.05rem">
          <?= htmlspecialchars($event['venue']) ?>
        </div>
      </div>
      <?php endif; ?>
    </div>
    <?php if ($event['status'] === 'active'): ?>
    <div style="background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);padding:28px;text-align:left">
      <div class="label-ui" style="margin-bottom:14px">Find Your Invite</div>
      <div style="display:flex;gap:8px">
        <input class="form-control" type="text" id="nameInput"
               placeholder="Enter your name or email…"
               onkeydown="if(event.key==='Enter')findGuest()">
        <button class="btn btn-gold" onclick="findGuest()">Find</button>
      </div>
      <div id="guest-result" style="margin-top:16px"></div>
    </div>
    <?php else: ?>
    <div class="badge badge-danger" style="font-size:.8rem;padding:8px 16px">Registration Closed</div>
    <?php endif; ?>
    <div style="margin-top:48px;color:var(--muted);font-size:.75rem;font-family:var(--font-ui);letter-spacing:.08em">
      <?= htmlspecialchars(strtoupper($brand)) ?>
    </div>
  </div>
</div>
<script>
function findGuest() {
  const q = document.getElementById('nameInput').value.trim();
  if (!q) return;
  const el = document.getElementById('guest-result');
  el.innerHTML = '<div class="text-muted text-sm">Searching…</div>';
  fetch('<?= BASE_URL ?>/api/search_guest.php?q='+encodeURIComponent(q)+'&event_id=<?= $event['id'] ?>&public=1')
    .then(r=>r.json())
    .then(guests=>{
      if (!guests.length) {
        el.innerHTML='<div class="alert alert-danger">No guest found. Contact the event organiser.</div>';
        return;
      }
      el.innerHTML=guests.map(g=>`
        <div style="display:flex;align-items:center;justify-content:space-between;
                    padding:12px 14px;background:var(--surface-2);
                    border:1px solid var(--border);border-radius:var(--radius);margin-bottom:8px">
          <div>
            <div style="font-weight:500">${esc(g.name)}</div>
            ${g.category?`<span class="badge badge-gold" style="margin-top:4px">${esc(g.category)}</span>`:''}
            ${g.table_number?`<span class="badge badge-muted" style="margin-top:4px">Table ${esc(g.table_number)}</span>`:''}
          </div>
          ${g.invite_path
            ?`<a href="<?= BASE_URL ?>/${esc(g.invite_path||'')}" target="_blank" class="btn btn-gold btn-sm">View Ticket</a>`
            :`<span class="badge badge-muted">Ticket pending</span>`}
        </div>`).join('');
    });
}
function esc(s){return String(s||'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))}
</script>
</body>
</html>
