<?php
// Include database connection
include 'db_connection.php';

// Start session to access session variables
session_start();

// Check if user is logged in
if (!isset($_SESSION['student_id'])) {
    die('Access denied. Please log in.');
}

// Check if request_id is set and is numeric
if (isset($_GET['request_id']) && is_numeric($_GET['request_id'])) {
    $request_id = intval($_GET['request_id']);
    
    // Get the current student's ID from session
    $student_id = $_SESSION['student_id'];

    // Prepare and execute the SQL query to update the request status to 'Rejected'
    $query = "UPDATE student_requests SET status = 'Rejected' WHERE request_id = ? AND requested_id = ? AND status = 'Pending'";
    $stmt = $conn->prepare($query);
    
    if (!$stmt) {
        die('Prepare failed: ' . htmlspecialchars($conn->error));
    }
    
    $stmt->bind_param("ii", $request_id, $student_id);

    if ($stmt->execute()) {
        if ($stmt->affected_rows > 0) {
            header("Location: friend_requests.php?status=success");
        } else {
            header("Location: friend_requests.php?status=error");
        }
    } else {
        die('Execute failed: ' . htmlspecialchars($stmt->error));
    }
    
    $stmt->close();
} else {
    header("Location: friend_requests.php?status=error");
}

$conn->close();
?>
