<?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'];

  // 1) Try JSON first
  if (file_exists($jsonFile) && filesize($jsonFile) > 5) {
    $j = json_decode(file_get_contents($jsonFile), true);
    if (is_array($j) && !empty($j)) {

      // If someone saved the "list of objects" format by mistake, auto-migrate it
      $looksLikeList = false;
      foreach ($days as $d) {
        if (!isset($j[$d])) continue;
        if (isset($j[$d][0]) && is_array($j[$d][0]) && isset($j[$d][0]['time'])) { $looksLikeList = true; break; }
      }

      if ($looksLikeList) {
        $fixed = [];
        foreach ($days as $d) $fixed[$d] = [];
        foreach ($days as $d) {
          $list = (isset($j[$d]) && is_array($j[$d])) ? $j[$d] : [];
          foreach ($list as $row) {
            if (!is_array($row)) continue;
            $time = trim((string)($row['time'] ?? ''));
            if (!preg_match('/^\d{2}:\d{2}$/', $time)) continue;
            $hour = (int)substr($time, 0, 2);

            $title = trim((string)($row['title'] ?? ''));
            $dj    = trim((string)($row['dj'] ?? ''));
            $val   = $title !== '' ? $title : $dj;
            if ($title !== '' && $dj !== '' && $title !== $dj) $val = $title . ' — ' . $dj;

            if ($val !== '') $fixed[$d][$hour] = $val;
          }
          ksort($fixed[$d]);
        }
        @file_put_contents($jsonFile, json_encode($fixed, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT), LOCK_EX);
        return $fixed;
      }

      // Ensure format is day => hour => string
      return $j;
    }
  }

  // 2) Fall back to legacy TXT: Day|HH:MM|Show or DJ  (or Day|HH:MM|Show Title|DJ)
  $out = [];
  foreach ($days as $d) $out[$d] = [];

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

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

      $hour = (int)substr($time, 0, 2);

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

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

      $val = $title !== '' ? $title : $dj;
      if ($title !== '' && $dj !== '' && $title !== $dj) $val = $title . ' — ' . $dj;

      if ($val !== '') $out[$day][$hour] = $val;
    }

    foreach ($days as $d) ksort($out[$d]);
    @file_put_contents($jsonFile, json_encode($out, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT), LOCK_EX);
  }

  return $out;
}

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

// ET/USA time
$nowUK = new DateTime("now", new DateTimeZone("America/New_York"));
$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"));
}

// Split "Show — DJ" into parts for nicer display
function smurf_split_show($val) {
  $val = trim((string)$val);
  if ($val === '') return ['',''];
  $parts = explode('—', $val, 2);
  if (count($parts) === 2) return [trim($parts[0]), trim($parts[1])];
  return [$val, ''];
}

$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 ET / USA Time (America/New_York)</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 schedule-grid--vertical">
      <?php foreach ($days as $day): ?>
        <?php
          $dayShows = (isset($schedule[$day]) && is_array($schedule[$day])) ? $schedule[$day] : [];

          // normalize to hour=>string
          $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);

          $morning = [];
          $evening = [];
          foreach ($filtered as $h => $name) {
            if ($h < 12) $morning[$h] = $name;
            else $evening[$h] = $name;
          }
        ?>

        <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-split">
              <div class="schedule-half">
                <h3>🌅 Morning</h3>
                <?php if (empty($morning)): ?>
                  <div class="schedule-empty">No shows listed.</div>
                <?php else: ?>
                  <?php foreach ($morning as $h => $val): ?>
                    <?php $isNow = ($isToday && $h === $currentHour); ?>
                    <?php [$show,$dj] = smurf_split_show($val); ?>
                    <div class="slot-row <?= $isNow ? 'current-hour' : '' ?>">
                      <div class="slot-time"><?= htmlspecialchars(formatHour($h, $format)) ?></div>
                      <div class="slot-pill">
                        <div class="slot-show"><?= htmlspecialchars($show) ?></div>
                        <?php if ($dj !== ''): ?><div class="slot-dj">🎙 <?= htmlspecialchars($dj) ?></div><?php endif; ?>
                      </div>
                    </div>
                  <?php endforeach; ?>
                <?php endif; ?>
              </div>

              <div class="schedule-half">
                <h3>🌙 Evening</h3>
                <?php if (empty($evening)): ?>
                  <div class="schedule-empty">No shows listed.</div>
                <?php else: ?>
                  <?php foreach ($evening as $h => $val): ?>
                    <?php $isNow = ($isToday && $h === $currentHour); ?>
                    <?php [$show,$dj] = smurf_split_show($val); ?>
                    <div class="slot-row <?= $isNow ? 'current-hour' : '' ?>">
                      <div class="slot-time"><?= htmlspecialchars(formatHour($h, $format)) ?></div>
                      <div class="slot-pill">
                        <div class="slot-show"><?= htmlspecialchars($show) ?></div>
                        <?php if ($dj !== ''): ?><div class="slot-dj">🎙 <?= htmlspecialchars($dj) ?></div><?php endif; ?>
                      </div>
                    </div>
                  <?php endforeach; ?>
                <?php endif; ?>
              </div>
            </div>
          <?php endif; ?>

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

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

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