<?php
/**
 * Get Messages AJAX Endpoint
 * Returns HTML for messages in a chat room
 */

require_once '../config/config.php';

requireLogin();
if (!isResearcher()) {
    http_response_code(403);
    exit('Unauthorized');
}

$roomId = isset($_GET['room']) ? (int)$_GET['room'] : 0;
$userId = getCurrentUserId();

if (!$roomId) {
    http_response_code(400);
    exit('Room ID required');
}

$db = getDB();

// Check if user is participant
$stmt = $db->prepare("SELECT COUNT(*) FROM chat_participants WHERE room_id = ? AND user_id = ?");
$stmt->execute([$roomId, $userId]);
if ($stmt->fetchColumn() == 0) {
    http_response_code(403);
    exit('Not a participant');
}

// Get messages
$stmt = $db->prepare("
    SELECT m.*, u.first_name, u.last_name
    FROM messages m
    JOIN users u ON m.sender_id = u.id
    WHERE m.room_id = ?
    ORDER BY m.created_at ASC
");
$stmt->execute([$roomId]);
$messages = $stmt->fetchAll();

// Output messages HTML
if (empty($messages)) {
    echo '<div class="text-center text-muted py-5">
        <i class="fas fa-comments fa-3x mb-3"></i>
        <p>No messages yet. Start the conversation!</p>
    </div>';
} else {
    foreach ($messages as $msg) {
        echo '<div class="mb-3 ' . ($msg['sender_id'] == $userId ? 'text-end' : '') . '">
            <div class="d-inline-block" style="max-width: 70%;">
                ' . ($msg['sender_id'] != $userId ? '<small class="text-muted d-block mb-1">' . e($msg['first_name'] . ' ' . $msg['last_name']) . '</small>' : '') . '
                <div class="p-3 rounded ' . ($msg['sender_id'] == $userId ? 'bg-primary text-white' : 'bg-light') . '">
                    ' . nl2br(e($msg['message'])) . '
                </div>
                <small class="text-muted d-block mt-1">' . date('g:i A', strtotime($msg['created_at'])) . '</small>
            </div>
        </div>';
    }
}
?>