

// session termination api
/******************************************************************
******** works but logs out on second hard refresh ***************
******************************************************************
window.addEventListener('unload', function(e) {
    // Check if the user is refreshing the page
    if (performance.navigation.type === 1) {
        return; 
    }

    // Send a beacon to terminate session
    if (navigator.sendBeacon) {
		console.log('Terminating session...');
        navigator.sendBeacon('/api/terminate_session.php');
    } else {
        // Fallback for older browsers
        fetch('/api/terminate_session.php', {
            method: 'POST',
            keepalive: true
        });
    }
});

/******************************************************************
***  second attempt  ***
******************************************************************

window.addEventListener('beforeunload', function(e) {
    // Check if the browser supports sending beacon data
    if (navigator.sendBeacon) {
        // Send a beacon request to terminate the session
        navigator.sendBeacon('/api/terminate_session.php');
    } else {
        // Fallback for older browsers
        // Create a synchronous XMLHttpRequest to terminate the session
        var xhr = new XMLHttpRequest();
        xhr.open('GET', '/api/terminate_session.php', false);
        xhr.send();
    }
});

/*****************************************************************
***  third attempt  ***
******************************************************************

let isTabClosing = false;

window.addEventListener('beforeunload', function(e) {
    // Check if the user is closing the tab
    if (!e.clientY) {
        isTabClosing = true;
    }
});

window.addEventListener('unload', function(e) {
    if (isTabClosing) {
        // Send a beacon to terminate session
        if (navigator.sendBeacon) {
            navigator.sendBeacon('/api/terminate_session.php');
        } else {
            // Fallback for older browsers
            fetch('/api/terminate_session.php', {
                method: 'POST',
                keepalive: true
            });
        }
    }
    // Reset the isTabClosing flag
    isTabClosing = false;
});
/*****************************************************************/

/*****************************************************************
***  fourth attempt  ***
******************************************************************
******** first method that logs out on second hard refresh *******
******** I added the cookie method instead      		   *******
******** so admin can toggle this via menu         		   *******
******************************************************************
window.addEventListener('unload', function(e) {
    // Get cookie value directly at time of unload
    const sessionCookie = document.cookie.split(';')
        .find(c => c.trim().startsWith('session='));
    const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';
    
    console.log('Session value at unload:', sessionValue);

    // Don't terminate if explicitly off or if refreshing
    if (sessionValue === 'off' || performance.navigation.type === 1) {
        console.log('Skipping termination - session off or refresh');
        return;
    }

    // Otherwise always try to terminate
    console.log('Attempting to terminate session');
    if (navigator.sendBeacon) {
        const sent = navigator.sendBeacon('/api/terminate_session.php');
        console.log('Beacon sent:', sent);
    } else {
        fetch('/api/terminate_session.php', {
            method: 'POST',
            keepalive: true
        });
    }
});

/*****************************************************************
***  fifth attempt  ***
******************************************************************
// session termination api
let isRefreshing = false;

window.addEventListener('beforeunload', function(e) {
    isRefreshing = true;
    setTimeout(() => { isRefreshing = false; }, 100);
});

window.addEventListener('unload', function(e) {
    // Get cookie value directly at time of unload
    const sessionCookie = document.cookie.split(';')
        .find(c => c.trim().startsWith('session='));
    const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';
    
    console.log('Session value at unload:', sessionValue);

    // Don't terminate if explicitly off or if refreshing
    if (sessionValue === 'off' || isRefreshing || performance.navigation.type === 1) {
        console.log('Skipping termination - session off or refresh');
        return;
    }

    // Otherwise attempt to terminate
    console.log('Attempting to terminate session');
    if (navigator.sendBeacon) {
        const sent = navigator.sendBeacon('/api/terminate_session.php');
        console.log('Beacon sent:', sent);
    } else {
        fetch('/api/terminate_session.php', {
            method: 'POST',
            keepalive: true
        });
    }
});
/*****************************************************************/

