<?php
require_once __DIR__ . '/config/db.php';
header('Content-Type: application/javascript');
header('Cache-Control: no-cache, no-store, must-revalidate');
$b = BASE_PATH;
?>
const CACHE_NAME = 'asterixx-v7';
const BASE = '<?= $b ?>';

// Install: cache static shell only (icons + offline fallback)
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME).then(cache => cache.addAll([
      BASE + '/favicon.png',
      BASE + '/icons/icon-192x192.png',
      BASE + '/icons/icon-512x512.png',
      BASE + '/css/styles.css',
    ])).catch(() => {})
  );
  self.skipWaiting();
});

// Activate: wipe ALL old caches immediately
self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(keys =>
      Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k)))
    )
  );
  self.clients.claim();
});

// Fetch: stale-while-revalidate for CSS/JS/images, network-first for HTML/PHP/API
self.addEventListener('fetch', event => {
  const { request } = event;
  const url = new URL(request.url);

  // Only handle same-origin GET requests
  if (request.method !== 'GET' || url.origin !== location.origin) return;

  // -- NEVER cache: API calls, admin, cart, checkout, account --
  const noCache = ['/api/', '/admin/', '/account/', '/cart', '/checkout', 'pos'];
  if (noCache.some(p => url.pathname.includes(p))) return;

  // -- Network-first for ALL PHP pages --
  if (url.pathname.endsWith('.php') || url.pathname === BASE + '/' || url.pathname === BASE) {
    event.respondWith(
      fetch(request)
        .then(res => {
          if (res && res.status === 200) {
            const clone = res.clone();
            caches.open(CACHE_NAME).then(c => c.put(request, clone));
          }
          return res;
        })
        .catch(() => caches.match(request))
    );
    return;
  }

  // -- Stale-while-revalidate for CSS/JS/images --
  // Returns cached instantly, then updates cache in background
  event.respondWith(
    caches.open(CACHE_NAME).then(cache =>
      cache.match(request).then(cached => {
        const networkFetch = fetch(request).then(res => {
          if (res && res.status === 200) cache.put(request, res.clone());
          return res;
        }).catch(() => cached);
        return cached || networkFetch;
      })
    )
  );
});

