Ryanhub - file viewer
filename: views/api/chat_send.php
branch: main
back to repo
<?php
declare(strict_types=1);

require_once __DIR__ . '/../../auth.php';

// Send a chat message for a given dinner date (default: today).

if (!isLoggedIn()) {
    http_response_code(401);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['ok' => false, 'error' => 'Sign in required.']);
    return;
}

$currentUserId = currentUserId();
if ($currentUserId === null) {
    http_response_code(401);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['ok' => false, 'error' => 'Sign in required.']);
    return;
}

$dateStr = (string)($_POST['dinner_date'] ?? '');
if ($dateStr === '') {
    $dateStr = (new DateTimeImmutable('today'))->format('Y-m-d');
}
$dinnerDate = DateTimeImmutable::createFromFormat('Y-m-d', $dateStr);
if ($dinnerDate === false) {
    http_response_code(400);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['ok' => false, 'error' => 'Invalid dinner_date']);
    return;
}
$dinnerDateStr = $dinnerDate->format('Y-m-d');

$body = trim((string)($_POST['body'] ?? ''));
if ($body === '') {
    http_response_code(400);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['ok' => false, 'error' => 'Message cannot be empty']);
    return;
}
if (mb_strlen($body) > 2000) {
    http_response_code(400);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['ok' => false, 'error' => 'Message too long']);
    return;
}

$nowStr = (new DateTimeImmutable('now'))->format('Y-m-d H:i:s');
$stmt = $db->prepare('
    INSERT INTO chat_messages (user_id, dinner_date, body, created_at)
    VALUES (?, ?, ?, ?)
');
$stmt->bind_param('isss', $currentUserId, $dinnerDateStr, $body, $nowStr);
$stmt->execute();

// If called via a normal form POST (non-AJAX), redirect back to schedule.
$isAjax = ($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '') === 'XMLHttpRequest';
if (!$isAjax) {
    header('Location: ' . url('schedule#chat-messages'));
    exit;
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => true, 'dinner_date' => $dinnerDateStr]);