<?php
session_start();
include('db_connection.php');
include('functions.php'); // Ensure this line is at the top
// Check if the student is logged in
if (!isset($_SESSION['student_id'])) {
    header("Location: login.php");
    exit();
}

$student_id = $_SESSION['student_id'];

// Fetch friends list
$sql_friends = "SELECT sf.friend_id, p.name, p.profile_picture 
                FROM student_friends sf 
                JOIN students s ON sf.friend_id = s.student_id 
                JOIN profiles p ON sf.friend_id = p.student_id 
                WHERE sf.student_id = ?";
$stmt_friends = $conn->prepare($sql_friends);
$stmt_friends->bind_param("i", $student_id);
$stmt_friends->execute();
$result_friends = $stmt_friends->get_result();

// Fetch pending friend requests
$sql_requests = "SELECT sr.request_id, sr.student_id, p.name, p.profile_picture 
                  FROM student_requests sr 
                  JOIN students s ON sr.student_id = s.student_id 
                  JOIN profiles p ON sr.student_id = p.student_id 
                  WHERE sr.requested_id = ? AND sr.status = 'Pending'";
$stmt_requests = $conn->prepare($sql_requests);
$stmt_requests->bind_param("i", $student_id);
$stmt_requests->execute();
$result_requests = $stmt_requests->get_result();
$pending_requests_count = getPendingFriendRequestsCount($student_id);
$unread_messages_count = getUnreadMessagesCount($student_id);

// Function to count pending friend requests
function countPendingRequests($student_id, $conn) {
    $query = "SELECT COUNT(*) AS pending_count FROM student_requests WHERE requested_id = ? AND status = 'Pending'";
    $stmt = $conn->prepare($query);
    if ($stmt === false) {
        die('Prepare failed: ' . htmlspecialchars($conn->error));
    }
    $stmt->bind_param("i", $student_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();
    return $row['pending_count'];
}

if ($stmt_requests === false) {
    die('Prepare failed: ' . htmlspecialchars($conn->error));
}
$stmt_requests->bind_param("i", $student_id);
$stmt_requests->execute();
$pending_requests_data = $stmt_requests->get_result();

$pending_requests_count = countPendingRequests($student_id, $conn);
$unread_messages_count = getUnreadMessagesCount($student_id);

// Fetch sent friend requests
$sql_sent_requests = "SELECT sr.request_id, sr.requested_id, p.name, p.profile_picture, sr.created_at
                      FROM student_requests sr
                      JOIN students s ON sr.requested_id = s.student_id
                      JOIN profiles p ON sr.requested_id = p.student_id
                      WHERE sr.student_id = ? AND sr.status = 'Pending'";
$stmt_sent_requests = $conn->prepare($sql_sent_requests);
$stmt_sent_requests->bind_param("i", $student_id);
$stmt_sent_requests->execute();
$result_sent_requests = $stmt_sent_requests->get_result();

// SQL to fetch suggested friends based on mutual friends and excluding blocked or already friends
$sql_suggested_friends = "
    SELECT p.profile_id, p.student_id, p.name, p.profile_picture, p.bio, COUNT(DISTINCT CASE WHEN sf2.student_id = '$student_id' THEN sf2.friend_id END) AS mutual_count
    FROM profiles p
    LEFT JOIN student_friends sf ON (sf.friend_id = p.student_id AND sf.student_id = '$student_id')
    LEFT JOIN student_friends sf2 ON (sf2.student_id = p.student_id OR sf2.friend_id = p.student_id)
    WHERE sf.status IS NULL AND p.student_id != '$student_id'
    AND p.student_id NOT IN (
        SELECT friend_id FROM student_friends WHERE student_id = '$student_id' AND status = 'Active'
        UNION
        SELECT student_id FROM student_friends WHERE friend_id = '$student_id' AND status = 'Active'
    )
    GROUP BY p.profile_id
    ORDER BY mutual_count DESC, RAND()
    LIMIT 5";

$result_suggested_friends = $conn->query($sql_suggested_friends);

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="sidebar.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <title>Friends Request</title>
    <style type="text/css">
        body {
    font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: row; /* Adjusted to row to fit sidebar and main content */
            background-color: #f0f2f5;
    overflow-y: hidden; 

}

header {
        background-color: #34495e;
        color: white;
        padding: 10px 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        z-index: 2;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    }

    .header-left, .header-center, .header-right {
        display: flex;
        align-items: center;
    }

    .header-left img {
        height: 40px;
        margin-right: 20px;
    }

    .search-box {
        padding: 5px;
        border-radius: 4px;
        border: none;
        width: 250px; /* Adjusted width */
    }

    .header-center .icon, .header-right .icon {
        margin: 0 10px;
        cursor: pointer;
        position: relative;
        margin-right: 35px; /* Space from the right edge */
    }


    .header-right .icon .dropdown {
        display: none;
        position: absolute;
        top: 100%;
        left: 50%;
        background-color: white;
        border: 1px solid #ddd;
        padding: 10px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        z-index: 1;
        width: max-content; /* Adjust to fit content */
        transform: translateX(-70%);
    }



    .header-right .icon:hover .dropdown {
        display: block;
    }

    .dropdown-item {
        padding: 15px 10px;
        cursor: pointer;
        display: flex;
        align-items: center;
        text-decoration: none;
        color: #000;
    }

    .dropdown-item i {
        margin-right: 8px;
    }

    .dropdown-item:hover {
        background-color: #f0f0f0;
    }

    .header-center a.dropdown-item {
        margin: 0 10px;
        cursor: pointer;
        text-decoration: none;
        color: white;
        display: flex;
        align-items: center;
    }

    .header-center a.dropdown-item:hover {
        color: #000;
    }

.sidebar {
    width: 300px;
    background-color: #fff;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    overflow: hidden;
    height: calc(100% - 50px);
    padding-top: 80px;
    position: fixed;
    left: 0;
    height: 100vh; /* Full height to align with header */
    top: 0; /* Ensure it's aligned with the top of the viewport */
    overflow-y: auto; /* Allow scrolling if needed */
}
 .sidebar h2 {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 0;
    padding: 16px;
    font-size: 20px;
    background-color: #fff;
    border-bottom: 1px solid #e0e0e0;
    color: #000;
}

.sidebar h2 i {
    font-size: 18px;
    color: #000;
    cursor: pointer;
    background-color: #ddd;
}

.sidebar ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.sidebar ul li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
   font-size: 18px;
    color: #000;
    cursor: pointer;
}

