self.addEventListener('push', function (event) {
    let data = { title: 'New Update', body: 'You have a new notification from Mabanga Express.' };

    if (event.data) {
        try {
            data = event.data.json();
        } catch (e) {
            data.body = event.data.text();
        }
    }

    const options = {
        body: data.body,
        icon: 'assets/images/logo-icon.png', // Ensure this path is correct
        badge: 'assets/images/logo-icon.png',
        vibrate: [100, 50, 100],
        data: {
            url: data.url || '/index.php'
        },
        actions: [
            { action: 'open', title: 'View Details' },
            { action: 'close', title: 'Dismiss' }
        ]
    };

    event.waitUntil(
        self.notification.showNotification(data.title, options)
    );
});

self.addEventListener('notificationclick', function (event) {
    event.notification.close();

    if (event.action === 'close') return;

    event.waitUntil(
        clients.matchAll({ type: 'window' }).then(windowClients => {
            // If a tab is already open, focus it; otherwise, open a new one
            for (let client of windowClients) {
                if (client.url === event.notification.data.url && 'focus' in client) {
                    return client.focus();
                }
            }
            if (clients.openWindow) {
                return clients.openWindow(event.notification.data.url);
            }
        })
    );
});