<?php
session_start();
require __DIR__ . '/auth.php';
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'=>'',
  'image'=>'',
  'show_entry_form'=>true,
  'show_external_link'=>false,
  'external_url'=>'https://events.broadcasturself.com/',
  'external_label'=>'Open External Events Site',
]);
if (!is_array($promo)) $promo = [];
$promo = array_merge([
  'enabled'=>false,
  'pinned'=>false,
  'title'=>'',
  'start'=>'',
  'end'=>'',
  'prizes'=>[],
  'description'=>'',
  'image'=>'',
  'show_entry_form'=>true,
  'show_external_link'=>false,
  'external_url'=>'https://events.broadcasturself.com/',
  'external_label'=>'Open External Events Site',
], $promo);

$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']);
  $promo['show_entry_form'] = !empty($_POST['show_entry_form']);
  $promo['show_external_link'] = !empty($_POST['show_external_link']);
  $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'] ?? ''));
  $promo['external_url'] = trim((string)($_POST['external_url'] ?? 'https://events.broadcasturself.com/'));
  $promo['external_label'] = trim((string)($_POST['external_label'] ?? 'Open External Events Site'));
  $promo['image'] = trim((string)($_POST['image'] ?? ''));
  if ($promo['image'] === '') {
    $uploaded = smurf_handle_upload('image_file', __DIR__ . '/../img/content');
    if ($uploaded !== '') $promo['image'] = $uploaded;
  }

  $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: events.php?saved=1'); exit;
}

if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['clear_entries']) && $CAN_EDIT) {
  file_put_contents($entriesFile, '');
  header('Location: 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))));
}

$eventImage = smurf_image_src((string)($promo['image'] ?? ''), 'img/content');
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">🎉 Events & Promotions</h1>
  <p style="opacity:.85;">Create an event card, add an image, control the public entry form, and link out to your external events site.</p>

  <div style="margin:10px 0 18px;display:flex;gap:10px;flex-wrap:wrap;">
    <a class="admin-btn" href="index.php">Back</a>
    <a class="admin-btn" href="https://events.broadcasturself.com/" target="_blank" rel="noopener">Open External Events Site</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="events.php" class="admin-form" enctype="multipart/form-data">
        <label class="admin-label"><input type="checkbox" name="enabled" <?= !empty($promo['enabled'])?'checked':''; ?>> Enable events page content</label>
        <label class="admin-label"><input type="checkbox" name="pinned" <?= !empty($promo['pinned'])?'checked':''; ?>> Feature on 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"><input type="checkbox" name="show_entry_form" <?= !empty($promo['show_entry_form'])?'checked':''; ?>> Show “Enter Now” form on public page</label>
        <label class="admin-label"><input type="checkbox" name="show_external_link" <?= !empty($promo['show_external_link'])?'checked':''; ?>> Show external events site button on public page</label>

        <label class="admin-label">Title</label>
        <input class="admin-input" type="text" name="title" value="<?= htmlspecialchars($promo['title'] ?? '') ?>" placeholder="e.g. Thunder 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">Event Image Link</label>
        <input class="admin-input" type="text" name="image" value="<?= htmlspecialchars($promo['image'] ?? '') ?>" placeholder="https://example.com/event.jpg">

        <label class="admin-label">Or Upload Event Image</label>
        <input class="admin-input" type="file" name="image_file" accept="image/*">
        <div class="admin-note" style="margin-top:-4px;">Use a portrait or square image around a couple sizes bigger than passport photo. It will be shown in compact featured cards.</div>

        <?php if ($eventImage !== ''): ?>
          <div class="content-card" style="margin-top:10px;text-align:left;">
            <strong>Current Event Image</strong>
            <div style="margin-top:10px;">
              <img src="<?= htmlspecialchars($eventImage) ?>" alt="Event image" style="width:140px;height:180px;object-fit:cover;border-radius:14px;display:block;">
            </div>
          </div>
        <?php endif; ?>

        <label class="admin-label">External Site Button Text</label>
        <input class="admin-input" type="text" name="external_label" value="<?= htmlspecialchars($promo['external_label'] ?? '') ?>" placeholder="Open External Events Site">

        <label class="admin-label">External Site URL</label>
        <input class="admin-input" type="text" name="external_url" value="<?= htmlspecialchars($promo['external_url'] ?? 'https://events.broadcasturself.com/') ?>" placeholder="https://events.broadcasturself.com/">

        <label class="admin-label">Prize list (one per line)</label>
        <textarea class="admin-input" name="prizes" rows="6" placeholder="Prize 1&#10;Prize 2&#10;Prize 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="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'; ?>