.sidebar a {
    color: #000;
   }

.sidebar ul li i:first-child {
    margin-right: 10px;
    font-size: 18px;
}

.sidebar ul li i:last-child {
    color: gray;
}

.sidebar ul li.active,
.sidebar ul li:hover {
    background-color: #e4e6eb;
}

.sidebar ul li span {
    flex-grow: 1;
}

.sidebar ul li i.fa-chevron-right {
    visibility: visible;

}

.sidebar ul li:not(.active):hover i.fa-chevron-right {
    visibility: visible;
}
.container {
    margin-left: 300px; /* Align with the sidebar */
    width: calc(100% - 300px); /* Adjust width to fit sidebar */
    padding: 20px 20px;
    padding-top: 70px; /* Space for header */
    background-color: #ddd;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    overflow-y: auto; /* Enable vertical scrolling */
    height: calc(100vh - 90px); /* Adjust height to fit below the header */
}

.main {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.main h2 {
    margin: 0;
    font-size: 24px;
}

.main .see-all {
    font-size: 14px;
    color: #1877f2;
    text-decoration: none;
}

.friend-requests {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}

.card {
    width: calc(25% - 20px);
    background-color: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    align-items: center;
}
 


.card img {
    width: 100%;
    height: 180px;
    object-fit: cover;
}

.card .info {
    padding: 10px;
    text-align: center;
}

.card .info h3 {
    margin: 10px 0;
    font-size: 18px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.card .info p {
    margin: 0;
    font-size: 14px;
    color: gray;
}

.card .info p i {
    margin-right: 5px;
}

.card .btn {
    width: 100%;
    padding: 10px;
    margin: 5px 0;
    font-size: 16px;
    border: none;
    cursor: pointer;
}

.card .btn.confirm {
    background-color: #1877f2;
    color: #fff;
    border-radius: 5px;
}

.card .btn.delete {
    background-color: #f0f2f5;
    color: #000;
    border-radius: 5px;
}
.subheader {
    font-size: 14px;
    color: #000;
    margin: 0 0 10px;
}

.view-sent-requests {
    font-size: 14px;
    color: #1877f2;
    text-decoration: none;
    display: block;
    margin-bottom: 20px;
}

.friend-requests {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .request-card, .suggested-card {
            background-color: white;
            padding: 16px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .request-card img, .suggested-card img {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            margin-right: 16px;
        }

        .request-card .details, .suggested-card .details {
            flex-grow: 1;
        }

        .request-card .details h4, .suggested-card .details h4 {
            margin: 0;
            font-size: 18px;
        }

        .request-card .details p, .suggested-card .details p {
            margin: 4px 0 0;
            color: gray;
            font-size: 14px;
        }

        .request-card .actions, .suggested-card .actions {
            display: flex;
            gap: 8px;
        }

        .request-card button, .suggested-card button {
            padding: 8px 12px;
            font-size: 14px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .request-card button.accept {
            background-color: #1877f2;
            color: white;
        }

        .request-card button.reject, .suggested-card button.add-friend {
            background-color: #f0f0f0;
        }
         .suggested-card {
            background-color: white;
            padding: 16px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 10px;
        }

        .suggested-card img {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            margin-right: 16px;
        }

        .suggested-card .details {
            flex-grow: 1;
        }

        .suggested-card .details h4 {
            margin: 0;
            font-size: 18px;
        }

        .suggested-card .details p {
            margin: 0;
            font-size: 14px;
            color: #555;
        }

        .suggested-card .actions {
            display: flex;
            gap: 8px;
        }

        .suggested-card button.add-friend {
            padding: 8px 12px;
            font-size: 14px;
            border: none;
            border-radius: 4px;
            background-color: #1877f2;
            color: white;
            cursor: pointer;
        }
                .user-avatar .profile-picture {
    width: 40px; /* Adjust the width as needed */
    height: 40px; /* Adjust the height as needed */
    border-radius: 50%; /* Makes the image circular */
    object-fit: cover; /* Ensures the image covers the container without distortion */
    cursor: pointer; /* Adds a pointer cursor for better UX */
    border: 2px solid #fff; /* Optional: Adds a white border for better visibility */
}

.user-avatar {
    position: relative;
    display: inline-block;
}

.user-avatar .dropdown {
    display: none;
    position: absolute;
    top: 50px; /* Adjust to position the dropdown correctly */
    right: 0;
    background-color: #fff;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    z-index: 1;
}

.user-avatar:hover .dropdown {
    display: block;
}


    </style>
</head>
<body>
    <header>
        <div class="header-left">
           <a href="index.php">
                <img src="/csms/admin/uploads/11.png" alt="Logo">
            </a>
            <div class="search-box">
                <input type="text" placeholder="Search">
            </div>
        </div>
        <div class="header-center">
            <a href="#" class="dropdown-item"><i class="fas fa-home"></i></a>
            <a href="creat_group.php" class="dropdown-item"><i class="fas fa-users"></i></a>
            <a href="#" class="dropdown-item"><i class="fa-brands fa-facebook-messenger"></i></a>
        </div>
        <div class="header-right">
            <div class="icon menu">
                <i class="fas fa-bars"></i>
                <div class="dropdown">
                    <a href="#" class="dropdown-item"><i class="fas fa-plus"></i> Create</a>
                    <a href="#" class="dropdown-item"><i class="fas fa-pen"></i> Post</a>
                    <a href="#" class="dropdown-item"><i class="fas fa-book"></i> Story</a>
                    <a href="#" class="dropdown-item"><i class="fas fa-birthday-cake"></i> Life Event</a>
                    <a href="#" class="dropdown-item"><i class="fas fa-video"></i> Reel</a>
                    <a href="#" class="dropdown-item"><i class="fas fa-flag"></i> Page</a>
                    <a href="#" class="dropdown-item"><i class="fas fa-users"></i> Group</a>
                    <a href="#" class="dropdown-item"><i class="fas fa-calendar-alt"></i> Event</a>
                </div>
            </div>
            <div class="icon"><i class="fas fa-bell"></i></div>
            <div class="icon user-avatar">
                <img src="<?= $profilePicturePath ?>" alt="Profile Picture" class="profile-picture">
 
                <div class="dropdown">
                    <a href="#" class="dropdown-item"><i class="fas fa-cog"></i> Settings</a>
                    <a href="#" class="dropdown-item"><i class="fas fa-user-shield"></i> Privacy</a>
                    <a href="#" class="dropdown-item"><i class="fas fa-adjust"></i> Display</a>
                    <a href="#" class="dropdown-item"><i class="fas fa-universal-access"></i> Accessibility</a>
                    <a href="logout.php" class="dropdown-item"><i class="fas fa-sign-out-alt"></i> Log Out</a>
                </div>
            </div>
        </div>
    </header>
    <div class="sidebar">
        <h2>Friends <i class="fas fa-cog"></i></h2>
        <ul>
            <li>
                <a href="friends.php">
                <i class="fas fa-users"></i>
                <span>Home</span>
            </a>
            </li>
            <li class="active">
                <a href="friend_request.php">
                <i class="fas fa-user-friends"></i>
                <span>Friend requests</span>
                <i class="fas fa-chevron-right"></i>
                </a>
            </li>
             <li>
                <a href="all_friends.php">
                <i class="fas fa-address-book"></i>
                <span>All friends</span>
                <i class="fas fa-chevron-right"></i>
                 </a>
            </li>
            <li>
                <i class="fas fa-gift"></i>
                <span>Birthdays</span>
                <i class="fas fa-chevron-right"></i>
            </li>
            <li>
                <i class="fas fa-list"></i>
                <span>Custom lists</span>
                <i class="fas fa-chevron-right"></i>
            </li>
        </ul>
    </div>

    <div class="container">
<div class="main">
            <h2>Friend requests<i class="fas fa-users"></i></h2> <p class="subheader"><?php echo htmlspecialchars($pending_requests_count); ?> friend requests</p> <div class="view-sent-requests"><a href="sent_requests.php">View Sent Requests</a></div>
            <a href="#" class="see-all">See all</a>
        </div>
        <div class="friend-requests">
            <!-- Friend Request Card Start -->
 <?php if ($result_requests->num_rows > 0): ?>
                <?php while ($row_request = $result_requests->fetch_assoc()): ?>
                    <div class="card">
                        <img src="uploads/<?php echo $row_request['profile_picture']; ?>" alt="Requestor Picture">
                        <div class="info">
                            <h3><?php echo $row_request['name']; ?></h3>
                            <form method="post" action="accept_friend.php">
                                <input type="hidden" name="request_id" value="<?php echo $row_request['request_id']; ?>">
                                <button type="submit" class="btn" style="background-color: green;">Accept</button>
                            </form>
                            <form method="post" action="reject_friend.php">
                                <input type="hidden" name="request_id" value="<?php echo $row_request['request_id']; ?>">
                                <button type="submit" class="btn" style="background-color: red;">Decline</button>
                            </form>
                        </div>
                    </div>
                <?php endwhile; ?>
            <?php else: ?>
                <p>No pending friend requests</p>
            <?php endif; ?>
        </div>
<div class="main" style="margin-top: 40px;">
        <h2>People You May Know</h2>
    </div>
   <div class="friend-requests">
    <?php if ($result_suggested_friends->num_rows > 0): ?>
        <?php while ($row = $result_suggested_friends->fetch_assoc()): ?>
            <?php
            $profilePicture = htmlspecialchars($row['profile_picture']); // Ensure proper escaping
            $name = htmlspecialchars($row['name']); // Ensure proper escaping
            ?>
            <div class="suggested-card">
                <!-- Ensure the correct path to the profile picture -->
                <img src="uploads/<?php echo $profilePicture; ?>" alt="<?php echo $name; ?>" class="profile-picture">
                
                <div class="details">
                    <h4><?php echo $name; ?></h4>
                    <p><?php echo htmlspecialchars($row['bio']); // Properly escape user data ?></p>
                    <p>Mutual Friends: <?php echo intval($row['mutual_count']); // Sanitize integer data ?></p>
                </div>
                <div class="actions">
                    <button class="add-friend" onclick="handleFriendAction('add', <?php echo intval($row['student_id']); ?>)">Add Friend</button>
                    <button class="remove-friend" onclick="handleFriendAction('remove', <?php echo intval($row['student_id']); ?>)">Remove Friend</button>
                </div>
            </div>
        <?php endwhile; ?>
    <?php else: ?>
        <p>No suggested friends found.</p>
    <?php endif; ?>
</div>
    </div>
 <script>
        function handleFriendAction(action, studentId) {
            if (action === 'add') {
                if (confirm("Are you sure you want to send a friend request?")) {
                    window.location.href = `friend_action.php?action=add&student_id=${studentId}`;
                }
            } else if (action === 'remove') {
                if (confirm("Are you sure you want to remove this friend?")) {
                    window.location.href = `friend_action.php?action=remove&student_id=${studentId}`;
                }
            }
        }

        function cancelRequest(requestId) {
            if (confirm("Are you sure you want to cancel this request?")) {
                window.location.href = `cancel_request.php?request_id=${requestId}`;
            }
        }
    </script> 
</body>
</html>
