<?php
// Serve service worker with correct MIME type - NO BOOTSTRAP
header('Content-Type: application/javascript; charset=utf-8');
header('Service-Worker-Allowed: /');
header('Cache-Control: public, max-age=3600');
header('Access-Control-Allow-Origin: *');
?>

/**
 * Service Worker
 * SSCI Office Platform - PWA Support
 */

const CACHE_NAME = 'ssci-office-v1';
const ASSETS_TO_CACHE = [
    '/',
    '/index.php',
    '/offline.html'
];

/**
 * Install event
 */
self.addEventListener('install', (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME).then((cache) => {
            return cache.addAll(ASSETS_TO_CACHE).catch(() => {
                // Ignore errors
            });
        })
    );
    self.skipWaiting();
});

/**
 * Activate event
 */
self.addEventListener('activate', (event) => {
    event.waitUntil(
        caches.keys().then((cacheNames) => {
            return Promise.all(
                cacheNames.map((cacheName) => {
                    if (cacheName !== CACHE_NAME) {
                        return caches.delete(cacheName);
                    }
                })
            );
        })
    );
    self.clients.claim();
});

/**
 * Fetch event
 */
self.addEventListener('fetch', (event) => {
    if (event.request.method !== 'GET') {
        return;
    }

    event.respondWith(
        caches.match(event.request)
            .then((response) => {
                if (response) {
                    return response;
                }
                return fetch(event.request)
                    .catch(() => {
                        return caches.match('/offline.html');
                    });
            })
    );
});

