<?php
/**
 * Page Footer Template
 */
?>
<?php if (SessionManager::isLoggedIn()): ?>
        </main>
    </div>
</div>
<?php endif; ?>

<script>
function toggleSidebar() {
    document.body.classList.toggle('sidebar-collapsed');
}
document.querySelectorAll('.alert').forEach(function(el) {
    setTimeout(function() { el.style.opacity = '0'; setTimeout(function() { el.remove(); }, 300); }, 5000);
});
document.querySelectorAll('[data-confirm]').forEach(function(el) {
    el.addEventListener('click', function(e) {
        if (!confirm(el.getAttribute('data-confirm'))) e.preventDefault();
    });
});

// Load DataTables JS and init
const datatablesScript = document.createElement('script');
datatablesScript.src  = 'https://cdn.datatables.net/2.1.5/js/dataTables.js';
datatablesScript.defer = true;
datatablesScript.onload = function() {
    const responsiveScript = document.createElement('script');
    responsiveScript.src      = 'https://cdn.datatables.net/responsive/3.0.2/js/dataTables.responsive.js';
    responsiveScript.defer    = true;
    responsiveScript.onload   = function() {
        const appScript = document.createElement('script');
        appScript.src           = '<?= APP_URL ?>/assets/js/items_datatables.js';
        appScript.defer         = true;
        document.head.appendChild(appScript);
    };
    document.head.appendChild(responsiveScript);
};
document.head.appendChild(datatablesScript);

// ======================  PWA — SERVICE WORKER  ============================
(function registerSW() {
    if (!('serviceWorker' in navigator)) return;

    const SW_URL = '/invcount/assets/js/sw.js';

    navigator.serviceWorker
        .register(SW_URL, { scope: '/invcount/' })
        .then(registration => {
            console.info('[PWARegister] Service Worker registered.', {
                scriptURL: registration.scriptURL,
                scope:     registration.scope,
                state:     registration.active?.state ?? 'unknown',
            });

            registration.addEventListener('updatefound', () => {
                const installing = registration.installing;
                installing.addEventListener('statechange', () => {
                    if (
                        installing.state === 'installed'
                        && navigator.serviceWorker.controller
                    ) {
                        console.info('[SW] New version ready. Reload to activate.');
                        window.location.reload();
                    }
                });
            });

            navigator.serviceWorker.addEventListener('controllerchange', () => {
                console.info('[PWARegister] Controller changed — reloading.');
                window.location.reload();
            });
        })
        .catch(error =>
            console.error('[PWARegister] Service Worker registration failed:', error)
        );
})();

// ======================  PWA — INSTALL PROMPT  ============================
window.addEventListener('beforeinstallprompt', e => {
    e.preventDefault();
    window.__deferredInstallPrompt = e;
    const btn = document.createElement('button');
    btn.id         = 'install-pwa-btn';
    btn.textContent = 'Install Inventory Counter';
    btn.style.cssText = [
        'display:none',
        'margin:1rem auto',
        'padding:.75rem 1.5rem',
        'background:#16213e',
        'color:#fff',
        'border:none',
        'border-radius:8px',
        'cursor:pointer',
        'font-size:1rem',
    ].join(';');
    // Append near the topbar where it won't be hidden by layout
    document.querySelector('.topbar-actions')?.appendChild(btn) ?? document.body.appendChild(btn);

    btn.addEventListener('click', async () => {
        const promptEvent = window.__deferredInstallPrompt;
        if (!promptEvent) return;
        const { outcome } = await promptEvent.prompt();
        console.log('[PWA] Install prompt outcome =', outcome);
        window.__deferredInstallPrompt = null;
        btn.remove();
    });
    btn.style.display = 'block';
});

// Handle app-installed event (Android / desktop)
window.addEventListener('appinstalled', () => {
    console.info('[PWA] Inventory Counter was installed.');
    window.__deferredInstallPrompt = null;
    const btn = document.getElementById('install-pwa-btn');
    if (btn) btn.remove();
});
</script>
</body>
</html>
