<?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
    $sender_email = $conn->real_escape_string($_POST['sender_email']);
    $reciever_email = $conn->real_escape_string($_POST['reciever_email']);

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

    // Check if the request already exists
    $check_sql = "SELECT * FROM `requests` WHERE `sender_email` = '$sender_email' AND `reciever_email` = '$reciever_email'";
    $check_result = $conn->query($check_sql);

    if ($check_result->num_rows > 0) {
        // Request already exists
        echo json_encode(array('success' => 'Request already added.'));
    } else {
        // Attempt insert query execution
        $insert_sql = "INSERT INTO `requests` (`sender_email`, `reciever_email`) 
                       VALUES ('$sender_email', '$reciever_email')";

        if ($conn->query($insert_sql) === TRUE) {
            echo json_encode(array('success' => 'Request added successfully.'));
        } else {
            echo json_encode(array('error' => 'Error: ' . $conn->error));
        }
    }
}

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