<?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.');
}

// Fetch pending friend requests from the database
$student_id = $_SESSION['student_id'];
$query = "SELECT sr.request_id, p.profile_picture, p.name
          FROM student_requests sr
          JOIN profiles p ON sr.student_id = p.profile_id
          WHERE sr.requested_id = ? AND sr.status = 'Pending'";
$stmt = $conn->prepare($query);
if (!$stmt) {
    die('Prepare failed: ' . htmlspecialchars($conn->error));
}
$stmt->bind_param("i", $student_id);
$stmt->execute();
$result_sent_requests = $stmt->get_result();

if ($result_sent_requests === false) {
    die('Query failed: ' . htmlspecialchars($stmt->error));
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Friend Requests</title>
    <link rel="stylesheet" href="styles.css"> <!-- Link your CSS here -->
</head>
<body>

<!-- Display status messages -->
<?php if (isset($_GET['status'])): ?>
    <div class="status-message">
        <?php if ($_GET['status'] == 'success'): ?>
            <p class="success">Request rejected successfully.</p>
        <?php elseif ($_GET['status'] == 'error'): ?>
            <p class="error">An error occurred. Please try again.</p>
        <?php endif; ?>
    </div>
<?php endif; ?>

<!-- Display received friend requests -->
<?php if ($result_sent_requests && $result_sent_requests->num_rows > 0): ?>
    <?php while ($row = $result_sent_requests->fetch_assoc()): ?>
        <div class="request">
            <img src="<?php echo htmlspecialchars($row['profile_picture']); ?>" alt="Profile">
            <div class="info">
                <p class="name"><?php echo htmlspecialchars($row['name']); ?></p>
            </div>
            <button class="reject" onclick="rejectRequest(<?php echo intval($row['request_id']); ?>)">Reject</button>
        </div>
    <?php endwhile; ?>
<?php else: ?>
    <div class="placeholder">
        <img src="placeholder-icon.png" class="placeholder-icon" alt="No Requests">
        <p>No friend requests found.</p>
    </div>
<?php endif; ?>

<script>
function rejectRequest(requestId) {
    if (confirm("Are you sure you want to reject this request?")) {
        window.location.href = "reject_friend.php?request_id=" + requestId;
    }
}
</script>

</body>
</html>

<?php
$stmt->close();
$conn->close();
?>
