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

$settingsFile = __DIR__ . '/../data/settings.json';
$settings = [];
if (file_exists($settingsFile)) {
  $settings = json_decode(file_get_contents($settingsFile), true);
  if (!is_array($settings)) $settings = [];
}
if (empty($settings['chat_enabled']) || empty($settings['chat_live_now'])) {
  echo json_encode(['ok'=>false,'error'=>'Chat offline']);
  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)
]);
