function fetchNotifications() {
    fetch("fetch_notifications.php")
        .then(response => response.json())
        .then(data => {
            const notificationBadge = document.getElementById("notification-badge");
            const notificationList = document.getElementById("notification-list");

            // Update notification count
            if (data.unread_count > 0) {
                notificationBadge.style.display = "inline-block";
                notificationBadge.innerText = data.unread_count;
            } else {
                notificationBadge.style.display = "none";
            }

            // Populate the notification dropdown
            notificationList.innerHTML = "";
            if (data.notifications.length > 0) {
                data.notifications.forEach(notification => {
                    let li = document.createElement("li");
                    li.classList.add("notification-item");
                    li.innerText = notification.message;
                    notificationList.appendChild(li);
                });
            } else {
                let li = document.createElement("li");
                li.innerText = "No new notifications";
                notificationList.appendChild(li);
            }
        })
        .catch(error => console.error("Error fetching notifications:", error));
}

// Toggle dropdown and mark notifications as read
document.getElementById("notification-container").addEventListener("click", function () {
    let dropdown = document.getElementById("notification-dropdown");
    dropdown.classList.toggle("show");

    // Mark notifications as read when opened
    fetch("mark_notifications.php")
        .then(() => {
            document.getElementById("notification-badge").style.display = "none";
        })
        .catch(error => console.error("Error marking notifications as read:", error));
});

// Fetch notifications every 5 seconds
document.addEventListener("DOMContentLoaded", function () {
    fetchNotifications();
    setInterval(fetchNotifications, 5000);
});
