<?php
// pwa/components/pwa_inject.php
// Single-entry injector for PWA header/nav. Call pwa_inject() from any PWA page.

if (!function_exists('pwa_inject')) {

    function pwa_inject()
    {
        // Prevent double-injection in same request
        static $injected = false;
        if ($injected) return;
        $injected = true;

        // Detect base paths (adjust if your structure differs)
        $basePath = dirname(__DIR__); // pwa/
        $assetsPath = $basePath . '/assets';
        $manifestPath = $basePath . '/manifest.json';

        // Prefer server session auth to detect role/user (if available)
        if (session_status() === PHP_SESSION_NONE) {
            @session_start();
        }

        $user = [
            'id' => $_SESSION['user_id'] ?? null,
            'role' => $_SESSION['role'] ?? 'Guest',
            'team_id' => $_SESSION['team_id'] ?? null,
            'name' => $_SESSION['name'] ?? null
        ];

        // Output head partial (meta + manifest + icons)
        require_once __DIR__ . '/pwa_header.php';
        pwa_header($manifestPath);

        // Top header bar
        require_once __DIR__ . '/pwa_nav.php';
        pwa_nav($user);

        // Register service worker & load pwa_app.js once
        echo "\n<!-- PWA Assets & SW -->\n";
        ?>
        <script>
        // ensure pwa_app loaded once
        (function(){
            if (!window.__PWA_APP_LOADED) {
                var s = document.createElement('script');
                s.src = '/pwa/assets/pwa_app.js';
                s.defer = true;
                document.head.appendChild(s);
                window.__PWA_APP_LOADED = true;
            }
        })();
        // register SW
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/pwa/service-worker.js').catch(function(e){
                console.warn('SW register failed:', e);
            });
        }
        </script>
        <?php

        // At this point header & nav are injected. Page content follows.
    }

}
