<?php
require_once __DIR__ . '/../includes/bootstrap.php';
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['ok'=>false,'message'=>'Method not allowed']); exit; }
$name = trim($_POST['name'] ?? 'Guest');
$message = trim($_POST['message'] ?? '');
$gifUrl = trim($_POST['gif_url'] ?? '');
if ($message === '') { echo json_encode(['ok'=>false,'message'=>'Message required']); exit; }
if (ugfx_contains_banned_word($message)) { echo json_encode(['ok'=>false,'message'=>'Message blocked']); exit; }
if ($gifUrl !== '' && !filter_var($gifUrl, FILTER_VALIDATE_URL)) { echo json_encode(['ok'=>false,'message'=>'GIF URL invalid']); exit; }
$allowedGif = $gifUrl === '' || preg_match('/\.(gif|webp|png|jpe?g)(\?.*)?$/i', $gifUrl);
if (!$allowedGif) { echo json_encode(['ok'=>false,'message'=>'GIF/link image only']); exit; }
ugfx_chat_add([
  'name' => ugfx_substr($name, 0, 30),
  'message' => ugfx_substr($message, 0, 400),
  'gif_url' => $gifUrl,
  'type' => 'user',
  'created_at' => date('Y-m-d H:i:s')
]);
echo json_encode(['ok'=>true,'message'=>'Message posted']);
?>
