<?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;
}

$status = ugfx_chat_public_status();
if (!$status['enabled']) {
    echo json_encode(['ok' => false, 'message' => $status['message'], 'disabled' => true], JSON_UNESCAPED_SLASHES);
    exit;
}

$name = trim((string)($_POST['name'] ?? 'Guest'));
$message = trim((string)($_POST['message'] ?? ''));
$gifUrl = trim((string)($_POST['gif_url'] ?? ''));
$sticker = trim((string)($_POST['sticker'] ?? ''));
$voiceUrl = trim((string)($_POST['voice_url'] ?? ''));
$voiceMime = trim((string)($_POST['voice_mime'] ?? 'audio/webm'));
$textColor = trim((string)($_POST['text_color'] ?? '#f3f7ff'));

if ($name === '') $name = 'Guest';
if ($message === '' && $gifUrl === '' && $sticker === '' && $voiceUrl === '') {
    echo json_encode(['ok' => false, 'message' => 'Add a message, GIF, sticker, or voice clip.']);
    exit;
}

$nameState = ugfx_chat_name_state($name);
if ($nameState === 'banned') {
    echo json_encode(['ok' => false, 'message' => 'That username is banned from chat.']);
    exit;
}
if ($nameState === 'muted') {
    echo json_encode(['ok' => false, 'message' => 'That username is muted right now.']);
    exit;
}

$combined = trim($name . ' ' . $message . ' ' . $gifUrl . ' ' . $sticker);
if ($combined !== '' && ugfx_contains_banned_word($combined)) {
    echo json_encode(['ok' => false, 'message' => 'Message blocked.']);
    exit;
}

$isAllowedMediaPath = static function(string $value): bool {
    return (bool) preg_match('#^(?:/?assets/chat-media/|/?storage/chat/|https?://)#i', $value);
};

if ($gifUrl !== '' && !$isAllowedMediaPath($gifUrl)) {
    echo json_encode(['ok' => false, 'message' => 'GIF URL invalid.']);
    exit;
}

if ($sticker !== '' && !$isAllowedMediaPath($sticker) && !preg_match('/^[\p{L}\p{N} _\-!?.#]+$/u', $sticker)) {
    echo json_encode(['ok' => false, 'message' => 'Sticker invalid.']);
    exit;
}
if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $textColor)) {
    $textColor = '#f3f7ff';
}

if ($voiceUrl !== '' && !preg_match('#^(storage/chat/|https?://)#i', $voiceUrl)) {
    echo json_encode(['ok' => false, 'message' => 'Voice clip URL invalid.']);
    exit;
}

$entry = ugfx_chat_add([
    'name' => ugfx_substr($name, 0, 30),
    'message' => ugfx_substr($message, 0, 600),
    'gif_url' => ugfx_substr($gifUrl, 0, 500),
    'sticker' => ugfx_substr($sticker, 0, 500),
    'voice_url' => ugfx_substr($voiceUrl, 0, 500),
    'voice_mime' => ugfx_substr($voiceMime, 0, 80),
    'text_color' => $textColor,
    'type' => 'user',
    'created_at' => date('Y-m-d H:i:s'),
]);

echo json_encode(['ok' => true, 'message' => 'Message posted.', 'entry' => $entry], JSON_UNESCAPED_SLASHES);