/*****************************************************************
***  sixth attempt  ***
*** sessionstorage isn't tracking properly across tabs ***
******************************************************************
// Track page refreshes in sessionStorage
if (sessionStorage.getItem('pageLoadedBefore') === null) {
    sessionStorage.setItem('pageLoadedBefore', 'true');
    sessionStorage.setItem('isRefresh', 'false');
} else {
    sessionStorage.setItem('isRefresh', 'true');
}

console.log('Saved Session State:', savedSession);
console.log('Is refresh:', sessionStorage.getItem('isRefresh'));

window.addEventListener('unload', function(e) {
    const isSessionTerminationEnabled = savedSession !== 'off';
    const isRefresh = sessionStorage.getItem('isRefresh') === 'true';
    
    console.log('Session state:', savedSession);
    console.log('Is refresh:', isRefresh);
    console.log('Will terminate:', isSessionTerminationEnabled && !isRefresh);

    if (isSessionTerminationEnabled && !isRefresh) {
        if (navigator.sendBeacon) {
            console.log('Terminating session...');
            navigator.sendBeacon('/api/terminate_session.php');
        } else {
            fetch('/api/terminate_session.php', {
                method: 'POST',
                keepalive: true
            });
        }
    }
});

/*****************************************************************
***  seventh attempt  ***
***  trying localstorage  ***
******************************************************************
// Track page refreshes/loads
if (!localStorage.getItem('pageLoadedBefore')) {
    localStorage.setItem('pageLoadedBefore', 'true');
    localStorage.setItem('isRefresh', 'false');
} else {
    localStorage.setItem('isRefresh', 'true');
}

// Clear refresh state when opening in new tab
window.addEventListener('load', function() {
    if (!document.referrer) {
        localStorage.setItem('isRefresh', 'false');
    }
});

console.log('Saved Session State:', savedSession);
console.log('Is refresh:', localStorage.getItem('isRefresh'));

window.addEventListener('unload', function(e) {
    const isSessionTerminationEnabled = savedSession !== 'off';
    const isRefresh = localStorage.getItem('isRefresh') === 'true';
    const isNewTab = !document.referrer;
    
    console.log('Session state:', savedSession);
    console.log('Is refresh:', isRefresh);
    console.log('Is new tab:', isNewTab);
    console.log('Will terminate:', isSessionTerminationEnabled && !isRefresh);

    if (isSessionTerminationEnabled && !isRefresh) {
        if (navigator.sendBeacon) {
            console.log('Terminating session...');
            navigator.sendBeacon('/api/terminate_session.php');
        } else {
            fetch('/api/terminate_session.php', {
                method: 'POST',
                keepalive: true
            });
        }
    }
});
/******************************************************************/
/*****************************************************************
***  eighth attempt  ***
***  attempt to force logout on new tab  ***
******************************************************************
// Track if this is a new tab/window
window.addEventListener('load', function() {
    if (!document.referrer) {
        localStorage.setItem('isNewSession', 'true');
    } else {
        localStorage.setItem('isNewSession', 'false');
    }
});

console.log('Saved Session State:', savedSession);
console.log('Is new session:', localStorage.getItem('isNewSession'));

window.addEventListener('unload', function(e) {
    const isSessionTerminationEnabled = savedSession !== 'off';
    const isRefresh = performance.navigation.type === 1;
    const isNewSession = localStorage.getItem('isNewSession') === 'true';
    
    console.log('Session state:', savedSession);
    console.log('Is refresh:', isRefresh);
    console.log('Is new session:', isNewSession);

    // Terminate if it's not a refresh AND either it's not a new session or it's the first load
    if (isSessionTerminationEnabled && !isRefresh) {
        if (navigator.sendBeacon) {
            console.log('Terminating session...');
            navigator.sendBeacon('/api/terminate_session.php');
        } else {
            fetch('/api/terminate_session.php', {
                method: 'POST',
                keepalive: true
            });
        }
    }
});
/******************************************************************/
/*****************************************************************
***  ninth attempt  ***
***  new php session handling  ***
******************************************************************
// session termination api - just the basic call
window.addEventListener('unload', function(e) {
    const isSessionTerminationEnabled = savedSession !== 'off';
    
    // Only proceed if session termination is enabled
    if (isSessionTerminationEnabled) {
        // Check if the user is refreshing the page
        if (performance.navigation.type === 1) {
            return; 
        }
        // Send a beacon to terminate session
        if (navigator.sendBeacon) {
            navigator.sendBeacon('/api/terminate_session_php.php');
        } else {
            fetch('/api/terminate_session_php.php', {
                method: 'POST',
                keepalive: true
            });
        }
    }
});

/******************************************************************/
/*****************************************************************
***  tenth attempt  ***
***  new php session handling  ***
*** update: caused bug that view cases would cause logout ***
******************************************************************
// session termination api
window.addEventListener('unload', function(e) {
    const isSessionTerminationEnabled = savedSession !== 'off';
    console.log('Unload event fired');
    console.log('Saved session value:', savedSession);
    console.log('Session termination enabled:', isSessionTerminationEnabled);
    
    // Only proceed if session termination is enabled
    if (isSessionTerminationEnabled) {
        // Check if the user is refreshing the page
        if (performance.navigation.type === 1) {
            console.log('Skipping - page refresh detected');
            return; 
        }
        // Send a beacon to terminate session
        if (navigator.sendBeacon) {
            console.log('Sending beacon to terminate session');
            const sent = navigator.sendBeacon('/api/terminate_session.php');
            console.log('Beacon sent:', sent);
        } else {
            console.log('Using fetch fallback');
            fetch('/api/terminate_session.php', {
                method: 'POST',
                keepalive: true
            });
        }
    }
});


/******************************************************************/
/*****************************************************************
***  eleventh attempt  ***
***  trying to fix the view cases settings page to not logout  ***
******************************************************************
// session termination api

// Modify any click handlers for settings/cases navigation to set this flag
document.addEventListener('DOMContentLoaded', function() {
    // Add click handlers for internal navigation
    const internalLinks = document.querySelectorAll('.view-settings, .view-cases, .change-settings, .settings-switch div');
    internalLinks.forEach(link => {
        link.addEventListener('click', () => {
            isInternalNavigation = true;
            setTimeout(() => { isInternalNavigation = false; }, 100);
        });
    });
});

// Modify the unload event handler
window.addEventListener('unload', function(e) {
    // Get cookie value directly at time of unload
    const sessionCookie = document.cookie.split(';')
        .find(c => c.trim().startsWith('session='));
    const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';
    
    console.log('Session value at unload:', sessionValue);
    console.log('Is internal navigation:', isInternalNavigation);

    // Don't terminate if:
    // 1. Session is explicitly off OR
    // 2. It's a refresh OR
    // 3. It's internal navigation
    if (sessionValue === 'off' || 
        performance.navigation.type === 1 || 
        isInternalNavigation) {
        console.log('Skipping termination - session off or refresh or internal navigation');
        return;
    }

    // Otherwise attempt to terminate
    console.log('Attempting to terminate session');
    if (navigator.sendBeacon) {
        const sent = navigator.sendBeacon('/api/terminate_session.php');
        console.log('Beacon sent:', sent);
    } else {
        fetch('/api/terminate_session.php', {
            method: 'POST',
            keepalive: true
        });
    }
});
/***************************************************************/


