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

// Initialize response array
$response = array(
    'friends' => array(),
    'message' => '',
    'error' => ''
);

// Check if form is submitted using POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Escape user input for security (assuming $conn is the database connection object)
    $user_email = $conn->real_escape_string($_POST['user_email']);

    // Select query to retrieve friend emails for the given user_email
    $sql = "SELECT friend_email FROM friend_table WHERE user_email = '$user_email'";
    $result = $conn->query($sql);

    if ($result) {
        if ($result->num_rows > 0) {
            // Fetching and storing results in response array
            while($row = $result->fetch_assoc()) {
                $response['friends'][] = $row["friend_email"];
            }
        } else {
            // No friends found for this user
            $response['message'] = "No friends found for this user.";
        }
    } else {
        // Error executing the SQL query
        $response['error'] = "Error retrieving friends: " . $conn->error;
    }
} else {
    // If not a POST request, handle accordingly (optional)
    $response['error'] = "Invalid request method.";
}

// Close the database connection
$conn->close();

// Convert PHP array to JSON format and output the response
echo json_encode($response);
?>
