<?php
require_once 'connection.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $groupId = $_POST['groupId'];

    // Prepare SQL statement to get messages and user details
    $sql = "
        SELECT 
            gm.messageId,
            gm.groupId,
            gm.senderEmail,
            gm.messageContent AS message,
            gm.messageType,
            u.name AS senderName,
            u.image AS senderImage
        FROM 
            groupmessagetable gm
        JOIN 
            user u ON gm.senderEmail = u.email
        WHERE 
            gm.groupId = ?
    ";

    // Use prepared statement to prevent SQL injection
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $groupId);

    // Execute the statement
    if ($stmt->execute()) {
        // Get the result
        $result = $stmt->get_result();
        $messages = [];

        // Fetch data as an associative array
        while ($row = $result->fetch_assoc()) {
            $messages[] = $row;
        }

        // Output the result as JSON
        echo json_encode(["success" => true, "messages" => $messages]);
    } else {
        echo json_encode(["success" => false, "message" => "Error: " . $stmt->error]);
    }

    // Close statement and connection
    $stmt->close();
    $conn->close();
}
?>
