<?php
require_once '../../../config/cors.php';
require_once '../../../config/db.php';
require_once '../../../helpers/response.php';

$stream_id = $_GET['stream_id'] ?? null;
$last_id = (int)($_GET['last_id'] ?? 0);

if (!$stream_id) {
    sendError('Stream ID required', 400);
}

/*
|----------------------------------------------------------
| Fetch chat messages (works for live + ended streams)
|----------------------------------------------------------
*/
$stmt = $pdo->prepare("
    SELECT 
        cm.id,
        cm.message,
        cm.created_at,
        cm.user_type,

        CASE 
            WHEN cm.user_type = 'public' 
                THEN COALESCE(pu.display_name, 'User')
            WHEN cm.user_type = 'admin' 
                THEN '🎙️ Host'
            ELSE 'User'
        END as user_name

    FROM chat_messages cm

    LEFT JOIN public_users pu 
        ON pu.id = cm.user_id 
        AND cm.user_type = 'public'

    WHERE cm.stream_id = ? 
      AND cm.id > ?
      AND cm.is_deleted = FALSE

    ORDER BY cm.id ASC
    LIMIT 100
");

$stmt->execute([$stream_id, $last_id]);
$messages = $stmt->fetchAll();

/*
|----------------------------------------------------------
| Safe latest ID calculation
|----------------------------------------------------------
*/
$latestId = $last_id;

if (!empty($messages)) {
    $lastMessage = end($messages);

    if ($lastMessage && isset($lastMessage['id'])) {
        $latestId = (int)$lastMessage['id'];
    }
}

/*
|----------------------------------------------------------
| Response
|----------------------------------------------------------
*/
sendSuccess([
    'messages' => $messages,
    'latest_id' => $latestId
]);