<?php
session_start();
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/nav.php';

$promoFile = __DIR__ . '/data/promo.json';
$promo = file_exists($promoFile) ? json_decode((string)file_get_contents($promoFile), true) : [];
if (!is_array($promo)) $promo = [];
$promo = array_merge([
  'enabled' => false,
  'title' => '',
  'start' => '',
  'end' => '',
  'description' => '',
  'prizes' => [],
  'image' => '',
  'show_entry_form' => true,
  'show_external_link' => false,
  'external_url' => 'https://events.broadcasturself.com/',
  'external_label' => 'Open External Events Site',
], $promo);
$enabled = !empty($promo['enabled']);
$sent = !empty($_GET['sent']);
$error = $_GET['err'] ?? '';
$image = trim((string)($promo['image'] ?? ''));
if ($image !== '' && !preg_match('~^(https?:)?//~i', $image) && strpos($image, '/img/') !== 0) {
  $image = '/img/content/' . ltrim($image, '/');
}
$showEntryForm = !empty($promo['show_entry_form']);
$showExternalLink = !empty($promo['show_external_link']) && trim((string)($promo['external_url'] ?? '')) !== '';
?>
<main class="content-area">
  <div class="smurf-divider"></div>
  <div class="content-wrapper">
    <section class="content-card center-text"><h1>🎉 Events & Promotions</h1><p>What’s happening on Thunder Mountain.</p></section>
    <div class="smurf-divider"></div>
    <?php if (!$enabled): ?>
      <section class="content-card center-text"><h2>No promotions running right now</h2><p style="opacity:.85;">Check back soon.</p></section>
    <?php else: ?>
      <section class="content-card" style="text-align:left;">
        <div style="display:flex;gap:18px;align-items:flex-start;flex-wrap:wrap;">
          <?php if ($image !== ''): ?><div style="flex:0 0 auto;"><img src="<?= htmlspecialchars($image) ?>" alt="Event image" style="width:140px;height:180px;object-fit:cover;border-radius:14px;display:block;"></div><?php endif; ?>
          <div style="flex:1 1 320px;min-width:0;">
            <h2 style="margin-top:0;"><?= htmlspecialchars($promo['title'] ?: 'Promotion') ?></h2>
            <?php $start = trim((string)($promo['start'] ?? '')); $end = trim((string)($promo['end'] ?? '')); ?>
            <?php if ($start || $end): ?>
              <div class="content-card" style="margin-top:12px;"><strong>⏳ Countdown</strong><div id="promoCountdown" style="margin-top:10px;font-size:1.2em;"></div>
                <script>(function(){const el=document.getElementById('promoCountdown');const endStr=<?= json_encode($end) ?>;if(!endStr){el.textContent='—';return;}const end=new Date(endStr.replace(' ','T')+':00+01:00');function tick(){const now=new Date();let ms=end-now;if(ms<=0){el.textContent='This promotion has ended.';return;}const s=Math.floor(ms/1000),d=Math.floor(s/86400),h=Math.floor((s%86400)/3600),m=Math.floor((s%3600)/60),ss=s%60;el.textContent=d+'d '+h+'h '+m+'m '+ss+'s';}tick();setInterval(tick,1000);})();</script>
              </div>
            <?php endif; ?>
            <?php if (!empty($promo['description'])): ?><p style="margin-top:14px;white-space:pre-wrap;"><?= htmlspecialchars($promo['description']) ?></p><?php endif; ?>
            <?php if ($showExternalLink): ?><div style="margin-top:14px;"><a href="<?= htmlspecialchars($promo['external_url']) ?>" target="_blank" rel="noopener" class="btn-accent"><?= htmlspecialchars($promo['external_label'] ?: 'Open External Events Site') ?></a></div><?php endif; ?>
          </div>
        </div>
        <?php if (!empty($promo['prizes']) && is_array($promo['prizes'])): ?><h3 style="margin-top:18px;">🏆 Prizes</h3><ul><?php foreach ($promo['prizes'] as $p): ?><li><?= htmlspecialchars($p) ?></li><?php endforeach; ?></ul><?php endif; ?>
      </section>
      <?php if ($showEntryForm): ?>
        <div class="smurf-divider"></div>
        <section class="content-card" style="text-align:left;">
          <h2 style="margin-top:0;">🎟️ Enter Now</h2>
          <?php if ($sent): ?><div class="content-card" style="border-color:rgba(120,255,220,.6);">✅ Entry received! Good luck!</div><?php elseif ($error): ?><div class="content-card" style="border-color:rgba(255,120,120,.6);">⚠️ <?= htmlspecialchars($error) ?></div><?php endif; ?>
          <form method="post" action="/send_promo_entry.php" class="request-wrapper"><div class="request-box"><div class="request-field"><label>Your Name</label><input type="text" class="request-input" name="name" required></div><div class="request-field"><label>Your Email</label><input type="email" class="request-input" name="email" required></div><div class="request-field"><label>Message (optional)</label><textarea class="request-input" name="message" rows="4" placeholder="Tell us why you should win"></textarea></div><button type="submit" class="btn-accent">Submit Entry 🎉</button></div></form>
        </section>
      <?php endif; ?>
    <?php endif; ?>
  </div>
</main>
<?php include __DIR__ . '/includes/footer.php'; ?>
