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

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

$eventsDir = __DIR__ . '/../data/events/';
$eventsIndexFile = __DIR__ . '/../data/events.json';
$legacyPromoFile = __DIR__ . '/../data/promo.json';
$entriesFile = __DIR__ . '/../data/promo_entries.txt';
$settingsFile = __DIR__ . '/../data/settings.json';
if (!is_dir($eventsDir)) mkdir($eventsDir, 0777, true);
ht_migrate_legacy_events_to_files(dirname(__DIR__));

function event_defaults(): array { return ht_event_defaults(); }
function safe_event_file($name) {
  $name = basename((string)$name);
  return preg_match('/^[a-zA-Z0-9._-]+\.json$/', $name) ? $name : '';
}
function rebuild_events_index(string $eventsDir, string $eventsIndexFile, string $legacyPromoFile): void {
  $items = ht_load_event_items(dirname(__DIR__));
  $out = [];
  $firstPublished = null;
  foreach ($items as $item) {
    $item = ht_normalize_event_item($item, (string)($item['source_file'] ?? ''), (int)($item['_mtime'] ?? 0));
    unset($item['_mtime']);
    $out[] = $item;
    if ($firstPublished === null && !empty($item['published'])) $firstPublished = $item;
  }
  smurf_write_json($eventsIndexFile, $out);
  $legacy = ht_event_defaults();
  if ($firstPublished) {
    $legacy = array_merge($legacy, $firstPublished, [
      'enabled' => !empty($firstPublished['published']),
      'pinned' => !empty($firstPublished['featured_home']),
    ]);
  } else {
    $legacy['enabled'] = false;
    $legacy['pinned'] = false;
  }
  smurf_write_json($legacyPromoFile, $legacy);
}

$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;

$action = $_GET['action'] ?? '';
$file = $_GET['file'] ?? '';
if ($action === 'delete' && $file) {
  if (!$CAN_EDIT) smurf_admin_denied('You do not have permission to delete events.');
  $sf = safe_event_file($file);
  if ($sf && file_exists($eventsDir . $sf)) {
    @copy($eventsDir . $sf, $eventsDir . $sf . '.bak');
    unlink($eventsDir . $sf);
    rebuild_events_index($eventsDir, $eventsIndexFile, $legacyPromoFile);
  }
  header('Location: /admin/events.php?deleted=1');
  exit;
}
$editFile = ($action === 'edit' && $file) ? safe_event_file($file) : '';
$event = event_defaults();
if ($editFile && file_exists($eventsDir . $editFile)) $event = ht_normalize_event_item(smurf_read_json($eventsDir . $editFile, []), $editFile, (int)@filemtime($eventsDir . $editFile));

