<?php
// schedule_lib.php - shared helpers for schedule based features (UK time)
$SMURF_DAYS_ORDER = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];

function smurf_load_schedule_hourmap(string $jsonFile, string $txtFile, array $daysOrder): array {
  // Expected JSON format: {"Monday": {"0":"Show — DJ", "13":"..."}, ...}
  if (file_exists($jsonFile) && filesize($jsonFile) > 5) {
    $j = json_decode((string)file_get_contents($jsonFile), true);
    if (is_array($j)) {
      // Normalize keys to ints where possible
      foreach ($daysOrder as $d) {
        if (!isset($j[$d]) || !is_array($j[$d])) $j[$d] = [];
      }
      return $j;
    }
  }

  // Fallback import from TXT formats:
  // Day|HH:MM|DJ
  // Day|HH:MM|Show Title|DJ
  $out = [];
  foreach ($daysOrder as $d) $out[$d] = [];
  if (file_exists($txtFile) && filesize($txtFile) > 0) {
    foreach (file($txtFile, FILE_IGNORE_NEW_LINES) as $line) {
      $line = trim((string)$line);
      if ($line === '' || (function_exists('str_starts_with') && str_starts_with($line, '#'))) continue;
      if ($line !== '' && substr($line,0,1)==='#') continue;

      $parts = array_map('trim', explode('|', $line));
      if (count($parts) < 3) continue;

      $day  = $parts[0];
      $time = $parts[1];
      if (!in_array($day, $daysOrder, 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 ($daysOrder as $d) {
      if (isset($out[$d]) && is_array($out[$d])) ksort($out[$d]);
    }
  }
  return $out;
}

function smurf_extract_dj(string $val): string {
  $val = trim((string)$val);
  if ($val === '') return '';
  $parts = explode('—', $val, 2);
  if (count($parts) === 2) return trim($parts[1]);
  return $val;
}

function smurf_schedule_now_next(array $schedule, string $tz='Europe/London'): array {
  $daysOrder = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
  $now = new DateTime('now', new DateTimeZone($tz));
  $day = $now->format('l');
  $hour = (int)$now->format('H');

  $todayMap = (isset($schedule[$day]) && is_array($schedule[$day])) ? $schedule[$day] : [];

  $current = smurf_extract_dj((string)($todayMap[$hour] ?? ''));
  $nextHour = ($hour + 1) % 24;
  $next = smurf_extract_dj((string)($todayMap[$nextHour] ?? ''));

  $afterHour = ($hour + 2) % 24;
  $after = smurf_extract_dj((string)($todayMap[$afterHour] ?? ''));

  return [
    'day' => $day,
    'hour' => $hour,
    'now' => $current,
    'next' => $next,
    'after' => $after,
    'timeLabelNow' => str_pad((string)$hour,2,'0',STR_PAD_LEFT).':00',
    'timeLabelNext' => str_pad((string)$nextHour,2,'0',STR_PAD_LEFT).':00',
  ];
}

function smurf_is_live_dj(string $djName, array $settings): bool {
  $dj = trim((string)$djName);
  if ($dj === '') return false;
  $auto = $settings['autodj_names'] ?? ['Auto DJ','Smurfies Groovies','Smurfies Groovies (Auto DJ)'];
  if (!is_array($auto)) $auto = ['Auto DJ','Smurfies Groovies','Smurfies Groovies (Auto DJ)'];
  foreach ($auto as $a) {
    if ($a !== '' && strcasecmp($dj, (string)$a) === 0) return false;
  }
  return true;
}
