<?php
/* ============================================================================
 *  auto_update.php  —  drop-in auto-update watcher for any page.
 *  Include it once, just before </body>:
 *      <?php require __DIR__ . '/../config/auto_update.php'; ?>
 *  (adjust the relative path to reach /config/ from the page's folder).
 *
 *  The open page polls the version endpoint and reloads itself when a newer
 *  version of the app is deployed — no need to close & reopen. It won't reload
 *  while the user is typing in a field.
 * ==========================================================================*/

require_once __DIR__ . '/app_version.php';
$__appVer = app_version();
?>
<script>
(function(){
    var APP_VERSION = <?= json_encode($__appVer) ?>;
    function safeToReload(){
        var a = document.activeElement;
        if (a && (a.tagName === 'INPUT' || a.tagName === 'TEXTAREA' || a.isContentEditable)) return false;
        return true;
    }
    async function checkAppVersion(){
        try{
            var r = await fetch('/seven-credit-system/auth/app_version.php?_=' + Date.now(), {cache:'no-store'});
            if (!r.ok) return;
            var v = (await r.text()).trim();
            if (v && APP_VERSION && v !== APP_VERSION && safeToReload()) { location.reload(); }
        }catch(e){}
    }
    setInterval(checkAppVersion, 30000);
    document.addEventListener('visibilitychange', function(){ if (!document.hidden) checkAppVersion(); });
    window.addEventListener('pageshow', checkAppVersion);
    window.addEventListener('focus', checkAppVersion);
})();
</script>