/**
 * Session Manager
 * Handles session timeout, activity tracking, and session refresh
 * GHAMECC Choir Management Platform
 */

class SessionManager {
    constructor(options = {}) {
        // Default options
        this.options = {
            timeout: 600000, // 10 minutes in milliseconds
            warningTime: 60000, // Show warning 1 minute before timeout
            warningElement: '#session-timeout-warning',
            logoutUrl: '/ghameccapp/logout.php',
            keepAliveUrl: '/ghameccapp/ajax/keep_alive.php',
            keepAliveInterval: 240000, // 4 minutes
            showWarning: null, // Custom function to show warning
            hideWarning: null, // Custom function to hide warning
            ...options
        };

        // Initialize variables
        this.timeoutTimer = null;
        this.warningTimer = null;
        this.keepAliveTimer = null;
        this.lastActivity = new Date().getTime();
        this.warningShown = false;

        // Initialize
        this.init();
    }

    /**
     * Initialize the session manager
     */
    init() {
        // Bind activity tracking events
        this.bindEvents();
        
        // Start timers
        this.resetTimers();
        
        // Start keep-alive interval
        this.startKeepAlive();
        
        // Set up event listeners for modal buttons
        this.setupModalListeners();
        
        console.log('Session manager initialized with timeout of ' + (this.options.timeout / 60000) + ' minutes');
    }

    /**
     * Set up event listeners for modal buttons
     */
    setupModalListeners() {
        // Add event listeners to warning buttons if they exist
        const stayLoggedInBtn = document.querySelector('#session-stay-logged-in');
        if (stayLoggedInBtn) {
            stayLoggedInBtn.addEventListener('click', () => this.resetActivity());
        }
        
        const logoutNowBtn = document.querySelector('#session-logout-now');
        if (logoutNowBtn) {
            logoutNowBtn.addEventListener('click', () => this.logout());
        }
    }

    /**
     * Bind events to track user activity
     */
    bindEvents() {
        // Track mouse movement, clicks, and keypresses
        const activityEvents = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart', 'click'];
        
        activityEvents.forEach(eventName => {
            document.addEventListener(eventName, () => this.resetActivity(), true);
        });
    }

    /**
     * Reset activity timestamp and timers
     */
    resetActivity() {
        this.lastActivity = new Date().getTime();
        
        // Hide warning if shown
        if (this.warningShown) {
            this.hideWarning();
        }
        
        // Reset timers
        this.resetTimers();
    }

    /**
     * Reset timeout and warning timers
     */
    resetTimers() {
        // Clear existing timers
        clearTimeout(this.timeoutTimer);
        clearTimeout(this.warningTimer);
        
        // Set new timers
        this.warningTimer = setTimeout(() => this.showWarning(), this.options.timeout - this.options.warningTime);
        this.timeoutTimer = setTimeout(() => this.logout(), this.options.timeout);
    }

    /**
     * Start keep-alive interval to refresh session
     */
    startKeepAlive() {
        // Clear any existing interval
        clearInterval(this.keepAliveTimer);
        
        // Set new interval
        this.keepAliveTimer = setInterval(() => this.keepAlive(), this.options.keepAliveInterval);
    }

    /**
     * Send AJAX request to keep session alive
     */
    keepAlive() {
        // Only send keep-alive if there was activity since last keep-alive
        const currentTime = new Date().getTime();
        const timeSinceLastActivity = currentTime - this.lastActivity;
        
        if (timeSinceLastActivity < this.options.keepAliveInterval) {
            fetch(this.options.keepAliveUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                credentials: 'same-origin'
            })
            .then(response => {
                if (response.ok) {
                    console.log('Session refreshed');
                } else {
                    console.error('Failed to refresh session');
                }
            })
            .catch(error => {
                console.error('Error refreshing session:', error);
            });
        }
    }

    /**
     * Show session timeout warning
     */
    showWarning() {
        // Use custom showWarning function if provided
        if (typeof this.options.showWarning === 'function') {
            this.options.showWarning();
            this.warningShown = true;
            return;
        }
        
        // Default behavior
        const warningElement = document.querySelector(this.options.warningElement);
        
        if (warningElement) {
            warningElement.style.display = 'block';
            this.warningShown = true;
        } else {
            // If no warning element exists, create a simple alert
            alert('Your session will expire in 1 minute due to inactivity. Please click OK to stay logged in.');
            this.resetActivity();
        }
    }

    /**
     * Hide session timeout warning
     */
    hideWarning() {
        // Use custom hideWarning function if provided
        if (typeof this.options.hideWarning === 'function') {
            this.options.hideWarning();
            this.warningShown = false;
            return;
        }
        
        // Default behavior
        const warningElement = document.querySelector(this.options.warningElement);
        
        if (warningElement) {
            warningElement.style.display = 'none';
        }
        
        this.warningShown = false;
    }

    /**
     * Logout user when session times out
     */
    logout() {
        window.location.href = this.options.logoutUrl;
    }
}
