$(document).ajaxComplete(function(event, xhr, settings) {
    if (xhr.responseText.indexOf("SESSION_EXPIRED") !== -1) {
        window.location.replace('logout.php?timeout=1'); // Faster than href
    }
});

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

    // Use the global variable injected from PHP, fallback to 90 seconds
    const csrfHeartbeatInterval = typeof CSRF_HEARTBEAT_INTERVAL !== 'undefined' ? CSRF_HEARTBEAT_INTERVAL : 150000;

    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;
                    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);
});
 