// Push Notifications JavaScript
let vapidPublicKey = null;
let isSubscribed = false;

// Check if service workers and push notifications are supported
if ('serviceWorker' in navigator && 'PushManager' in window) {
    initializePushNotifications();
}

async function initializePushNotifications() {
    try {
        // Register service worker
        const registration = await navigator.serviceWorker.register('/Capstone_Project/sw.js');
        console.log('Service Worker registered successfully');

        // Get VAPID public key from server
        const response = await fetch('/Capstone_Project/api/get_vapid_key.php');
        const data = await response.json();
        vapidPublicKey = data.publicKey;

        // Check if already subscribed
        const subscription = await registration.pushManager.getSubscription();
        isSubscribed = subscription !== null;

        if (!isSubscribed) {
            // Request permission and subscribe if not already subscribed
            await requestNotificationPermission(registration);
        } else {
            console.log('Already subscribed to push notifications');
        }

    } catch (error) {
        console.error('Error initializing push notifications:', error);
    }
}

async function requestNotificationPermission(registration) {
    try {
        const permission = await Notification.requestPermission();

        if (permission === 'granted') {
            console.log('Notification permission granted');
            await subscribeToPushNotifications(registration);
        } else if (permission === 'denied') {
            console.log('Notification permission denied');
        } else {
            console.log('Notification permission dismissed');
        }
    } catch (error) {
        console.error('Error requesting notification permission:', error);
    }
}

async function subscribeToPushNotifications(registration) {
    try {
        // Convert VAPID key to Uint8Array
        const convertedVapidKey = urlBase64ToUint8Array(vapidPublicKey);

        // Subscribe to push notifications
        const subscription = await registration.pushManager.subscribe({
            userVisibleOnly: true,
            applicationServerKey: convertedVapidKey
        });

        console.log('Push subscription successful:', subscription);

        // Send subscription to server
        await sendSubscriptionToServer(subscription);

        isSubscribed = true;
    } catch (error) {
        console.error('Error subscribing to push notifications:', error);
    }
}

async function sendSubscriptionToServer(subscription) {
    try {
        const response = await fetch('/Capstone_Project/api/subscribe_push.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(subscription)
        });

        const data = await response.json();
        console.log('Subscription sent to server:', data);
    } catch (error) {
        console.error('Error sending subscription to server:', error);
    }
}

async function unsubscribeFromPushNotifications() {
    try {
        const registration = await navigator.serviceWorker.getRegistration('/Capstone_Project/sw.js');
        const subscription = await registration.pushManager.getSubscription();

        if (subscription) {
            // Unsubscribe from browser
            await subscription.unsubscribe();

            // Remove from server
            await fetch('/Capstone_Project/api/unsubscribe_push.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(subscription)
            });

            isSubscribed = false;
            console.log('Unsubscribed from push notifications');
        }
    } catch (error) {
        console.error('Error unsubscribing from push notifications:', error);
    }
}

// Helper function to convert VAPID 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;
}

// Optional: Add UI to toggle notifications
function createNotificationToggle() {
    const toggleButton = document.createElement('button');
    toggleButton.id = 'notification-toggle';
    toggleButton.className = 'notification-toggle-btn';
    toggleButton.innerHTML = isSubscribed ? '🔔 Notifications On' : '🔕 Notifications Off';

    toggleButton.addEventListener('click', async () => {
        if (isSubscribed) {
            await unsubscribeFromPushNotifications();
            toggleButton.innerHTML = '🔕 Notifications Off';
        } else {
            const registration = await navigator.serviceWorker.getRegistration('/Capstone_Project/sw.js');
            await requestNotificationPermission(registration);
            toggleButton.innerHTML = '🔔 Notifications On';
        }
    });

    return toggleButton;
}