/******************************************************************/
/*****************************************************************
***  twelfth attempt  ***
***  trying to fix the view cases settings page to not logout  ***
******************************************************************
// session termination api

// Helper function to check if current page is settings
function isSettingsPage() {
    return window.location.pathname.includes('/settings') || 
           window.location.href.includes('/settings.php');
}

// Helper to set navigation state with storage backup
function setNavigationState(state) {
    isInternalNavigation = state;
    if (state) {
        sessionStorage.setItem('isNavigatingToSettings', 'true');
    } else {
        sessionStorage.removeItem('isNavigatingToSettings');
    }
}

// Helper to check navigation state including storage
function checkNavigationState() {
    return isInternalNavigation || sessionStorage.getItem('isNavigatingToSettings') === 'true';
}

document.addEventListener('DOMContentLoaded', function() {
    // Clear any stale navigation state on fresh page load
    if (!isSettingsPage()) {
        sessionStorage.removeItem('isNavigatingToSettings');
    }
    
    // Track clicks on internal navigation links
    const internalLinks = document.querySelectorAll('.view-settings, .view-cases, .change-settings, .settings-switch div');
    internalLinks.forEach(link => {
        link.addEventListener('click', () => {
            setNavigationState(true);
            // Keep the flag true longer for internal navigation
            setTimeout(() => {
                if (!isSettingsPage()) {
                    setNavigationState(false);
                }
            }, 1000);
        });
    });

    // Track all navigation to settings
    document.addEventListener('click', (e) => {
        const closestLink = e.target.closest('a');
        if (closestLink && closestLink.href && 
            (closestLink.href.includes('/settings') || closestLink.href.includes('/settings.php'))) {
            setNavigationState(true);
            // Don't clear the state - let the next page load handle it
        }
    });

    // If we're on the settings page, ensure navigation state is maintained
    if (isSettingsPage()) {
        setNavigationState(true);
    }
});

// Handle page visibility changes
document.addEventListener('visibilitychange', function() {
    if (document.visibilityState === 'visible' && isSettingsPage()) {
        setNavigationState(true);
    }
});

// Session termination handler
window.addEventListener('unload', function(e) {
    // Get session cookie value
    const sessionCookie = document.cookie.split(';')
        .find(c => c.trim().startsWith('session='));
    const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';
    
    const isOnSettings = isSettingsPage();
    const isNavigating = checkNavigationState();
    
    console.log('Unload event - Debug info:', {
        sessionValue,
        isOnSettings,
        isNavigating,
        isInternalNavigation,
        storedNavigation: sessionStorage.getItem('isNavigatingToSettings'),
        currentPath: window.location.pathname,
        currentUrl: window.location.href
    });

    // Don't terminate if:
    // 1. Session is explicitly off OR
    // 2. It's a page refresh OR
    // 3. We're on settings page OR
    // 4. We're navigating to/within settings
    if (sessionValue === 'off' || 
        performance.navigation.type === 1 || 
        isOnSettings || 
        isNavigating) {
        console.log('Skipping termination - conditions not met');
        return;
    }

    // Only proceed with termination if we're really sure we should
    console.log('Proceeding with session termination');
    if (navigator.sendBeacon) {
        const sent = navigator.sendBeacon('/api/terminate_session.php');
        console.log('Beacon sent:', sent);
    } else {
        fetch('/api/terminate_session.php', {
            method: 'POST',
            keepalive: true
        });
    }
});
/******************************************************************/

/******************************************************************/
/*****************************************************************
***  thirteenth attempt  ***
***  trying to prevent session termination if we're either on the settings page or if we're going to the settings page  ***
******************************************************************
// session termination api

// Session termination handler
window.addEventListener('unload', function(e) {
    // First, check if this is a navigation to settings
    const navEntry = performance.getEntriesByType('navigation')[0];
    const nextURL = navEntry && navEntry.name ? new URL(navEntry.name).pathname : '';
    const isGoingToSettings = nextURL.includes('/settings');

    // Second, check if we're currently on settings
    const isOnSettings = window.location.pathname.includes('/settings') || 
                        window.location.href.includes('/settings.php');

    // Get session cookie value
    const sessionCookie = document.cookie.split(';')
        .find(c => c.trim().startsWith('session='));
    const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';
    
    console.log('Debug info:', {
        currentPath: window.location.pathname,
        isOnSettings,
        isGoingToSettings,
        sessionValue,
        nextURL
    });

    // Don't terminate if:
    // 1. Session is explicitly off OR
    // 2. It's a page refresh OR
    // 3. We're on settings OR going to settings
    if (sessionValue === 'off' || 
        performance.navigation.type === 1 || 
        isOnSettings || 
        isGoingToSettings) {
        console.log('Skipping termination');
        return;
    }

    // Otherwise attempt to terminate
    console.log('Attempting to terminate session');
    if (navigator.sendBeacon) {
        navigator.sendBeacon('/api/terminate_session.php');
    } else {
        fetch('/api/terminate_session.php', {
            method: 'POST',
            keepalive: true
        });
    }
});
/******************************************************************/


