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

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Escape user inputs for security (assuming connection is established)
    $user_email = $conn->real_escape_string($_POST['user_email']);

    // Query to fetch friends' profiles
    $friends_sql = "SELECT u1.name, u1.email, u1.image, u1.fcm
                    FROM friend_table AS f1
                    JOIN user AS u1 ON f1.friend_email = u1.email
                    WHERE f1.user_email = '$user_email'
                    
                    UNION
                    
                    SELECT u2.name, u2.email, u2.image, u2.fcm
                    FROM friend_table AS f2
                    JOIN user AS u2 ON f2.user_email = u2.email
                    WHERE f2.friend_email = '$user_email'";

    $friends_result = $conn->query($friends_sql);

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

    if ($friends_result->num_rows > 0) {
        // Iterate over each row and add to the response array
        while ($row = $friends_result->fetch_assoc()) {
            $friend = array(
                'name' => $row['name'],
                'email' => $row['email'],
                'image' => $row['image'],
                'fcm' => $row['fcm']
            );
            // Check if the user_email is the same as the current friend's email
            // If yes, mark as bidirectional friendship
            if ($row['email'] == $user_email) {
                $friend['bidirectional'] = true;
            }
            $response[] = $friend;
        }
    } else {
        // No friends found message
        $response['message'] = "No friends found for this user.";
    }

    // Output the JSON response
    header('Content-Type: application/json');
    echo json_encode($response);
}

$conn->close();
?>
