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

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

// Fetch chat messages (HTML/JSON): returns JSON for last 24 hours.
// We scope messages to the selected dinner_date (default: today).

header('Content-Type: application/json; charset=utf-8');

$dateStr = (string)($_GET['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);
    echo json_encode(['ok' => false, 'error' => 'Invalid dinner_date']);
    return;
}

$fromTs = (new DateTimeImmutable('now - 24 hours'))->format('Y-m-d H:i:s');
$dinnerDateStr = $dinnerDate->format('Y-m-d');

$stmt = $db->prepare('
    SELECT
        c.id,
        c.user_id,
        m.display_name,
        m.photo_url,
        c.body,
        c.created_at
    FROM chat_messages c
    JOIN member_profiles m ON m.user_id = c.user_id
    WHERE c.dinner_date = ?
      AND c.created_at >= ?
    ORDER BY c.created_at DESC, c.id DESC
');
$stmt->bind_param('ss', $dinnerDateStr, $fromTs);
$stmt->execute();

$messages = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

echo json_encode([
    'ok' => true,
    'dinner_date' => $dinnerDateStr,
    'messages' => array_map(function (array $m) {
        return [
            'id' => (int)($m['id'] ?? 0),
            'user_id' => (int)($m['user_id'] ?? 0),
            'display_name' => (string)($m['display_name'] ?? ''),
            'photo_url' => $m['photo_url'] ?? null,
            'body' => (string)($m['body'] ?? ''),
            'created_at' => (string)($m['created_at'] ?? ''),
        ];
    }, $messages),
]);