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

// Set header to return JSON response
header('Content-Type: application/json');

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

    // Check if the friendship already exists
    $check_sql = "SELECT * FROM `friend_table` WHERE `user_email`='$user_email' AND `friend_email`='$friend_email'";
    $check_result = $conn->query($check_sql);

    if ($check_result === FALSE) {
        echo json_encode(array("status" => "error", "message" => "Database query error."));
        exit();
    }

    if ($check_result->num_rows > 0) {
        // Return response as JSON
        echo json_encode(array("status" => "exists", "message" => "Friend already exists for this user."));
    } else {
        // Insert new friend
        $insert_sql = "INSERT INTO `friend_table` (`user_email`, `friend_email`) VALUES ('$user_email', '$friend_email')";

        if ($conn->query($insert_sql) === TRUE) {
            echo json_encode(array("status" => "success", "message" => "Friend added successfully."));
        } else {
            echo json_encode(array("status" => "error", "message" => "Error adding friend: " . $conn->error));
        }
    }
} else {
    echo json_encode(array("status" => "error", "message" => "Invalid request method. Only POST is allowed."));
}

$conn->close();
?>
