<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../includes/schedule_lib.php';

$settingsFile = __DIR__ . '/../data/settings.json';
$settings = [];
if (file_exists($settingsFile)) {
  $settings = json_decode((string)file_get_contents($settingsFile), true);
  if (!is_array($settings)) $settings = [];
}
if (empty($settings['chat_enabled'])) {
  echo json_encode(['ok'=>false,'error'=>'Chat offline']);
  exit;
}
$schedule = smurf_load_schedule_hourmap(__DIR__ . '/../data/schedule.json', __DIR__ . '/../data/schedule.txt', $SMURF_DAYS_ORDER);
$nn = smurf_schedule_now_next($schedule);
$currentDJ = $nn['now'] ?: 'DJ BLAZE';
$isLive = smurf_is_live_dj($currentDJ, $settings);
$requireLive = array_key_exists('chat_require_live', $settings) ? !empty($settings['chat_require_live']) : true;
if ($requireLive && !$isLive) {
  echo json_encode(['ok'=>false,'error'=>'Chat is available only when a Live DJ is on-air']);
  exit;
}
$file = __DIR__ . '/../data/chat.json';
$data = [];
if (file_exists($file)) {
  $data = json_decode((string)file_get_contents($file), true);
  if (!is_array($data)) $data = [];
}
echo json_encode(['ok'=>true,'ts'=>time(),'messages'=>array_slice($data, -120)]);
