<script>
$(document).ajaxComplete(function(event, xhr, settings) {
// if (settings.type && settings.type.toUpperCase() !== "POST") {
//         return; // skip if not a POST request
//     }
    // if (xhr.responseText.indexOf("SESSION_EXPIRED") !== -1) {
    //     window.location.replace('<?php echo LOGOUT_URL; ?>'); // Faster than href
    // }
    const body = (xhr.responseText || '').trim();
if (body === 'SESSION_EXPIRED') {
    window.location.replace('<?php echo LOGOUT_URL; ?>');
}
});


$(document).ready(function () {
    let isRefreshing = false;

    // Use the global variable injected from PHP, fallback to 90 seconds
   const csrfHeartbeatInterval =  <?php echo CSRF_HEARTBEAT_INTERVAL ?> ;

    setInterval(function () {
        if (isRefreshing) return;
        isRefreshing = true;

        $.ajax({
            url: 'security/refresh_csrf.php',
            method: 'GET',
            timeout: 5000,
            success: function (data) {
                if (typeof data === "string" && data.trim() !== "") {
                    window.csrfToken = data;
                    // keep meta in sync so all code paths see the same token
                    const $meta = $('meta[name="csrf-token"]');
                    if ($meta.length) $meta.attr('content', window.csrfToken);
                }
            },
            error: function (xhr, status, error) {
                console.warn("CSRF token refresh failed:", error);
            },
            complete: function () {
                isRefreshing = false;
            }
        });
    }, csrfHeartbeatInterval);
});
</script> 