<?php
date_default_timezone_set('America/New_York');

header('Content-Type: application/json; charset=utf-8');

$scheduleFile = 'schedule.txt';

// Read schedule.txt into $schedule[DayName][HH:00] = DJ
$schedule = [];
if (file_exists($scheduleFile)) {
  $lines = file($scheduleFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  foreach ($lines as $line) {
    $parts = explode('|', trim($line));
    if (count($parts) === 3) {
      [$day, $hour, $dj] = $parts;
      $day = trim($day);
      $hour = trim($hour);
      $dj = trim($dj);
      $schedule[$day][$hour] = $dj;
    }
  }
}

function format12Hour(string $hour24): string {
  return date("g:i A", strtotime($hour24));
}

function getDayNameOffset(string $dayName, int $offsetDays): string {
  // Convert a day name ("Sunday") to a date, add offset, return day name
  $base = new DateTime("this $dayName", new DateTimeZone('America/New_York'));
  if ($offsetDays !== 0) {
    $base->modify(($offsetDays > 0 ? '+' : '') . $offsetDays . ' day');
  }
  return $base->format('l');
}

$currentDay = date('l');
$currentHour = date('H') . ':00';

// Helper to fetch DJ for a given day + hour with fallback
function djAt(array $schedule, string $day, string $hour): string {
  return $schedule[$day][$hour] ?? 'auto dj';
}

// CURRENT
$currentDJ = djAt($schedule, $currentDay, $currentHour);

// NEXT (correctly moves into next day if crossing midnight)
$currentHourNum = (int)substr($currentHour, 0, 2);
$nextHourNum = ($currentHourNum + 1) % 24;
$nextHour = str_pad((string)$nextHourNum, 2, '0', STR_PAD_LEFT) . ':00';

$nextDay = $currentDay;
if ($currentHourNum === 23) {
  // crossing midnight
  $nextDay = getDayNameOffset($currentDay, 1);
}
$nextDJ = djAt($schedule, $nextDay, $nextHour);

// AFTER (one more hour after NEXT, also handles day rollover)
$afterHourNum = ($currentHourNum + 2) % 24;
$afterHour = str_pad((string)$afterHourNum, 2, '0', STR_PAD_LEFT) . ':00';

$afterDay = $currentDay;
if ($currentHourNum >= 22) {
  // 22-> after is 00 next day, 23-> after is 01 next day
  $afterDay = getDayNameOffset($currentDay, 1);
}
$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);