<?php
// Filename: reset.php
require 'config.php';
// Optional: requireLogin(); if you only want logged-in users to run this
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>System Reset</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>
        body { 
            height: 100vh; display: flex; align-items: center; justify-content: center; 
            background: #f8f9fd; font-family: sans-serif; text-align: center;
        }
        .loader { width: 3rem; height: 3rem; border-width: 0.25em; }
    </style>
</head>
<body>

    <div>
        <div class="spinner-border text-primary loader" role="status"></div>
        <h4 class="mt-3 fw-bold text-dark">Updating System...</h4>
        <p class="text-muted">Clearing old caches and service workers.</p>
        <div id="status" class="small text-secondary fst-italic">Initializing...</div>
    </div>

    <script>
        async function performReset() {
            const status = document.getElementById('status');
            
            // 1. Unregister Service Workers
            if ('serviceWorker' in navigator) {
                status.innerText = "Removing Service Worker...";
                const registrations = await navigator.serviceWorker.getRegistrations();
                for (let registration of registrations) {
                    await registration.unregister();
                    console.log('ServiceWorker unregistered.');
                }
            }

            // 2. Clear Cache Storage (The hard drive of the PWA)
            if ('caches' in window) {
                status.innerText = "Clearing Cache Storage...";
                const keys = await caches.keys();
                for (let key of keys) {
                    await caches.delete(key);
                    console.log('Cache deleted:', key);
                }
            }

            // 3. Clear LocalStorage/SessionStorage (Optional, keeps login if you don't do this)
            // localStorage.clear();
            // sessionStorage.clear();

            status.innerText = "Done! Redirecting...";
            
            // 4. Force Reload to Dashboard (Bypassing cache)
            setTimeout(() => {
                window.location.href = 'dashboard.php?v=' + new Date().getTime();
            }, 1000);
        }

        // Run immediately
        performReset();
    </script>
</body>
</html>