<?php
/**
 * Progressive Web App — shared <head> tags for mobile screens.
 * Requires config (BASE_PATH, SITE_NAME) — call after init.php or equivalent.
 */
declare(strict_types=1);

if (!function_exists('nazareth_mobile_pwa_head')) {
    function nazareth_mobile_pwa_head(): void
    {
        if (!defined('BASE_PATH') || !defined('SITE_NAME')) {
            return;
        }
        $base = BASE_PATH;
        $swMtime = @filemtime(__DIR__ . '/sw.js') ?: time();
        $manifestUrl = $base . '/mobile/manifest.php?v=' . (int)$swMtime;
        $icon192M = (int) (@filemtime(__DIR__ . '/assets/img/192.png') ?: 0);
        $appIcon192 = $base . '/mobile/assets/img/192.png' . ($icon192M ? '?v=' . $icon192M : '');
        $shortTitle = SITE_NAME . ' Field';
        ?>
    <meta name="theme-color" content="#0b1b89">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="<?= htmlspecialchars($shortTitle, ENT_QUOTES, 'UTF-8') ?>">
    <link rel="manifest" href="<?= htmlspecialchars($manifestUrl, ENT_QUOTES, 'UTF-8') ?>">
    <link rel="apple-touch-icon" href="<?= htmlspecialchars($appIcon192, ENT_QUOTES, 'UTF-8') ?>">
        <?php
    }

    function nazareth_mobile_pwa_scripts(): void
    {
        if (!defined('BASE_PATH')) {
            return;
        }
        $base = htmlspecialchars(BASE_PATH, ENT_QUOTES, 'UTF-8');
        ?>
    <script>
    (function () {
        if (!('serviceWorker' in navigator)) return;
        var url = '<?= $base ?>/mobile/sw.js';
        var scope = '<?= $base ?>/mobile/';
        window.addEventListener('load', function () {
            navigator.serviceWorker.register(url, { scope: scope }).catch(function () {});
        });
    })();
    </script>
        <?php
    }
}
