<?php
date_default_timezone_set('America/New_York');
header('Content-Type: application/json; charset=utf-8');

function ht_schedule_now_map(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;
      $out[$day][$hour] = count($parts) >= 4 ? trim($parts[2] . ' — ' . $parts[3], ' —') : $parts[2];
    }
  }
  return $out;
}

$schedule = ht_schedule_now_map(__DIR__ . '/data/schedule.json', __DIR__ . '/data/schedule.txt');
function format12Hour(string $hour24): string { return date('g:i A', strtotime($hour24)); }
function getDayNameOffset(string $dayName, int $offsetDays): string {
  $base = new DateTime('this ' . $dayName, new DateTimeZone('America/New_York'));
  if ($offsetDays !== 0) $base->modify(($offsetDays > 0 ? '+' : '') . $offsetDays . ' day');
  return $base->format('l');
}
function djAt(array $schedule, string $day, string $hour): string { return trim((string)($schedule[$day][$hour] ?? '')) ?: 'auto dj'; }
$currentDay = date('l');
$currentHour = date('H') . ':00';
$currentHourNum = (int)substr($currentHour, 0, 2);
$currentDJ = djAt($schedule, $currentDay, $currentHour);
$nextHourNum = ($currentHourNum + 1) % 24;
$nextHour = str_pad((string)$nextHourNum, 2, '0', STR_PAD_LEFT) . ':00';
$nextDay = $currentHourNum === 23 ? getDayNameOffset($currentDay, 1) : $currentDay;
$nextDJ = djAt($schedule, $nextDay, $nextHour);
$afterHourNum = ($currentHourNum + 2) % 24;
$afterHour = str_pad((string)$afterHourNum, 2, '0', STR_PAD_LEFT) . ':00';
$afterDay = $currentHourNum >= 22 ? getDayNameOffset($currentDay, 1) : $currentDay;
$afterDJ = djAt($schedule, $afterDay, $afterHour);

echo json_encode([
  'current' => ['dj' => $currentDJ, 'hour' => format12Hour($currentHour)],
  'next'    => ['dj' => $nextDJ,    'hour' => format12Hour($nextHour)],
  'after'   => ['dj' => $afterDJ,   'hour' => format12Hour($afterHour)]
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
