<?php include 'includes/header.php'; ?>
<style>
  .schedule-table { background-color: #000 !important; color: #fff !important; border-color: #444 !important; }
  .schedule-table th, .schedule-table td { background-color: #000 !important; color: #fff !important; border: 1px solid #444 !important; }
  .schedule-table th { font-weight: bold; }
  .schedule-table td strong { color: #fff !important; }
  .schedule-table td small { color: #ccc; display: block; margin-top: 2px; }
</style>
<?php
function ht_schedule_read(string $jsonFile, string $txtFile): array {
  $days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
  $out = [];
  foreach ($days as $d) $out[$d] = [];

  if (is_file($jsonFile)) {
    $j = json_decode((string)file_get_contents($jsonFile), true);
    if (is_array($j)) {
      foreach ($days as $d) {
        $rows = $j[$d] ?? [];
        if (!is_array($rows)) continue;
        foreach ($rows as $h => $val) {
          if (!is_numeric($h)) continue;
          $hh = (int)$h;
          if ($hh < 0 || $hh > 23) continue;
          $out[$d][sprintf('%02d:00', $hh)] = trim((string)$val);
        }
      }
      return $out;
    }
  }

  if (is_file($txtFile)) {
    foreach (file($txtFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
      $parts = array_map('trim', explode('|', trim($line)));
      if (count($parts) < 3) continue;
      [$day, $hour] = [$parts[0], $parts[1]];
      if (!isset($out[$day]) || !preg_match('/^\d{2}:\d{2}$/', $hour)) continue;
      $value = count($parts) >= 4 ? trim($parts[2] . ' — ' . $parts[3], ' —') : $parts[2];
      $out[$day][$hour] = $value;
    }
  }
  return $out;
}
$schedule = ht_schedule_read(__DIR__ . '/data/schedule.json', __DIR__ . '/data/schedule.txt');
$days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
$hours = [];
for ($i = 0; $i < 24; $i++) $hours[] = str_pad((string)$i, 2, '0', STR_PAD_LEFT) . ':00';
?>
<div class="container content-box mt-5">
  <div class="text-center mb-5">
    <h1>Weekly DJ Schedule</h1>
    <p class="subtext">Here’s what’s spinning this week on Home Time Radio (EST timezone)</p>
  </div>
  <div class='table-responsive'>
    <table class='table table-bordered text-center schedule-table'>
      <thead><tr><th>Time (EST)</th><?php foreach ($days as $day): ?><th><?= htmlspecialchars($day, ENT_QUOTES, 'UTF-8') ?></th><?php endforeach; ?></tr></thead>
      <tbody>
      <?php foreach ($hours as $hour): $hour12 = date('g:i A', strtotime($hour)); ?>
        <tr>
          <td><strong><?= htmlspecialchars($hour, ENT_QUOTES, 'UTF-8') ?></strong><small>(<?= htmlspecialchars($hour12, ENT_QUOTES, 'UTF-8') ?>)</small></td>
          <?php foreach ($days as $day): ?><td><?= htmlspecialchars((string)($schedule[$day][$hour] ?? ''), ENT_QUOTES, 'UTF-8') ?></td><?php endforeach; ?>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include 'includes/footer.php'; ?>
