<?php
// Ensure connection to database
require_once 'connection.php';

// Check if sender_email and receiver_email are provided via GET or POST
if (isset($_REQUEST['sender_email']) && isset($_REQUEST['receiver_email'])) {
    $sender_email = $conn->real_escape_string($_REQUEST['sender_email']);
    $receiver_email = $conn->real_escape_string($_REQUEST['receiver_email']);

    // Prepare SQL statement to select messages between specified sender and receiver
    $sql = "SELECT 
                c.sender_email, 
                c.receiver_email, 
                c.message, 
                c.type,  -- Include the type field
                s.image AS sender_image, 
                r.image AS receiver_image 
            FROM 
                chat c 
            INNER JOIN 
                user s ON c.sender_email = s.email 
            INNER JOIN 
                user r ON c.receiver_email = r.email 
            WHERE 
                (c.sender_email = '$sender_email' AND c.receiver_email = '$receiver_email') 
                OR 
                (c.sender_email = '$receiver_email' AND c.receiver_email = '$sender_email')
            ORDER BY 
                c.id"; // Assuming `id` is the primary key or another ordering column

    // Execute SQL query
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // Array to hold messages
        $messages = array();

        // Fetch data and store in array
        while($row = $result->fetch_assoc()) {
            $message = array(
                'sender_email' => $row['sender_email'],
                'sender_image' => $row['sender_image'],
                'receiver_email' => $row['receiver_email'],
                'receiver_image' => $row['receiver_image'],
                'message' => $row['message'],
                'type' => $row['type']  // Include type field in each message
            );
            $messages[] = $message;
        }

        // Encode array as JSON and output
        header('Content-Type: application/json');
        echo json_encode($messages);
    } else {
        echo json_encode(array('message' => 'No messages found between the specified users.'));
    }
} else {
    echo json_encode(array('message' => 'Sender_email and receiver_email parameters are required.'));
}

// Close connection
$conn->close();
?>