// TEMPORARY DEBUG
document.addEventListener('DOMContentLoaded', function() {
    // Add debug overlay
    const debugDiv = document.createElement('div');
    debugDiv.style.position = 'fixed';
    debugDiv.style.bottom = '0';
    debugDiv.style.left = '0';
    debugDiv.style.backgroundColor = 'rgba(0,0,0,0.8)';
    debugDiv.style.color = 'white';
    debugDiv.style.padding = '10px';
    debugDiv.style.zIndex = '9999';
    document.body.appendChild(debugDiv);

    // Update debug info
    function updateDebug() {
        const info = {
            currentPath: window.location.pathname,
            isSettings: window.location.pathname.includes('/settings'),
            sessionCookie: document.cookie.split(';').find(c => c.trim().startsWith('session=')),
            performance: performance.navigation.type,
            referrer: document.referrer
        };
        debugDiv.textContent = JSON.stringify(info, null, 2);
    }

    updateDebug();
    setInterval(updateDebug, 1000);
});



/******************************************************************/
/*****************************************************************
***  fourteenth attempt  ***
***  after debug showed that the path is /settings let's make it simpler  ***
******************************************************************
// session termination api

// Session termination handler
window.addEventListener('unload', function(e) {
    // Simple check for settings page
    const isSettingsPage = window.location.pathname === '/settings';
    
    // Get session cookie value
    const sessionCookie = document.cookie.split(';')
        .find(c => c.trim().startsWith('session='));
    const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';
    
    console.log('Unload event debug:', {
        path: window.location.pathname,
        isSettingsPage,
        sessionValue,
        referrer: document.referrer
    });

    // NEVER terminate if we're on settings page
    if (isSettingsPage) {
        console.log('On settings page - skipping termination');
        return;
    }

    // Don't terminate if:
    // 1. Session is explicitly off OR
    // 2. It's a page refresh OR
    // 3. We're navigating TO settings
    if (sessionValue === 'off' || 
        performance.navigation.type === 1 || 
        document.activeElement?.href?.includes('/settings')) {
        console.log('Skipping termination - session off or refresh or going to settings');
        return;
    }

    // Otherwise attempt to terminate
    console.log('Attempting to terminate session');
    if (navigator.sendBeacon) {
        navigator.sendBeacon('/api/terminate_session.php');
    } else {
        fetch('/api/terminate_session.php', {
            method: 'POST',
            keepalive: true
        });
    }
});

// Additional measure: Block termination for any settings-related clicks
document.addEventListener('click', function(e) {
    const closestLink = e.target.closest('a, .view-settings, .view-cases, .change-settings');
    if (closestLink) {
        // Prevent termination for the next 2 seconds after clicking any settings-related link
        window.preventTermination = true;
        setTimeout(() => {
            window.preventTermination = false;
        }, 2000);
    }
});
/******************************************************************/


/******************************************************************/
/*****************************************************************
***  fifteenth attempt  ***
***  try path blocklist  ***
******************************************************************
// session termination api

// Session termination handler
window.addEventListener('unload', function(e) {
    // Paths where we never want to terminate the session
    const noTerminatePaths = [
        '/settings',
        '/settings/',
        '/settings.php'
    ];
    
    // Get current path and clean it
    const currentPath = window.location.pathname.replace(/\/+$/, '');
    
    // Get session cookie value
    const sessionCookie = document.cookie.split(';')
        .find(c => c.trim().startsWith('session='));
    const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';
    
    console.log('Debug info:', {
        currentPath,
        sessionValue,
        isNoTerminatePath: noTerminatePaths.includes(currentPath)
    });

    // Block termination if:
    // 1. Current path is in our blocklist OR
    // 2. Session is explicitly off OR
    // 3. It's a page refresh
    if (noTerminatePaths.includes(currentPath) || 
        sessionValue === 'off' || 
        performance.navigation.type === 1) {
        console.log('Skipping termination');
        return;
    }

    // Otherwise terminate
    console.log('Attempting to terminate session');
    if (navigator.sendBeacon) {
        navigator.sendBeacon('/api/terminate_session.php');
    } else {
        fetch('/api/terminate_session.php', {
            method: 'POST',
            keepalive: true
        });
    }
});
/******************************************************************/


/******************************************************************/
/*****************************************************************
***  sixteenth attempt  ***
***  try localstorage to prevent from firing before unload event ***
******************************************************************
// session termination api


// Global flag to track settings navigation
document.addEventListener('DOMContentLoaded', function() {
    // Clear any previous navigation flags on fresh page load
    sessionStorage.removeItem('navigatingToSettings');
    
    // Add listeners for all settings-related navigation
    const settingsLinks = document.querySelectorAll('a[href*="settings"], .view-settings, .view-cases, .change-settings');
    settingsLinks.forEach(link => {
        link.addEventListener('click', () => {
            console.log('Settings link clicked - setting navigation flag');
            sessionStorage.setItem('navigatingToSettings', 'true');
        });
    });
});

// Session termination handler
window.addEventListener('unload', function(e) {
    // First check if we're navigating to settings
    const goingToSettings = sessionStorage.getItem('navigatingToSettings') === 'true';
    
    // Also check if we're currently on settings
    const onSettings = window.location.pathname.includes('/settings');
    
    // Get session cookie value
    const sessionCookie = document.cookie.split(';')
        .find(c => c.trim().startsWith('session='));
    const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';
    
    console.log('Unload event debug:', {
        goingToSettings,
        onSettings,
        sessionValue,
        path: window.location.pathname,
        storage: sessionStorage.getItem('navigatingToSettings')
    });

    // Don't terminate if:
    // 1. We're navigating to settings OR
    // 2. We're on settings OR
    // 3. Session is explicitly off OR
    // 4. It's a page refresh
    if (goingToSettings || 
        onSettings || 
        sessionValue === 'off' || 
        performance.navigation.type === 1) {
        console.log('Skipping session termination');
        return;
    }

    console.log('Proceeding with session termination');
    if (navigator.sendBeacon) {
        navigator.sendBeacon('/api/terminate_session.php');
    } else {
        fetch('/api/terminate_session.php', {
            method: 'POST',
            keepalive: true
        });
    }
});

/******************************************************************/


