        </main>
    </div>
</div>

<div class="toast-container position-fixed bottom-0 end-0 p-3" style="z-index: 1100">
    </div>

<audio id="notificationSound" src="/assets/notification.mp3" preload="auto"></audio>

<div class="position-fixed bottom-0 start-0 p-3" style="z-index: 1100">
    <button class="btn btn-primary" id="push-subscription-btn" style="display: none;"><i class="bi bi-bell-fill"></i> Subscribe to Notifications</button>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    
    // --- START: Realtime Pop-up Notification Logic ---
    const toastContainer = document.querySelector('.toast-container');
    const notificationSound = document.getElementById('notificationSound');

    function createToast(notification) {
        const toastEl = document.createElement('div');
        toastEl.className = 'toast';
        toastEl.setAttribute('role', 'alert');
        toastEl.setAttribute('aria-live', 'assertive');
        toastEl.setAttribute('aria-atomic', 'true');
        // Set toast to not autohide and add a dismiss button
        toastEl.setAttribute('data-bs-autohide', 'false');

        let icon = 'bi-info-circle-fill';
        let bodyText = `New request from <strong>${escapeHtml(notification.detail)}</strong>.`;

        // Logic to handle different notification types
        if (notification.type.includes('Partner')) icon = 'bi-person-plus-fill';
        if (notification.type.includes('Top-Up')) icon = 'bi-arrow-up-circle-fill';
        if (notification.type.includes('Withdrawal')) icon = 'bi-cash-coin';
        if (notification.type.includes('Document')) icon = 'bi-file-earmark-check-fill';
        if (notification.type.includes('Message')) icon = 'bi-envelope-fill';
        if (notification.type.includes('New Listing')) {
            icon = 'bi-plus-circle-fill text-success';
            bodyText = `<strong>${escapeHtml(notification.detail)}</strong> added a new listing: ${escapeHtml(notification.item)}.`;
        }

        toastEl.innerHTML = `
            <div class="toast-header">
                <i class="bi ${icon} rounded me-2"></i>
                <strong class="me-auto">${notification.type}</strong>
                <small>Just now</small>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body">${bodyText}</div>
        `;
        
        toastContainer.appendChild(toastEl);
        const toast = new bootstrap.Toast(toastEl);
        toast.show();

        if (notificationSound) {
            notificationSound.currentTime = 0;
            notificationSound.play().catch(error => {
                console.warn("Notification sound was blocked by the browser. User must interact with the page first.");
            });
        }
    }

    function escapeHtml(unsafe) {
        return unsafe ? unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;") : '';
    }

    function checkAdminNotifications() {
        fetch(`check-admin-notifications.php`)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.notifications.length > 0) {
                    data.notifications.forEach(notification => createToast(notification));
                }
            })
            .catch(error => {
                console.error('Error checking for notifications:', error);
            });
    }

    // Check for new notifications every 10 seconds
    setInterval(checkAdminNotifications, 10000);
    // --- END: Realtime Pop-up Notification Logic ---



    // --- START: Push Notification Subscription Logic ---
    const VAPID_PUBLIC_KEY = '<?php echo $site_settings['vapid_public_key'] ?? ''; ?>';

    function urlBase64ToUint8Array(base64String) {
        const padding = '='.repeat((4 - base64String.length % 4) % 4);
        const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
        const rawData = window.atob(base64);
        const outputArray = new Uint8Array(rawData.length);
        for (let i = 0; i < rawData.length; ++i) {
            outputArray[i] = rawData.charCodeAt(i);
        }
        return outputArray;
    }

    async function subscribeUser() {
        try {
            const registration = await navigator.serviceWorker.register('/sw.js');
            await registration.pushManager.getSubscription();
            
            const subscription = await registration.pushManager.subscribe({
                userVisibleOnly: true,
                applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY)
            });

            const response = await fetch('save-subscription.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(subscription)
            });

            if(response.ok) {
                document.getElementById('push-subscription-btn').style.display = 'none';
                alert('You have successfully subscribed to push notifications!');
            } else {
                alert('Failed to save subscription on the server.');
            }

        } catch (err) {
            console.error('Failed to subscribe the user: ', err);
            alert('Failed to subscribe to push notifications. Please ensure you have granted permission.');
        }
    }

    function initializePushNotifications() {
        if (!('serviceWorker' in navigator) || !('PushManager' in window) || !VAPID_PUBLIC_KEY) { 
            return; 
        }

        const pushBtn = document.getElementById('push-subscription-btn');
        
        navigator.serviceWorker.ready.then(reg => {
            reg.pushManager.getSubscription().then(subscription => {
                if (subscription === null) { 
                    pushBtn.style.display = 'block'; 
                }
            });
        });
        
        pushBtn.addEventListener('click', () => subscribeUser());
    }

    initializePushNotifications();
    // --- END: Push Notification Subscription Logic ---
});
</script>

</body>
</html>
