<?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;
}
$name = trim((string)($_POST['name'] ?? ''));
$msg  = trim((string)($_POST['msg'] ?? ''));
if ($name === '' || $msg === '') {
  echo json_encode(['ok'=>false,'error'=>'Missing name or message']);
  exit;
}
if (mb_strlen($name) > 24) $name = mb_substr($name, 0, 24);
if (mb_strlen($msg) > 240) $msg = mb_substr($msg, 0, 240);
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
$rateFile = __DIR__ . '/../data/chat_rate.json';
$rate = file_exists($rateFile) ? json_decode((string)file_get_contents($rateFile), true) : [];
if (!is_array($rate)) $rate = [];
$now = time();
$last = (int)($rate[$ip] ?? 0);
if ($now - $last < 2) {
  echo json_encode(['ok'=>false,'error'=>'You are sending too fast']);
  exit;
}
$rate[$ip] = $now;
file_put_contents($rateFile, json_encode($rate, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES), LOCK_EX);
$file = __DIR__ . '/../data/chat.json';
$data = file_exists($file) ? json_decode((string)file_get_contents($file), true) : [];
if (!is_array($data)) $data = [];
$data[] = ['id'=>'chat_' . substr(md5(uniqid('', true)),0,12),'role'=>'user','name'=>$name,'msg'=>$msg,'time'=>date('H:i'),'ts'=>$now];
if (count($data) > 200) $data = array_slice($data, -200);
file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES), LOCK_EX);
echo json_encode(['ok'=>true]);
