<?php
session_start();
require __DIR__ . '/includes/admin_lib.php';


if (!$CAN_VIEW) { http_response_code(403); echo "<h1>Access Denied</h1>"; exit; }

$promoFile = __DIR__ . '/../data/promo.json';
$entriesFile = __DIR__ . '/../data/promo_entries.txt';
$promo = smurf_read_json($promoFile, ['enabled'=>false,'pinned'=>false,'title'=>'','start'=>'','end'=>'','prizes'=>[],'description'=>'']);
if (!is_array($promo)) $promo = ['enabled'=>false,'pinned'=>false,'title'=>'','start'=>'','end'=>'','prizes'=>[],'description'=>''];
$settingsFile = __DIR__ . '/../data/settings.json';
$settings = smurf_read_json($settingsFile, []);
if (!is_array($settings)) $settings = [];
$eventsShowNav = array_key_exists('events_show_in_nav', $settings) ? !empty($settings['events_show_in_nav']) : true;

if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_promo']) && $CAN_EDIT) {
  $promo['enabled'] = !empty($_POST['enabled']);
  $promo['pinned'] = !empty($_POST['pinned']);
  $settings['events_show_in_nav'] = !empty($_POST['events_show_in_nav']);
  smurf_write_json($settingsFile, $settings);
  $promo['title'] = trim((string)($_POST['title'] ?? ''));
  $promo['start'] = trim((string)($_POST['start'] ?? ''));
  $promo['end'] = trim((string)($_POST['end'] ?? ''));
  $promo['description'] = trim((string)($_POST['description'] ?? ''));
  $pr = trim((string)($_POST['prizes'] ?? ''));
  $promo['prizes'] = array_values(array_filter(array_map('trim', preg_split("/\r?\n/", $pr))));
  smurf_write_json($promoFile, $promo);
  header('Location: /admin/events.php?saved=1'); exit;
}

if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['clear_entries']) && $CAN_EDIT) {
  file_put_contents($entriesFile, '');
  header('Location: /admin/events.php?cleared=1'); exit;
}

$entries = [];
if (file_exists($entriesFile) && filesize($entriesFile)>0) {
  $entries = array_reverse(array_filter(array_map('trim', file($entriesFile, FILE_IGNORE_NEW_LINES))));
}
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">🎉 Events & Promotions</h1>
  <p style="opacity:.85;">Create a promo, show a countdown on the site, and collect entries.</p>

  <div style="margin:10px 0 18px;">
    <a class="admin-btn" href="/admin/index.php">Back</a>
  </div>

  <?php if (!empty($_GET['saved'])): ?><div class="content-card" style="border-color:rgba(120,255,220,.6);">✅ Saved</div><?php endif; ?>
  <?php if (!empty($_GET['cleared'])): ?><div class="content-card" style="border-color:rgba(255,120,120,.6);">🧹 Entries cleared</div><?php endif; ?>

  <div class="admin-grid-2">
    <div class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;">Current Promotion</h3>
      <form method="post" action="/admin/events.php" class="admin-form">
        <label class="admin-label"><input type="checkbox" name="enabled" <?= !empty($promo['enabled'])?'checked':''; ?>> Enable promo</label>
        <label class="admin-label"><input type="checkbox" name="pinned" <?= !empty($promo['pinned'])?'checked':''; ?>> Pin to Home Page</label>
        <label class="admin-label"><input type="checkbox" name="events_show_in_nav" <?= $eventsShowNav?'checked':''; ?>> Show Events link in navigation</label>

        <label class="admin-label">Title</label>
        <input class="admin-input" type="text" name="title" value="<?= htmlspecialchars($promo['title'] ?? '') ?>" placeholder="e.g. Smurfette’s Giveaway Night">

        <label class="admin-label">Start (YYYY-MM-DD HH:MM) UK</label>
        <input class="admin-input" type="text" name="start" value="<?= htmlspecialchars($promo['start'] ?? '') ?>" placeholder="2026-04-03 18:00">

        <label class="admin-label">End (YYYY-MM-DD HH:MM) UK</label>
        <input class="admin-input" type="text" name="end" value="<?= htmlspecialchars($promo['end'] ?? '') ?>" placeholder="2026-04-06 23:59">

        <label class="admin-label">Prize list (one per line)</label>
        <textarea class="admin-input" name="prizes" rows="6" placeholder="Prize 1\nPrize 2\nPrize 3"><?= htmlspecialchars(implode("\n", $promo['prizes'] ?? [])) ?></textarea>

        <label class="admin-label">Description</label>
        <textarea class="admin-input" name="description" rows="6" placeholder="Tell listeners what to do…"><?= htmlspecialchars($promo['description'] ?? '') ?></textarea>

        <?php if ($CAN_EDIT): ?>
          <button class="admin-btn" type="submit" name="save_promo" value="1">Save Promotion</button>
        <?php else: ?>
          <p style="opacity:.8;">You have view-only access.</p>
        <?php endif; ?>
      </form>
    </div>

    <div class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;">Entries</h3>
      <p style="opacity:.8;">Stored in <code>/data/promo_entries.txt</code></p>

      <?php if ($CAN_EDIT): ?>
        <form method="post" action="/admin/events.php" onsubmit="return confirm('Clear all entries?');">
          <button class="admin-btn" type="submit" name="clear_entries" value="1">Clear Entries</button>
        </form>
      <?php endif; ?>

      <?php if (empty($entries)): ?>
        <p>No entries yet.</p>
      <?php else: ?>
        <div style="max-height:420px;overflow:auto;padding-right:6px;">
          <?php foreach ($entries as $line): ?>
            <div style="border:1px solid rgba(255,215,120,.25);border-radius:10px;padding:10px;margin:10px 0;opacity:.95;">
              <?= htmlspecialchars($line) ?>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </div>
  </div>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
