<?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 = [];
require_once __DIR__ . '/../includes/schedule_lib.php';
}
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'] ?: 'DJ Eagle';
$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);

// basic spam controls
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
$rateFile = __DIR__ . '/../data/chat_rate.json';
$rate = [];
if (file_exists($rateFile)) {
  $rate = json_decode(file_get_contents($rateFile), true);
  if (!is_array($rate)) $rate = [];
}
$now = time();
$last = (int)($rate[$ip] ?? 0);
if ($now - $last < 2) { // 1 msg per 2 seconds per IP
  echo json_encode(['ok'=>false,'error'=>'You are sending too fast']);
  exit;
}
$rate[$ip] = $now;
file_put_contents($rateFile, json_encode($rate));

$file = __DIR__ . '/../data/chat.json';
$data = [];
if (file_exists($file)) {
  $data = json_decode(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
];

// keep last 200
if (count($data) > 200) $data = array_slice($data, -200);

file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
echo json_encode(['ok'=>true]);
