<?php
// Include the database connection file
require_once 'connection.php';

// Check if 'receiver_email' parameter is present in the POST request
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['receiver_email'])) {
    // Escape user input for security
    $receiver_email = $conn->real_escape_string($_POST['receiver_email']);

    // Validate input (e.g., check if email is valid)
    if (filter_var($receiver_email, FILTER_VALIDATE_EMAIL) === false) {
        echo json_encode(array('error' => 'Invalid email format.'));
        exit();
    }

    // Query to fetch received requests and sender details
    $sql = "SELECT r.sender_email, u.name, u.image
            FROM requests AS r
            JOIN user AS u ON r.sender_email = u.email
            WHERE r.reciever_email = '$receiver_email'";

    $result = $conn->query($sql);

    // Prepare an array to hold the results
    $response = array();

    if ($result->num_rows > 0) {
        // Iterate over each row and add to the response array
        while ($row = $result->fetch_assoc()) {
            $request = array(
                'sender_email' => $row['sender_email'],
                'name' => $row['name'],
                'image' => $row['image']
            );
            $response[] = $request;
        }
    }
    // No received requests found will also be represented as an empty array
    echo json_encode($response);
} else {
    // Handle missing 'receiver_email' parameter
    echo json_encode(array('error' => 'Missing parameter: receiver_email'));
}

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