
<?php
header('Content-Type: application/json; charset=utf-8');
$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 (function_exists('mb_substr')) { if (mb_strlen($name) > 24) $name = mb_substr($name, 0, 24); if (mb_strlen($msg) > 240) $msg = mb_substr($msg, 0, 240); }
$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'=>time()];
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]);
