// push_sw.js
// Service Worker untuk Push Notification

self.addEventListener('install', function(event) {
    self.skipWaiting();
});

self.addEventListener('activate', function(event) {
    event.waitUntil(clients.claim());
});

self.addEventListener('push', function(event) {
    let data = event.data ? event.data.json() : {};
    
    const title = data.title || 'Sistem Absensi';
    const options = {
        body: data.body || 'Ada notifikasi baru',
        icon: data.icon || '/assets/icon-192.png',
        badge: data.badge || '/assets/badge-72x72.png',
        vibrate: [200, 100, 200],
        data: {
            url: data.url || '/scan_wa_api.php'
        },
        actions: [
            {
                action: 'open',
                title: 'Buka'
            },
            {
                action: 'close',
                title: 'Tutup'
            }
        ]
    };
    
    event.waitUntil(self.registration.showNotification(title, options));
});

self.addEventListener('notificationclick', function(event) {
    event.notification.close();
    
    if (event.action === 'open' || !event.action) {
        const url = event.notification.data.url || '/scan_wa_api.php';
        event.waitUntil(
            clients.matchAll({ type: 'window' }).then(function(clientList) {
                for (let i = 0; i < clientList.length; i++) {
                    const client = clientList[i];
                    if (client.url === url && 'focus' in client) {
                        return client.focus();
                    }
                }
                if (clients.openWindow) {
                    return clients.openWindow(url);
                }
            })
        );
    }
});