/******************************************************************/
/*****************************************************************
***  seventeeth attempt: debug  ***
***  try debug to find out why it's still killing session (note that I already tried to see if it was this code, by commenting out all attempts, and it did load cases normally, so it's definitely this) ***
******************************************************************
// session termination api

// Debug helper
function logDebug(message, data = {}) {
    console.log(`%c${message}`, 'background: #333; color: lime; padding: 2px;', {
        timestamp: new Date().toISOString(),
        url: window.location.href,
        path: window.location.pathname,
        ...data
    });
}

// Global flag to track settings navigation
document.addEventListener('DOMContentLoaded', function() {
    logDebug('DOMContentLoaded fired', {
        existingFlag: sessionStorage.getItem('navigatingToSettings'),
        isSettingsPage: window.location.pathname.includes('/settings')
    });

    // Clear any previous navigation flags on fresh page load
    sessionStorage.removeItem('navigatingToSettings');
    
    // Debug all existing settings links
    const settingsLinks = document.querySelectorAll('a[href*="settings"], .view-settings, .view-cases, .change-settings');
    logDebug('Found settings links', {
        count: settingsLinks.length,
        elements: Array.from(settingsLinks).map(el => ({
            className: el.className,
            href: el.href,
            text: el.textContent
        }))
    });

    // Add listeners for all settings-related navigation
    settingsLinks.forEach(link => {
        link.addEventListener('click', (e) => {
            logDebug('Settings link clicked', {
                element: {
                    className: e.target.className,
                    href: e.target.href,
                    text: e.target.textContent
                },
                currentTarget: {
                    className: e.currentTarget.className,
                    href: e.currentTarget.href,
                    text: e.currentTarget.textContent
                }
            });
            sessionStorage.setItem('navigatingToSettings', 'true');
            
            // Verify flag was set
            logDebug('Navigation flag set', {
                flagValue: sessionStorage.getItem('navigatingToSettings')
            });
        });
    });

    // Add global click handler to catch dynamically added elements
    document.addEventListener('click', (e) => {
        const settingsLink = e.target.closest('a[href*="settings"], .view-settings, .view-cases, .change-settings');
        if (settingsLink) {
            logDebug('Settings link clicked (global handler)', {
                element: settingsLink.outerHTML,
                className: settingsLink.className,
                href: settingsLink.href
            });
            sessionStorage.setItem('navigatingToSettings', 'true');
        }
    });
});

// Monitor sessionStorage changes
const originalSetItem = sessionStorage.setItem;
sessionStorage.setItem = function(key, value) {
    logDebug('sessionStorage.setItem called', {
        key,
        value,
        stack: new Error().stack
    });
    originalSetItem.apply(this, arguments);
};

// Session termination handler
window.addEventListener('unload', function(e) {
    logDebug('Unload event starting', {
        type: e.type,
        timeStamp: e.timeStamp,
        performance: performance.navigation.type
    });

    // First check if we're navigating to settings
    const goingToSettings = sessionStorage.getItem('navigatingToSettings') === 'true';
    
    // Also check if we're currently on settings
    const onSettings = window.location.pathname.includes('/settings');
    
    // Get session cookie value
    const sessionCookie = document.cookie.split(';')
        .find(c => c.trim().startsWith('session='));
    const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';
    
    const debugInfo = {
        goingToSettings,
        onSettings,
        sessionValue,
        path: window.location.pathname,
        storage: sessionStorage.getItem('navigatingToSettings'),
        cookies: document.cookie,
        referrer: document.referrer,
        performance: {
            type: performance.navigation.type,
            entries: performance.getEntriesByType('navigation')
        }
    };
    
    logDebug('Unload event debug info', debugInfo);

    // Don't terminate if:
    if (goingToSettings) {
        logDebug('Skipping termination - going to settings');
        return;
    }
    if (onSettings) {
        logDebug('Skipping termination - on settings page');
        return;
    }
    if (sessionValue === 'off') {
        logDebug('Skipping termination - session off');
        return;
    }
    if (performance.navigation.type === 1) {
        logDebug('Skipping termination - page refresh');
        return;
    }

    logDebug('Proceeding with session termination');
    if (navigator.sendBeacon) {
        const sent = navigator.sendBeacon('/api/terminate_session.php');
        logDebug('Beacon sent', { success: sent });
    } else {
        fetch('/api/terminate_session.php', {
            method: 'POST',
            keepalive: true
        }).then(() => logDebug('Fetch completed'))
          .catch(err => logDebug('Fetch failed', { error: err }));
    }
});

// Additional debugging for navigation
window.addEventListener('beforeunload', (e) => {
    logDebug('beforeunload event', {
        storage: sessionStorage.getItem('navigatingToSettings'),
        activeElement: document.activeElement.outerHTML
    });
});

window.addEventListener('popstate', (e) => {
    logDebug('popstate event', {
        state: e.state,
        storage: sessionStorage.getItem('navigatingToSettings')
    });
});
/******************************************************************/


