<?php
include 'db_connection.php';

// Fetch group ID from the request
$group_id = isset($_GET['group_id']) ? intval($_GET['group_id']) : 0;

header('Content-Type: application/json');

// Fetch messages
$sql_messages = "SELECT gm.message_id, gm.sender_id, gm.message, gm.timestamp, s.name AS sender_name
                 FROM group_messages gm
                 JOIN students s ON gm.sender_id = s.student_id
                 WHERE gm.group_id = ?
                 ORDER BY gm.timestamp DESC";
$stmt_messages = $conn->prepare($sql_messages);
$stmt_messages->bind_param("i", $group_id);
$stmt_messages->execute();
$result_messages = $stmt_messages->get_result();

// Prepare messages and replies data
$messages_with_replies = [];
while ($message = $result_messages->fetch_assoc()) {
    $message_id = $message['message_id'];
    $sql_replies = "SELECT mr.reply_id, mr.sender_id, mr.reply, mr.timestamp, s.name AS sender_name
                    FROM message_replies mr
                    JOIN students s ON mr.sender_id = s.student_id
                    WHERE mr.message_id = ?
                    ORDER BY mr.timestamp";
    $stmt_replies = $conn->prepare($sql_replies);
    $stmt_replies->bind_param("i", $message_id);
    $stmt_replies->execute();
    $result_replies = $stmt_replies->get_result();
    $message['replies'] = $result_replies->fetch_all(MYSQLI_ASSOC);
    $messages_with_replies[] = $message;
}

$stmt_messages->close();
$conn->close();

// Return data as JSON
echo json_encode(['messages' => $messages_with_replies]);
?>