if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_event'])) {
  if (!$CAN_EDIT) smurf_admin_denied('You do not have permission to edit events.');
  $editFile = safe_event_file($_POST['edit_file'] ?? '');
  if (isset($_POST['create_new']) && $_POST['create_new'] === '1') $editFile = '';
  $event = event_defaults();
  $event['title'] = trim((string)($_POST['title'] ?? '')) ?: 'Event';
  $event['start'] = trim((string)($_POST['start'] ?? ''));
  $event['end'] = trim((string)($_POST['end'] ?? ''));
  $event['description'] = trim((string)($_POST['description'] ?? ''));
  $event['image'] = trim((string)($_POST['image'] ?? ''));
  if ($event['image'] === '') {
    $uploaded = smurf_handle_upload('image_file', __DIR__ . '/../img/content');
    if ($uploaded !== '') {
      $event['image'] = $uploaded;
    } elseif ($editFile && file_exists($eventsDir . $editFile)) {
      $existing = smurf_read_json($eventsDir . $editFile, []);
      if (is_array($existing) && !empty($existing['image'])) $event['image'] = (string)$existing['image'];
    }
  }
  $event['published'] = isset($_POST['published']) ? 1 : 0;
  $event['featured_home'] = isset($_POST['featured_home']) ? 1 : 0;
  $event['show_entry_form'] = isset($_POST['show_entry_form']) ? 1 : 0;
  $event['show_external_link'] = isset($_POST['show_external_link']) ? 1 : 0;
  $event['external_url'] = trim((string)($_POST['external_url'] ?? ''));
  $event['external_label'] = trim((string)($_POST['external_label'] ?? 'Open External Events Site'));
  $event['prizes'] = array_values(array_filter(array_map('trim', preg_split('/\r?\n/', (string)($_POST['prizes'] ?? '')))));
  $settings['events_show_in_nav'] = !empty($_POST['events_show_in_nav']);
  smurf_write_json($settingsFile, $settings);

  $slug = preg_replace('/[^a-z0-9]+/i', '-', strtolower($event['title']));
  $slug = trim((string)$slug, '-');
  if ($slug === '') $slug = 'event';
  $fname = $editFile ?: (date('Ymd_His') . '_' . substr(md5(uniqid('', true)), 0, 6) . '_' . $slug . '.json');
  $event['source_file'] = $fname;
  smurf_write_json($eventsDir . $fname, $event);
  rebuild_events_index($eventsDir, $eventsIndexFile, $legacyPromoFile);
  $target = $editFile ? ('/admin/events.php?action=edit&file=' . urlencode($fname) . '&saved=1') : '/admin/events.php?created=1';
  header('Location: ' . $target); 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))));
}
$allItems = ht_load_event_items(dirname(__DIR__));
$q = smurf_q('q');
$status = strtolower(smurf_q('status', 'all'));
$items = array_values(array_filter($allItems, function($item) use ($q, $status) {
  $haystack = implode(' ', [
    (string)($item['title'] ?? ''),
    (string)($item['description'] ?? ''),
    (string)($item['start'] ?? ''),
    implode(' ', (array)($item['prizes'] ?? [])),
  ]);
  if (!smurf_match_text($haystack, $q)) return false;
  return match ($status) {
    'published' => !empty($item['published']),
    'draft' => empty($item['published']),
    'featured' => !empty($item['featured_home']),
    'entryform' => !empty($item['show_entry_form']),
    default => true,
  };
}));
$stats = [
  'all' => count($allItems),
  'published' => count(array_filter($allItems, fn($i) => !empty($i['published']))),
  'draft' => count(array_filter($allItems, fn($i) => empty($i['published']))),
  'featured' => count(array_filter($allItems, fn($i) => !empty($i['featured_home']))),
  'entryform' => count(array_filter($allItems, fn($i) => !empty($i['show_entry_form']))),
];
$eventImage = ht_asset_url((string)($event['image'] ?? ''), 'img/content');
$uploadError = (string)($GLOBALS['SMURF_UPLOAD_ERROR'] ?? '');
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">🎉 Events &amp; Promotions</h1>
  <p style="opacity:.85;">Create multiple events, feature one on the homepage, show or hide the public entry form, and upload event images.</p>

  <?php if (!empty($_GET['saved'])): ?><div class="content-card" style="border-color:rgba(120,255,220,.6);">✅ Event updated</div><?php endif; ?>
  <?php if (!empty($_GET['created'])): ?><div class="content-card" style="border-color:rgba(120,255,220,.6);">✅ Event created</div><?php endif; ?>
  <?php if (!empty($_GET['deleted'])): ?><div class="content-card" style="border-color:rgba(255,160,120,.6);">🗑️ Event deleted</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; ?>
  <?php if ($uploadError !== ''): ?><div class="msg error"><?= smurf_h($uploadError) ?></div><?php endif; ?>

  <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;margin:12px 0 18px;">
    <div class="content-card"><strong><?= (int)$stats['all'] ?></strong><div>Total events</div></div>
    <div class="content-card"><strong><?= (int)$stats['published'] ?></strong><div>Published</div></div>
    <div class="content-card"><strong><?= (int)$stats['draft'] ?></strong><div>Drafts</div></div>
    <div class="content-card"><strong><?= (int)$stats['featured'] ?></strong><div>Featured</div></div>
    <div class="content-card"><strong><?= (int)$stats['entryform'] ?></strong><div>Entry form on</div></div>
  </div>

  <div class="admin-grid-2">
    <div class="content-card" style="text-align:left;">
      <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;flex-wrap:wrap;">
        <h3 style="margin:0;"><?= $editFile ? 'Edit Event' : 'Create Event' ?></h3>
        <?php if ($editFile): ?><a class="admin-btn" href="/admin/events.php">Create New Event</a><?php endif; ?>
      </div>
      <form method="post" action="/admin/events.php" class="admin-form" enctype="multipart/form-data" style="margin-top:12px;">
        <input type="hidden" name="edit_file" value="<?= smurf_h($editFile) ?>">
        <input type="hidden" name="create_new" value="0">
        <label class="admin-label"><input type="checkbox" name="published" <?= !empty($event['published'])?'checked':''; ?>> Published</label>
        <label class="admin-label"><input type="checkbox" name="featured_home" <?= !empty($event['featured_home'])?'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($event['show_entry_form'])?'checked':''; ?>> Show public entry form</label>
        <label class="admin-label"><input type="checkbox" name="show_external_link" <?= !empty($event['show_external_link'])?'checked':''; ?>> Show external events button</label>

        <label class="admin-label">Title</label>
        <input class="admin-input" type="text" name="title" value="<?= htmlspecialchars((string)($event['title'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" placeholder="e.g. Home Time Giveaway Night">
        <label class="admin-label">Start (YYYY-MM-DD HH:MM)</label>
        <input class="admin-input" type="text" name="start" value="<?= htmlspecialchars((string)($event['start'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" placeholder="2026-04-03 18:00">
        <label class="admin-label">End (YYYY-MM-DD HH:MM)</label>
        <input class="admin-input" type="text" name="end" value="<?= htmlspecialchars((string)($event['end'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" placeholder="2026-04-06 23:59">
        <label class="admin-label">Event Image Link</label>
        <input class="admin-input" type="text" name="image" value="<?= htmlspecialchars((string)($event['image'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" 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/*">
        <?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, ENT_QUOTES, 'UTF-8') ?>" 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((string)($event['external_label'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" placeholder="Open External Events Site">
        <label class="admin-label">External Site URL</label>
        <input class="admin-input" type="text" name="external_url" value="<?= htmlspecialchars((string)($event['external_url'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" placeholder="https://events.example.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", $event['prizes'] ?? []), ENT_QUOTES, 'UTF-8') ?></textarea>
        <label class="admin-label">Description</label>
        <textarea class="admin-input" name="description" rows="6" placeholder="Tell listeners what to do…"><?= htmlspecialchars((string)($event['description'] ?? ''), ENT_QUOTES, 'UTF-8') ?></textarea>
        <?php if ($CAN_EDIT): ?><div style="display:flex;gap:10px;flex-wrap:wrap;"><button class="admin-btn" type="submit" name="save_event" value="1"><?= $editFile ? 'Save Event' : 'Create Event' ?></button><?php if ($editFile): ?><button class="admin-btn" type="submit" name="save_event" value="1" onclick="this.form.create_new.value='1';">Save as New Event</button><?php endif; ?></div><?php endif; ?>
      </form>
    </div>

    <div class="content-card" style="text-align:left;">
      <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;flex-wrap:wrap;">
        <h3 style="margin-top:0;">Current Events</h3>
        <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
          <input class="input-field" type="text" name="q" value="<?= smurf_h($q) ?>" placeholder="Search title or description" style="min-width:220px;">
          <select class="input-field" name="status" style="min-width:160px;">
            <option value="all" <?= $status === 'all' ? 'selected' : '' ?>>All events</option>
            <option value="published" <?= $status === 'published' ? 'selected' : '' ?>>Published</option>
            <option value="draft" <?= $status === 'draft' ? 'selected' : '' ?>>Drafts</option>
            <option value="featured" <?= $status === 'featured' ? 'selected' : '' ?>>Featured</option>
            <option value="entryform" <?= $status === 'entryform' ? 'selected' : '' ?>>Entry form on</option>
          </select>
          <button class="admin-btn" type="submit">Filter</button>
          <?php if ($q !== '' || $status !== 'all'): ?><a class="admin-btn" href="/admin/events.php">Reset</a><?php endif; ?>
        </form>
      </div>
      <?php if (empty($items)): ?>
        <p>No events match this view.</p>
      <?php else: ?>
        <?php foreach ($items as $j): $name = (string)($j['source_file'] ?? ''); $imageSrc = ht_asset_url((string)($j['image'] ?? ''), 'img/content'); ?>
          <div class="content-card" style="text-align:left; margin-bottom:12px;">
            <div style="display:flex;justify-content:space-between;gap:14px;align-items:flex-start;flex-wrap:wrap;">
              <div style="display:flex;gap:14px;align-items:flex-start;flex-wrap:wrap;flex:1 1 420px;">
                <?php if ($imageSrc !== ''): ?><img src="<?= smurf_h($imageSrc) ?>" alt="<?= smurf_h((string)$j['title']) ?>" style="width:110px;height:80px;object-fit:cover;border-radius:14px;flex:0 0 auto;"><?php endif; ?>
                <div>
                  <strong><?= smurf_h((string)$j['title']) ?></strong>
                  <div style="opacity:.8;font-size:.95em;"><?= smurf_h((string)$j['start']) ?><?= !empty($j['end']) ? ' → ' . smurf_h((string)$j['end']) : '' ?><?php if($name !== ''): ?> • <code><?= smurf_h($name) ?></code><?php endif; ?></div>
                  <div style="margin-top:6px; display:flex; gap:8px; flex-wrap:wrap;">
                    <span class="badge" style="background:<?= empty($j['published']) ? 'rgba(255,255,255,.08)' : 'rgba(0,204,136,.18)' ?>;padding:4px 8px;border-radius:999px;"><?= empty($j['published']) ? 'Draft' : 'Published' ?></span>
                    <?php if (!empty($j['featured_home'])): ?><span class="badge" style="background:rgba(255,215,0,.18);padding:4px 8px;border-radius:999px;">Featured</span><?php endif; ?>
                    <?php if (!empty($j['show_entry_form'])): ?><span class="badge" style="background:rgba(116,204,255,.18);padding:4px 8px;border-radius:999px;">Entry form on</span><?php endif; ?>
                  </div>
                  <?php if (!empty($j['description'])): ?><div style="margin-top:8px;opacity:.9;"><?= smurf_h(mb_strimwidth((string)$j['description'], 0, 180, '…', 'UTF-8')) ?></div><?php endif; ?>
                </div>
              </div>
              <div style="display:flex;gap:8px;">
                <?php if($name !== ''): ?><a class="admin-btn" href="/admin/events.php?action=edit&file=<?= urlencode($name) ?>">Edit</a><?php endif; ?>
                <?php if ($CAN_EDIT && $name !== ''): ?><a class="admin-btn" href="/admin/events.php?action=delete&file=<?= urlencode($name) ?>" onclick="return confirm('Delete this event?');">Delete</a><?php endif; ?>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>

      <h3 style="margin-top:24px;">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, ENT_QUOTES, 'UTF-8') ?></div><?php endforeach; ?></div><?php endif; ?>
    </div>
  </div>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