/******************************************************************/
/*****************************************************************
***  debug results  ***
***  - settings links aren't being found on the main page (count: 0)
***  - unload event is clearly firing and not being blocked when going to settings
***  - never see navigation flag being set in sessionStorage ***

***  eighteenth attempt:  ***
***  update: works  ***
******************************************************************
// session termination api

// Debug helper
function logDebug(message, data = {}) {
    console.log(`%c${message}`, 'background: #333; color: lime; padding: 2px;', {
        timestamp: new Date().toISOString(),
        url: window.location.href,
        path: window.location.pathname,
        ...data
    });
}

// Global flag to track settings navigation
document.addEventListener('DOMContentLoaded', function() {
    logDebug('DOMContentLoaded fired', {
        existingFlag: sessionStorage.getItem('navigatingToSettings')
    });

    // Clear flag only if we're not on settings page
    if (!window.location.pathname.includes('/settings')) {
        sessionStorage.removeItem('navigatingToSettings');
    }
    
    // More aggressive link detection
    function addSettingsListeners() {
        // Query for any possible settings-related elements
        const settingsElements = document.querySelectorAll(`
            a[href*="settings"],
            .view-settings, 
            .view-cases,
            .change-settings,
            .settings-switch div,
            [onclick*="settings"],
            [data-href*="settings"],
            .view-my-cases,
            .view-my-settings,
            .change-my-settings
        `);

        logDebug('Found settings elements', {
            count: settingsElements.length,
            elements: Array.from(settingsElements).map(el => ({
                className: el.className,
                href: el.href,
                text: el.textContent?.trim()
            }))
        });

        settingsElements.forEach(element => {
            element.addEventListener('click', (e) => {
                logDebug('Settings element clicked', {
                    element: e.target.outerHTML
                });
                sessionStorage.setItem('navigatingToSettings', 'true');
            }, true); // Use capture phase
        });
    }

    // Initial setup
    addSettingsListeners();

    // Also watch for dynamically added elements
    const observer = new MutationObserver((mutations) => {
        for (const mutation of mutations) {
            if (mutation.addedNodes.length) {
                addSettingsListeners();
            }
        }
    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
});

// Global click handler as backup
document.addEventListener('click', (e) => {
    // Check if the click target or any of its parents are settings-related
    const settingsElement = e.target.closest(`
        a[href*="settings"],
        .view-settings, 
        .view-cases,
        .change-settings,
        .settings-switch div,
        [onclick*="settings"],
        [data-href*="settings"],
        .view-my-cases,
        .view-my-settings,
        .change-my-settings
    `);

    if (settingsElement) {
        logDebug('Settings element clicked (global handler)', {
            element: settingsElement.outerHTML
        });
        sessionStorage.setItem('navigatingToSettings', 'true');
    }
}, true); // Use capture phase

// Session termination handler
window.addEventListener('unload', function(e) {
    const isSettingsPage = window.location.pathname.includes('/settings');
    const goingToSettings = sessionStorage.getItem('navigatingToSettings') === 'true';
    const sessionCookie = document.cookie.split(';')
        .find(c => c.trim().startsWith('session='));
    const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';
    
    logDebug('Unload event', {
        isSettingsPage,
        goingToSettings,
        sessionValue,
        pathname: window.location.pathname,
        referrer: document.referrer
    });

    // NEVER terminate on settings page
    if (isSettingsPage) {
        logDebug('On settings page - preventing termination');
        return;
    }

    // Don't terminate if going to settings
    if (goingToSettings) {
        logDebug('Going to settings - preventing termination');
        return;
    }

    // Don't terminate if session off or refresh
    if (sessionValue === 'off' || performance.navigation.type === 1) {
        logDebug('Session off or refresh - preventing termination');
        return;
    }

    logDebug('Proceeding with termination');
    if (navigator.sendBeacon) {
        navigator.sendBeacon('/api/terminate_session.php');
    } else {
        fetch('/api/terminate_session.php', {
            method: 'POST',
            keepalive: true
        });
    }
});

// Additional monitoring
window.addEventListener('beforeunload', (e) => {
    logDebug('beforeunload event', {
        storage: sessionStorage.getItem('navigatingToSettings')
    });
});
/******************************************************************/


/******************************************************************
***  eighteenth attempt (without debug)  ***
******************************************************************/

