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

$settingsFile = __DIR__ . '/../data/settings.json';
$settings = [];
require_once __DIR__ . '/../includes/schedule_lib.php';
if (file_exists($settingsFile)) {
  $settings = json_decode(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-based live gate
$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'] ?: 'Auto DJ';
$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';
if (!file_exists($file)) {
  echo json_encode(['ok'=>true,'ts'=>time(),'messages'=>[]]);
  exit;
}

$raw = file_get_contents($file);
$data = json_decode($raw, true);
if (!is_array($data)) $data = [];

echo json_encode([
  'ok' => true,
  'ts' => time(),
  'messages' => array_slice($data, -120)
]);
