<?php
session_start();
$pageTitle = "Schedule";
$pageClass = "page-schedule";
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/nav.php';

$scheduleJson = __DIR__ . '/data/schedule.json';
$scheduleTxt  = __DIR__ . '/data/schedule.txt';

// Load schedule from JSON; if empty, import legacy TXT automatically.
function smurf_load_schedule($jsonFile, $txtFile) {
  $days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];

  if (file_exists($jsonFile) && filesize($jsonFile) > 5) {
    $j = json_decode(file_get_contents($jsonFile), true);
    if (is_array($j) && !empty($j)) return $j;
  }

  if (file_exists($txtFile) && filesize($txtFile) > 0) {
    $out = [];
    foreach ($days as $d) $out[$d] = [];

    foreach (file($txtFile, FILE_IGNORE_NEW_LINES) as $line) {
      $line = trim($line);
      if ($line === '' || str_starts_with($line,'#')) continue;

      // supported formats:
      // Day|HH:MM|DJ
      // Day|HH:MM|Show Title|DJ
      $parts = array_map('trim', explode('|', $line));
      if (count($parts) < 3) continue;

      $day = $parts[0];
      $time = $parts[1];

      if (!in_array($day, $days, true)) continue;
      if (!preg_match('/^\d{2}:\d{2}$/', $time)) continue;

      $title = '';
      $dj = '';

      if (count($parts) >= 4) { $title = $parts[2]; $dj = $parts[3]; }
      else { $dj = $parts[2]; }

      $out[$day][] = ['time'=>$time,'title'=>$title,'dj'=>$dj];
    }

    @file_put_contents($jsonFile, json_encode($out, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE), LOCK_EX);
    return $out;
  }

  $out = [];
  foreach ($days as $d) $out[$d] = [];
  return $out;
}

$schedule = smurf_load_schedule($scheduleJson, $scheduleTxt);

// UK time
$nowUK = new DateTime("now", new DateTimeZone("Europe/London"));
$currentHour = (int)$nowUK->format("H");
$currentDay  = $nowUK->format("l");

// Format toggle (12 or 24)
$format = (isset($_GET['format']) && $_GET['format'] === '24') ? '24' : '12';

function formatHour($h, $format) {
  if ($format === '24') return sprintf("%02d:00", $h);
  return date("g:00 A", strtotime("$h:00"));
}

$days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
?>
<main class="content-area page-schedule">

  <div class="smurf-divider"></div>

  <div class="content-wrapper">
    <section class="content-card center-text">
      <h1>📅 Weekly Schedule</h1>
      <p>All times shown in UK Time (Europe/London)</p>

      <div class="schedule-format-switch">
        <a href="?format=12" class="<?= $format==='12'?'active':'' ?>">12‑Hour</a>
        <a href="?format=24" class="<?= $format==='24'?'active':'' ?>">24‑Hour</a>
      </div>
    </section>
  </div>

  <div class="smurf-divider"></div>

  <div class="content-wrapper">
    <div class="schedule-grid">
      <?php foreach ($days as $day): ?>
        <?php
          $dayShows = (isset($schedule[$day]) && is_array($schedule[$day])) ? $schedule[$day] : [];
          // $dayShows is expected as [hour => "Show Name"]
          // Keep only valid hours and sort
          $filtered = [];
          foreach ($dayShows as $h => $name) {
            if (!is_numeric($h)) continue;
            $hh = (int)$h;
            if ($hh < 0 || $hh > 23) continue;
            $name = trim((string)$name);
            if ($name === '') continue;
            $filtered[$hh] = $name;
          }
          ksort($filtered);
          $isToday = ($day === $currentDay);
        ?>
        <section class="content-card schedule-day-card <?= $isToday ? 'today' : '' ?>">
          <div class="schedule-day-head">
            <h2><?= htmlspecialchars($day) ?></h2>
            <?php if ($isToday): ?><span class="badge-live">Today</span><?php endif; ?>
          </div>

          <?php if (empty($filtered)): ?>
            <div class="schedule-empty">No shows listed.</div>
          <?php else: ?>
            <div class="schedule-list">
              <?php foreach ($filtered as $h => $name): ?>
                <?php $isNow = ($isToday && $h === $currentHour); ?>
                <div class="schedule-row <?= $isNow ? 'current-hour' : '' ?>">
                  <div class="schedule-time"><?= htmlspecialchars(formatHour($h, $format)) ?></div>
                  <div class="schedule-show"><?= htmlspecialchars($name) ?></div>
                </div>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>

        </section>
      <?php endforeach; ?>
    </div>
  </div>

  <div class="smurf-divider"></div>

</main>
<?php include __DIR__ . '/includes/footer.php'; ?>