// Global flag to track settings navigation
document.addEventListener('DOMContentLoaded', function() {
    // Clear flag only if we're not on settings page
    if (!window.location.pathname.includes('/settings')) {
        sessionStorage.removeItem('navigatingToSettings');
    }
    
    // Settings link detection
    function addSettingsListeners() {
        const settingsElements = document.querySelectorAll(`
            a[href*="settings"],
            .view-settings, 
            .view-cases,
            .change-settings,
            .settings-switch div,
            [onclick*="settings"],
            [data-href*="settings"],
            .view-my-cases,
            .view-my-settings,
            .change-my-settings
        `);

        settingsElements.forEach(element => {
            element.addEventListener('click', () => {
                sessionStorage.setItem('navigatingToSettings', 'true');
            }, true);
        });
    }

    // Initial setup
    addSettingsListeners();

    // Watch for dynamically added elements
    const observer = new MutationObserver((mutations) => {
        for (const mutation of mutations) {
            if (mutation.addedNodes.length) {
                addSettingsListeners();
            }
        }
    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
});

// Global click handler as backup
document.addEventListener('click', (e) => {
    const settingsElement = e.target.closest(`
        a[href*="settings"],
        .view-settings, 
        .view-cases,
        .change-settings,
        .settings-switch div,
        [onclick*="settings"],
        [data-href*="settings"],
        .view-my-cases,
        .view-my-settings,
        .change-my-settings
    `);

    if (settingsElement) {
        sessionStorage.setItem('navigatingToSettings', 'true');
    }
}, true);

// Session termination handler
window.addEventListener('unload', function(e) {
    const isSettingsPage = window.location.pathname.includes('/settings');
    const goingToSettings = sessionStorage.getItem('navigatingToSettings') === 'true';
    const sessionCookie = document.cookie.split(';')
        .find(c => c.trim().startsWith('session='));
    const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';

    // Don't terminate if:
    // 1. On settings page OR
    // 2. Going to settings OR
    // 3. Session is explicitly off OR
    // 4. It's a page refresh
    if (isSettingsPage || 
        goingToSettings || 
        sessionValue === 'off' || 
        performance.navigation.type === 1) {
        return;
    }

    // Proceed with termination
    if (navigator.sendBeacon) {
        navigator.sendBeacon('/api/terminate_session.php');
    } else {
        fetch('/api/terminate_session.php', {
            method: 'POST',
            keepalive: true
        });
    }
});


/******************************************************************
***  ninteenth attempt: add tab detection  ***
******************************************************************/

// Global flag to track settings navigation
document.addEventListener('DOMContentLoaded', function() {
    // Handle new tab detection
    if (!document.referrer) {
        // This is a new tab/window - terminate immediately if not settings
        if (!window.location.pathname.includes('/settings')) {
            if (navigator.sendBeacon) {
                navigator.sendBeacon('/api/terminate_session.php');
            } else {
                fetch('/api/terminate_session.php', {
                    method: 'POST',
                    keepalive: true
                });
            }
        }
    }

    // Clear flag only if we're not on settings page
    if (!window.location.pathname.includes('/settings')) {
        sessionStorage.removeItem('navigatingToSettings');
    }
    
    // Settings link detection
    function addSettingsListeners() {
        const settingsElements = document.querySelectorAll(`
            a[href*="settings"],
            .view-settings, 
            .view-cases,
            .change-settings,
            .settings-switch div,
            [onclick*="settings"],
            [data-href*="settings"],
            .view-my-cases,
            .view-my-settings,
            .change-my-settings
        `);

        settingsElements.forEach(element => {
            element.addEventListener('click', () => {
                sessionStorage.setItem('navigatingToSettings', 'true');
            }, true);
        });
    }

    // Initial setup
    addSettingsListeners();

    // Watch for dynamically added elements
    const observer = new MutationObserver((mutations) => {
        for (const mutation of mutations) {
            if (mutation.addedNodes.length) {
                addSettingsListeners();
            }
        }
    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
});

// Global click handler as backup
document.addEventListener('click', (e) => {
    const settingsElement = e.target.closest(`
        a[href*="settings"],
        .view-settings, 
        .view-cases,
        .change-settings,
        .settings-switch div,
        [onclick*="settings"],
        [data-href*="settings"],
        .view-my-cases,
        .view-my-settings,
        .change-my-settings
    `);

    if (settingsElement) {
        sessionStorage.setItem('navigatingToSettings', 'true');
    }
}, true);

// Session termination handler
window.addEventListener('unload', function(e) {
    const isSettingsPage = window.location.pathname.includes('/settings');
    const goingToSettings = sessionStorage.getItem('navigatingToSettings') === 'true';
    const sessionCookie = document.cookie.split(';')
        .find(c => c.trim().startsWith('session='));
    const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';

    // Don't terminate if:
    // 1. On settings page OR
    // 2. Going to settings OR
    // 3. Session is explicitly off OR
    // 4. It's a page refresh
    if (isSettingsPage || 
        goingToSettings || 
        sessionValue === 'off' || 
        performance.navigation.type === 1) {
        return;
    }

    // Proceed with termination
    if (navigator.sendBeacon) {
        navigator.sendBeacon('/api/terminate_session.php');
    } else {
        fetch('/api/terminate_session.php', {
            method: 'POST',
            keepalive: true
        });
    }
});



/******************************************************************
***  twentieth attempt: referrer check and sessionStorage to detect new tabs more reliably  ***
******************************************************************/

// Global flag to track settings navigation
document.addEventListener('DOMContentLoaded', function() {
    // Check if this is a fresh browser tab
    const isNewTab = !document.referrer || 
                    !sessionStorage.getItem('tabInitialized');
    
    // Mark this tab as initialized
    sessionStorage.setItem('tabInitialized', 'true');
    
    // Handle new tab detection
    if (isNewTab) {
        const isSettingsPage = window.location.pathname.includes('/settings');
        const sessionCookie = document.cookie.split(';')
            .find(c => c.trim().startsWith('session='));
        const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';

        // Only terminate if:
        // 1. Not on settings page AND
        // 2. Session is not explicitly off
        if (!isSettingsPage && sessionValue !== 'off') {
            if (navigator.sendBeacon) {
                navigator.sendBeacon('/api/terminate_session.php');
            } else {
                fetch('/api/terminate_session.php', {
                    method: 'POST',
                    keepalive: true
                });
            }
            return; // Exit early after termination
        }
    }

    // Clear navigation flag only if we're not on settings page
    if (!window.location.pathname.includes('/settings')) {
        sessionStorage.removeItem('navigatingToSettings');
    }
    
    // Settings link detection
    function addSettingsListeners() {
        const settingsElements = document.querySelectorAll(`
            a[href*="settings"],
            .view-settings, 
            .view-cases,
            .change-settings,
            .settings-switch div,
            [onclick*="settings"],
            [data-href*="settings"],
            .view-my-cases,
            .view-my-settings,
            .change-my-settings
        `);

        settingsElements.forEach(element => {
            element.addEventListener('click', () => {
                sessionStorage.setItem('navigatingToSettings', 'true');
            }, true);
        });
    }

    // Initial setup
    addSettingsListeners();

    // Watch for dynamically added elements
    const observer = new MutationObserver((mutations) => {
        for (const mutation of mutations) {
            if (mutation.addedNodes.length) {
                addSettingsListeners();
            }
        }
    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
});

// Global click handler as backup
document.addEventListener('click', (e) => {
    const settingsElement = e.target.closest(`
        a[href*="settings"],
        .view-settings, 
        .view-cases,
        .change-settings,
        .settings-switch div,
        [onclick*="settings"],
        [data-href*="settings"],
        .view-my-cases,
        .view-my-settings,
        .change-my-settings
    `);

    if (settingsElement) {
        sessionStorage.setItem('navigatingToSettings', 'true');
    }
}, true);

// Session termination handler
window.addEventListener('unload', function(e) {
    const isSettingsPage = window.location.pathname.includes('/settings');
    const goingToSettings = sessionStorage.getItem('navigatingToSettings') === 'true';
    const sessionCookie = document.cookie.split(';')
        .find(c => c.trim().startsWith('session='));
    const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';

    // Don't terminate if:
    // 1. On settings page OR
    // 2. Going to settings OR
    // 3. Session is explicitly off OR
    // 4. It's a page refresh
    if (isSettingsPage || 
        goingToSettings || 
        sessionValue === 'off' || 
        performance.navigation.type === 1) {
        return;
    }

    // Proceed with termination
    if (navigator.sendBeacon) {
        navigator.sendBeacon('/api/terminate_session.php');
    } else {
        fetch('/api/terminate_session.php', {
            method: 'POST',
            keepalive: true
        });
    }
});



/******************************************************************
***  twenty-first attempt: localStorage instead of sessionStorage to detect new tabs more reliably  ***
******************************************************************/

// Global flag to track settings navigation
document.addEventListener('DOMContentLoaded', function() {
    // Check for new tab using localStorage and referrer
    function isNewTabNavigation() {
        // Get the current tab ID or create a new one
        const currentTabId = localStorage.getItem('currentTabId') || Date.now().toString();
        const lastTabId = localStorage.getItem('lastTabId');

        // Update tab IDs
        localStorage.setItem('lastTabId', currentTabId);
        localStorage.setItem('currentTabId', currentTabId);

        // It's a new tab if:
        // 1. There's no referrer OR
        // 2. The tab ID doesn't match the last tab ID
        return !document.referrer || currentTabId !== lastTabId;
    }

    // Handle new tab detection
    if (isNewTabNavigation()) {
        const isSettingsPage = window.location.pathname.includes('/settings');
        const sessionCookie = document.cookie.split(';')
            .find(c => c.trim().startsWith('session='));
        const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';

        // Terminate if not settings page and session isn't off
        if (!isSettingsPage && sessionValue !== 'off') {
            if (navigator.sendBeacon) {
                navigator.sendBeacon('/api/terminate_session.php');
            } else {
                fetch('/api/terminate_session.php', {
                    method: 'POST',
                    keepalive: true
                });
            }
            return;
        }
    }

    // Clear navigation flag if not on settings page
    if (!window.location.pathname.includes('/settings')) {
        sessionStorage.removeItem('navigatingToSettings');
    }
    
    // Settings link detection
    function addSettingsListeners() {
        const settingsElements = document.querySelectorAll(`
            a[href*="settings"],
            .view-settings, 
            .view-cases,
            .change-settings,
            .settings-switch div,
            [onclick*="settings"],
            [data-href*="settings"],
            .view-my-cases,
            .view-my-settings,
            .change-my-settings
        `);

        settingsElements.forEach(element => {
            element.addEventListener('click', () => {
                sessionStorage.setItem('navigatingToSettings', 'true');
            }, true);
        });
    }

    // Initial setup
    addSettingsListeners();

    // Watch for dynamically added elements
    const observer = new MutationObserver((mutations) => {
        for (const mutation of mutations) {
            if (mutation.addedNodes.length) {
                addSettingsListeners();
            }
        }
    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
});

// Global click handler as backup
document.addEventListener('click', (e) => {
    const settingsElement = e.target.closest(`
        a[href*="settings"],
        .view-settings, 
        .view-cases,
        .change-settings,
        .settings-switch div,
        [onclick*="settings"],
        [data-href*="settings"],
        .view-my-cases,
        .view-my-settings,
        .change-my-settings
    `);

    if (settingsElement) {
        sessionStorage.setItem('navigatingToSettings', 'true');
    }
}, true);

// Session termination handler
window.addEventListener('unload', function(e) {
    const isSettingsPage = window.location.pathname.includes('/settings');
    const goingToSettings = sessionStorage.getItem('navigatingToSettings') === 'true';
    const sessionCookie = document.cookie.split(';')
        .find(c => c.trim().startsWith('session='));
    const sessionValue = sessionCookie ? sessionCookie.split('=')[1].trim() : 'on';

    // Don't terminate if:
    // 1. On settings page OR
    // 2. Going to settings OR
    // 3. Session is explicitly off OR
    // 4. It's a page refresh
    if (isSettingsPage || 
        goingToSettings || 
        sessionValue === 'off' || 
        performance.navigation.type === 1) {
        return;
    }

    // Proceed with termination
    if (navigator.sendBeacon) {
        navigator.sendBeacon('/api/terminate_session.php');
    } else {
        fetch('/api/terminate_session.php', {
            method: 'POST',
            keepalive: true
        });
    }
});