<?php
// Include database connection
include 'db_connection.php'; // Adjust the path to your actual database connection file

// Check if action and student_id are set
if (isset($_GET['action']) && isset($_GET['student_id'])) {
    $action = $_GET['action'];
    $student_id = intval($_GET['student_id']); // Sanitize student_id

    // Validate action
    if ($action !== 'add' && $action !== 'remove') {
        die('Invalid action');
    }

    // Get current user's ID (assuming it's stored in a session)
    session_start();
    $current_user_id = $_SESSION['student_id']; // Ensure the session contains the user_id

    // Perform database operations based on action
    if ($action === 'add') {
        // Check if there is already a pending request
        $query = "SELECT * FROM student_requests WHERE student_id = ? AND requested_id = ? AND status = 'Pending'";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("ii", $current_user_id, $student_id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            echo "Friend request already sent.";
        } else {
            // Send friend request
            $query = "INSERT INTO student_requests (student_id, requested_id, status) VALUES (?, ?, 'Pending')";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("ii", $current_user_id, $student_id);
            $stmt->execute();

            if ($stmt->affected_rows > 0) {
                echo "Friend request sent successfully.";
            } else {
                echo "Error sending friend request.";
            }
            $stmt->close();
        }
    } elseif ($action === 'remove') {
        // Remove friend request or friendship
        // First, check if there is a pending friend request
        $query = "DELETE FROM student_requests WHERE (student_id = ? AND requested_id = ?) OR (student_id = ? AND requested_id = ?)";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("iiii", $current_user_id, $student_id, $student_id, $current_user_id);
        $stmt->execute();

        // Also remove the friendship if it exists
        $query = "DELETE FROM friends WHERE (user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("iiii", $current_user_id, $student_id, $student_id, $current_user_id);
        $stmt->execute();

        if ($stmt->affected_rows > 0) {
            echo "Friend request or friendship removed successfully.";
        } else {
            echo "Error removing friend request or friendship.";
        }
        $stmt->close();
    }
} else {
    die('Missing action or student_id');
}

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