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

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

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

    // Query to fetch sent requests and receiver details
    $sql = "SELECT r.sender_email, r.reciever_email, u.name, u.image
            FROM requests AS r
            JOIN user AS u ON r.reciever_email = u.email
            WHERE r.sender_email = '$sender_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'],
                'reciever_email' => $row['reciever_email'],
                'name' => $row['name'],
                'image' => $row['image']
            );
            $response[] = $request;
        }
    }
    // No sent requests found will also be represented as an empty array
    echo json_encode($response);
} else {
    // Handle missing 'sender_email' parameter
    echo json_encode(array('error' => 'Missing parameter: sender_email'));
}

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