<?php
// Include header (which includes all dependencies)
include 'includes/header.php';
$page_title = $lang_frontend['PAGE_TITLE_LIVE_CHAT'] ?? 'Live Chat';

// Check if live chat is enabled
if (!defined('LIVE_CHAT') || !LIVE_CHAT) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_LIVE_CHAT_DISABLED'] ?? 'Live chat is currently disabled.', 'warning');
    redirectTo('index');
    exit;
}

// Get current user info for chat
$current_user = [
    'id' => isLoggedIn() ? $_SESSION['user_id'] : 'guest_' . session_id(),
    'name' => isLoggedIn() ? $_SESSION['name'] : ($lang_frontend['LIVE_CHAT_GUEST_NAME_DEFAULT'] ?? 'Guest'),
    'avatar' => isLoggedIn() && !empty($_SESSION['avatar']) ? $_SESSION['avatar'] : null,
    'role' => isLoggedIn() ? $_SESSION['role'] : 'guest',
    'is_operator' => isLoggedIn() && (isAdmin() || isStaff())
];
?>

<div class="row h-100">
    <div class="col-12">
        <div class="card h-100" style="min-height: 600px;">
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="bi bi-chat-dots"></i> <?php echo $lang_frontend['LIVE_CHAT_HEADER'] ?? 'Live Chat'; ?>
                    <span id="operatorStatus"
                        class="badge bg-secondary ms-2"><?php echo $lang_frontend['LIVE_CHAT_OPERATOR_STATUS_CHECKING'] ?? 'Checking...'; ?></span>
                </h5>
                <div id="chatControls" class="d-flex align-items-center">
                    <?php if ($current_user['is_operator']): ?>
                        <span class="badge bg-warning me-2"
                            id="activeUsersCount"><?php echo $lang_frontend['LIVE_CHAT_USERS_ONLINE_NONE'] ?? '0 users online'; ?></span>
                    <?php endif; ?>
                    <button class="btn btn-outline-light btn-sm" id="clearChatBtn"
                        title="<?php echo $lang_frontend['LIVE_CHAT_BUTTON_CLEAR_CHAT_TITLE'] ?? 'Clear Chat'; ?>">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>

            <div class="card-body d-flex flex-column p-0" style="height: 550px;">
                <?php if ($current_user['is_operator']): ?>
                    <!-- Operator View: User List + Chat -->
                    <div class="row h-100 g-0">
                        <div class="col-md-4 border-end">
                            <div class="p-3 border-bottom bg-light">
                                <h6 class="mb-0">
                                    <?php echo $lang_frontend['LIVE_CHAT_HEADING_ACTIVE_USERS'] ?? 'Active Users'; ?></h6>
                            </div>
                            <div id="usersList" class="p-2" style="height: 450px; overflow-y: auto;">
                                <div class="text-center text-muted p-3">
                                    <i class="bi bi-people" style="font-size: 2rem;"></i>
                                    <p class="mb-0">
                                        <?php echo $lang_frontend['LIVE_CHAT_NO_USERS_ONLINE'] ?? 'No users online'; ?></p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-8 d-flex flex-column">
                            <div class="p-3 border-bottom bg-light">
                                <h6 class="mb-0" id="selectedUserName">
                                    <?php echo $lang_frontend['LIVE_CHAT_SELECT_USER_TO_CHAT'] ?? 'Select a user to chat'; ?>
                                </h6>
                            </div>
                            <div id="chatMessages" class="flex-grow-1 p-3" style="height: 350px; overflow-y: auto;">
                                <div class="text-center text-muted p-4">
                                    <i class="bi bi-chat-text" style="font-size: 3rem;"></i>
                                    <p class="mb-0">
                                        <?php echo $lang_frontend['LIVE_CHAT_SELECT_USER_PROMPT'] ?? 'Select a user from the left to start chatting'; ?>
                                    </p>
                                </div>
                            </div>
                            <div id="messageInputArea" class="p-3 border-top bg-light" style="display: none;">
                                <div class="input-group">
                                    <input type="text" id="messageInput" class="form-control"
                                        placeholder="<?php echo $lang_frontend['LIVE_CHAT_MESSAGE_INPUT_PLACEHOLDER'] ?? 'Type your message...'; ?>"
                                        disabled>
                                    <button class="btn btn-primary" id="sendMessageBtn" disabled>
                                        <i class="bi bi-send"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php else: ?>
                    <!-- User/Guest View: Chat Only -->
                    <div id="operatorOfflineMessage" class="alert alert-warning m-3" style="display: none;">
                        <i class="bi bi-exclamation-triangle"></i>
                        <strong><?php echo $lang_frontend['LIVE_CHAT_OPERATORS_UNAVAILABLE_TITLE'] ?? 'Operators are not currently available.'; ?></strong>
                        <?php if (ALLOW_GUEST_TICKETS || isLoggedIn()): ?>
                            <br><?php echo $lang_frontend['YOU_CAN_TEXT'] ?? 'You can '; ?><a
                                href="<?php echo getCleanUrl('ticket_create'); ?>"
                                class="alert-link"><?php echo $lang_frontend['LIVE_CHAT_LINK_SEND_TICKET_INSTEAD'] ?? 'send a ticket instead'; ?></a><?php echo $lang_frontend['AND_WE_WILL_GET_BACK_TEXT'] ?? " and we'll get back to you soon."; ?>
                        <?php endif; ?>
                    </div>

                    <div id="chatContainer" class="d-flex flex-column h-100" style="display: none;">
                        <div id="chatMessages" class="flex-grow-1 p-3" style="overflow-y: auto;">
                            <div class="text-center text-muted p-4">
                                <i class="bi bi-chat-heart" style="font-size: 3rem; color: #6c757d;"></i>
                                <p class="mb-0">
                                    <?php echo $lang_frontend['LIVE_CHAT_WELCOME_MESSAGE'] ?? 'Welcome to live chat! Start a conversation below.'; ?>
                                </p>
                            </div>
                        </div>
                        <div class="p-3 border-top bg-light">
                            <div class="input-group">
                                <input type="text" id="messageInput" class="form-control"
                                    placeholder="<?php echo $lang_frontend['LIVE_CHAT_MESSAGE_INPUT_PLACEHOLDER'] ?? 'Type your message...'; ?>">
                                <button class="btn btn-primary" id="sendMessageBtn">
                                    <i class="bi bi-send"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<style>
    .chat-message {
        margin-bottom: 15px;
        padding: 10px;
        border-radius: 10px;
        max-width: 80%;
        word-wrap: break-word;
    }

    .chat-message.own {
        background-color: #007bff;
        color: white;
        margin-left: auto;
        text-align: right;
    }

    .chat-message.other {
        background-color: #f8f9fa;
        border: 1px solid #dee2e6;
        margin-right: auto;
    }

    .chat-message .message-header {
        font-size: 0.85rem;
        opacity: 0.8;
        margin-bottom: 5px;
    }

    .chat-message .message-time {
        font-size: 0.75rem;
        opacity: 0.7;
        margin-top: 5px;
    }

    .user-item {
        padding: 10px;
        margin-bottom: 5px;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.2s ease;
        border: 1px solid transparent;
    }

    .user-item:hover {
        background-color: #f8f9fa;
        border-color: #dee2e6;
    }

    .user-item.active {
        background-color: #007bff;
        color: white;
    }

    .user-item.has-unread {
        border-left: 4px solid #28a745;
        background-color: #d4edda;
    }

    .user-item.active.has-unread {
        border-left-color: #ffffff;
    }

    .user-avatar {
        width: 35px;
        height: 35px;
        border-radius: 50%;
        object-fit: cover;
    }

    .user-avatar-placeholder {
        width: 35px;
        height: 35px;
        border-radius: 50%;
        background-color: #6c757d;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        font-weight: bold;
    }

    .online-indicator {
        width: 10px;
        height: 10px;
        background-color: #28a745;
        border-radius: 50%;
        position: relative;
        top: -2px;
        animation: pulse 2s infinite;
    }

    @keyframes pulse {
        0% {
            opacity: 1;
        }

        50% {
            opacity: 0.5;
        }

        100% {
            opacity: 1;
        }
    }

    #chatMessages {
        scroll-behavior: smooth;
    }
</style>

<script>
    class LiveChat {
        constructor(csrfToken) {
            this.currentUser = <?php echo json_encode($current_user); ?>;
            this.csrfToken = csrfToken;
            this.selectedUserId = null;
            this.messages = [];
            this.lang = {
                online: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_STATUS_ONLINE'] ?? 'Online'); ?>',
                onlineCount: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_STATUS_ONLINE_COUNT'] ?? 'Online (%d)'); ?>',
                offline: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_STATUS_OFFLINE'] ?? 'Offline'); ?>',
                noUsersOnline: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_NO_USERS_ONLINE'] ?? $lang_frontend['LIVE_CHAT_NO_USERS_ONLINE'] ?? 'No users online'); ?>',
                usersCountSingular: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_USERS_COUNT_TEXT_SINGULAR'] ?? 'user online'); ?>',
                usersCountPlural: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_USERS_COUNT_TEXT_PLURAL'] ?? 'users online'); ?>',
                usersCountZero: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_USERS_COUNT_TEXT_ZERO'] ?? 'users online'); ?>',
                userStatusOnline: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_USER_STATUS_ONLINE'] ?? 'Online'); ?>',
                chatWithUser: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_CHAT_WITH_USER'] ?? 'Chat with %s'); ?>',
                noMessagesYet: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_NO_MESSAGES_YET'] ?? 'No messages yet. Start the conversation!'); ?>',
                unknownUser: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_UNKNOWN_USER'] ?? $lang_frontend['TEXT_UNKNOWN_USER'] ?? 'Unknown User'); ?>',
                alertSelectUser: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_ALERT_SELECT_USER_TO_SEND_MESSAGE'] ?? 'Please select a user to send a message to.'); ?>',
                alertNoOperators: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_ALERT_NO_OPERATORS_AVAILABLE'] ?? 'No operators are currently available.'); ?>',
                alertSendMessageFailed: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_ALERT_SEND_MESSAGE_FAILED'] ?? 'Failed to send message: %s'); ?>',
                alertUnknownError: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_UNKNOWN_ERROR'] ?? 'Unknown error'); ?>',
                alertSendMessageFailedTryAgain: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_ALERT_SEND_MESSAGE_FAILED_TRY_AGAIN'] ?? 'Failed to send message. Please try again.'); ?>',
                confirmClearChat: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_CONFIRM_CLEAR_CHAT'] ?? 'Are you sure you want to clear the chat? This will remove all messages.'); ?>',
                alertClearChatFailed: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_ALERT_CLEAR_CHAT_FAILED'] ?? 'Failed to clear chat: %s'); ?>',
                alertClearChatFailedTryAgain: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_ALERT_CLEAR_CHAT_FAILED_TRY_AGAIN'] ?? 'Failed to clear chat. Please try again.'); ?>',
                alertSendMessageFailedCheckConnection: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_ALERT_SEND_MESSAGE_FAILED_CHECK_CONNECTION'] ?? 'Failed to send message. Please check your connection.'); ?>',
                alertClearChatFailedCheckConnection: '<?php echo addslashes($lang_frontend['LIVE_CHAT_JS_ALERT_CLEAR_CHAT_FAILED_CHECK_CONNECTION'] ?? 'Failed to clear chat. Please check your connection.'); ?>'
            };
            this.users = [];
            this.lastActivity = Date.now();

            this.init();
            this.startPolling();
        }

        init() {
            // Event listeners
            document.getElementById('sendMessageBtn').addEventListener('click', () => this.sendMessage());
            document.getElementById('messageInput').addEventListener('keypress', (e) => {
                if (e.key === 'Enter') this.sendMessage();
            });
            document.getElementById('clearChatBtn').addEventListener('click', () => this.clearChat());

            // Initialize data in proper sequence
            this.loadInitialData();
        }

        async loadInitialData() {
            // First, register current user as online
            await this.updateUserActivity();

            // Then load all users and messages
            await this.loadUsers();
            await this.loadMessages();

            // Check operator availability
            this.checkOperatorAvailability();

            // Update UI based on user role
            if (this.currentUser.is_operator) {
                this.renderUsersList();
            } else {
                this.renderMessages();
            }
        }

        async updateUserActivity() {
            try {
                const formData = new FormData();
                formData.append('action', 'update_user');
                formData.append('csrf_token', this.csrfToken);

                const response = await fetch('chat_api.php', {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const responseText = await response.text();

                if (responseText.trim() === '') {
                    return false;
                }

                const data = JSON.parse(responseText);
                return data.success;
            } catch (error) {
                console.error('Error updating user activity:', error);
                console.error('Error details:', error.message);
                return false;
            }
        }

        checkOperatorAvailability() {
            const allOperators = this.users.filter(user => user.is_operator);
            const onlineOperators = this.users.filter(user =>
                user.is_operator && this.isUserOnline(user)
            );

            const isOperatorAvailable = onlineOperators.length > 0;
            const statusElement = document.getElementById('operatorStatus');

            if (this.currentUser.is_operator) {
                statusElement.textContent = this.lang.online;
                statusElement.className = 'badge bg-success ms-2';
            } else {
                if (isOperatorAvailable) {
                    statusElement.textContent = this.lang.onlineCount.replace('%d', onlineOperators.length);
                    statusElement.className = 'badge bg-success ms-2';
                    document.getElementById('operatorOfflineMessage').style.display = 'none';
                    document.getElementById('chatContainer').style.display = 'flex';
                } else {
                    statusElement.textContent = this.lang.offline;
                    statusElement.className = 'badge bg-danger ms-2';
                    document.getElementById('operatorOfflineMessage').style.display = 'block';
                    document.getElementById('chatContainer').style.display = 'none';
                }
            }
        }

        isUserOnline(user) {
            return (Date.now() / 1000 - user.lastSeen) < 30; // 30 seconds
        }

        renderUsersList() {
            const usersList = document.getElementById('usersList');
            const activeUsers = this.users.filter(user =>
                !user.is_operator && this.isUserOnline(user)
            );

            if (activeUsers.length === 0) {
                usersList.innerHTML = `
                <div class="text-center text-muted p-3">
                    <i class="bi bi-people" style="font-size: 2rem;"></i>
                    <p class="mb-0">${this.lang.noUsersOnline}</p>
                </div>
            `;
                document.getElementById('activeUsersCount').textContent = `0 ${this.lang.usersCountZero}`;
                return;
            }

            document.getElementById('activeUsersCount').textContent = `${activeUsers.length} ${activeUsers.length !== 1 ? this.lang.usersCountPlural : this.lang.usersCountSingular}`;

            usersList.innerHTML = activeUsers.map(user => {
                const unreadCount = this.getUnreadCount(user.id);
                const isActive = this.selectedUserId === user.id;

                return `
                <div class="user-item ${isActive ? 'active' : ''} ${unreadCount > 0 ? 'has-unread' : ''}" 
                     data-user-id="${user.id}" onclick="liveChat.selectUser('${user.id}')">
                    <div class="d-flex align-items-center">
                        <div class="me-2">
                            ${user.avatar ?
                        `<img src="uploads/avatars/${user.avatar}" class="user-avatar" alt="${user.name}">` :
                        `<div class="user-avatar-placeholder">${user.name.charAt(0).toUpperCase()}</div>`
                    }
                        </div>
                        <div class="flex-grow-1">
                            <div class="fw-bold">${user.name}</div>
                            <div class="small text-muted d-flex align-items-center">
                                <span class="online-indicator me-1"></span>
                                ${this.lang.userStatusOnline}
                                ${unreadCount > 0 ? `<span class="badge bg-success ms-auto">${unreadCount}</span>` : ''}
                            </div>
                        </div>
                    </div>
                </div>
            `;
            }).join('');
        }

        selectUser(userId) {
            this.selectedUserId = userId;
            const user = this.users.find(u => u.id === userId);

            if (user) {
                document.getElementById('selectedUserName').textContent = this.lang.chatWithUser.replace('%s', user.name);
                document.getElementById('messageInputArea').style.display = 'block';
                document.getElementById('messageInput').disabled = false;
                document.getElementById('sendMessageBtn').disabled = false;

                this.markMessagesAsRead(userId);
                this.loadMessages();
                this.renderUsersList(); // Refresh to remove unread indicator
            }
        }

        getUnreadCount(userId) {
            return this.messages.filter(msg =>
                msg.from === userId && msg.to === this.currentUser.id && !msg.read
            ).length;
        }

        async markMessagesAsRead(fromUserId) {
            try {
                const formData = new FormData();
                formData.append('action', 'mark_read');
                formData.append('from_user_id', fromUserId);
                formData.append('csrf_token', this.csrfToken);

                const response = await fetch('chat_api.php', {
                    method: 'POST',
                    body: formData
                });

                if (response.ok) {
                    // Update local messages
                    this.messages.forEach(msg => {
                        if (msg.from === fromUserId && msg.to === this.currentUser.id) {
                            msg.read = true;
                        }
                    });
                }
            } catch (error) {
                console.error('Error marking messages as read:', error);
            }
        }

        async loadUsers() {
            try {
                const response = await fetch('chat_api.php?action=get_users');
                if (response.ok) {
                    const responseText = await response.text();

                    if (responseText.trim() === '') {
                        this.users = [];
                    } else {
                        this.users = JSON.parse(responseText);
                    }
                } else {
                    console.error('Failed to load users, HTTP status:', response.status);
                }
            } catch (error) {
                console.error('Error loading users:', error);
                console.error('Error details:', error.message);
            }
        }

        async loadMessages() {
            try {
                let url = 'chat_api.php?action=get_messages';
                if (this.currentUser.is_operator && this.selectedUserId) {
                    url += `&selected_user=${this.selectedUserId}`;
                }

                const response = await fetch(url);
                if (response.ok) {
                    const responseText = await response.text();

                    if (responseText.trim() === '') {
                        this.messages = [];
                    } else {
                        this.messages = JSON.parse(responseText);
                    }
                    this.renderMessages();
                } else {
                    console.error('HTTP error:', response.status, response.statusText);
                }
            } catch (error) {
                console.error('Error loading messages:', error);
                console.error('Error details:', error.message);
            }
        }

        renderMessages() {
            const chatMessages = document.getElementById('chatMessages');

            let relevantMessages;
            if (this.currentUser.is_operator && this.selectedUserId) {
                relevantMessages = this.messages.filter(msg =>
                    (msg.from === this.currentUser.id && msg.to === this.selectedUserId) ||
                    (msg.from === this.selectedUserId && msg.to === this.currentUser.id)
                );
            } else {
                relevantMessages = this.messages.filter(msg =>
                    msg.from === this.currentUser.id || msg.to === this.currentUser.id
                );
            }

            if (relevantMessages.length === 0) {
                chatMessages.innerHTML = `
                <div class="text-center text-muted p-4">
                    <i class="bi bi-chat-heart" style="font-size: 3rem; color: #6c757d;"></i>
                    <p class="mb-0">${this.lang.noMessagesYet}</p>
                </div>
            `;
                return;
            }

            chatMessages.innerHTML = relevantMessages.map(msg => {
                const isOwn = msg.from === this.currentUser.id;
                const sender = this.users.find(u => u.id === msg.from) || { name: this.lang.unknownUser };
                const timestamp = new Date(msg.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });

                return `
                <div class="chat-message ${isOwn ? 'own' : 'other'}">
                    ${!isOwn ? `<div class="message-header">${sender.name}</div>` : ''}
                    <div>${msg.message}</div>
                    <div class="message-time">${timestamp}</div>
                </div>
            `;
            }).join('');

            // Scroll to bottom
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        async sendMessage() {
            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value.trim();

            if (!message) return;

            let targetUserId;
            if (this.currentUser.is_operator) {
                if (!this.selectedUserId) {
                    alert(this.lang.alertSelectUser);
                    return;
                }
                targetUserId = this.selectedUserId;
            } else {
                // Find an online operator
                const operators = this.users.filter(user =>
                    user.is_operator && this.isUserOnline(user)
                );
                if (operators.length === 0) {
                    alert(this.lang.alertNoOperators);
                    return;
                }
                targetUserId = operators[0].id; // Send to first available operator
            }

            try {
                const formData = new FormData();
                formData.append('action', 'send_message');
                formData.append('message', message);
                formData.append('target_user_id', targetUserId);
                formData.append('csrf_token', this.csrfToken);

                const response = await fetch('chat_api.php', {
                    method: 'POST',
                    body: formData
                });

                if (response.ok) {
                    const data = await response.json();
                    if (data.success) {
                        messageInput.value = '';
                        await this.loadMessages();

                        if (this.currentUser.is_operator) {
                            this.renderUsersList();
                        }
                    } else {
                        alert(this.lang.alertSendMessageFailed.replace('%s', (data.error || this.lang.alertUnknownError)));
                    }
                } else {
                    alert(this.lang.alertSendMessageFailedTryAgain);
                }
            } catch (error) {
                console.error('Error sending message:', error);
                alert(this.lang.alertSendMessageFailedCheckConnection);
            }
        }

        async clearChat() {
            if (confirm(this.lang.confirmClearChat)) {
                try {
                    const formData = new FormData();
                    formData.append('action', 'clear_chat');
                    formData.append('csrf_token', this.csrfToken);
                    if (this.currentUser.is_operator && this.selectedUserId) {
                        formData.append('selected_user_id', this.selectedUserId);
                    }

                    const response = await fetch('chat_api.php', {
                        method: 'POST',
                        body: formData
                    });

                    if (response.ok) {
                        const data = await response.json();
                        if (data.success) {
                            await this.loadMessages();
                            if (this.currentUser.is_operator) {
                                this.renderUsersList();
                            }
                        } else {
                            alert(this.lang.alertClearChatFailed.replace('%s', (data.error || this.lang.alertUnknownError)));
                        }
                    } else {
                        alert(this.lang.alertClearChatFailedTryAgain);
                    }
                } catch (error) {
                    console.error('Error clearing chat:', error);
                    alert(this.lang.alertClearChatFailedCheckConnection);
                }
            }
        }

        startPolling() {
            setInterval(async () => {
                await this.updateUserActivity();
                await this.loadUsers();
                await this.loadMessages();
                this.checkOperatorAvailability();

                if (this.currentUser.is_operator) {
                    this.renderUsersList();
                }
            }, 5000); // Poll every 5 seconds to reduce server load
        }
    }

    // Initialize chat when page loads
    let liveChat;
    document.addEventListener('DOMContentLoaded', function () {
        liveChat = new LiveChat('<?php echo generate_csrf_token(); ?>');
    });

    // Clean up when page unloads
    window.addEventListener('beforeunload', function () {
        // User activity will automatically timeout on server
    });
</script>

<?php include 'includes/footer.php'; ?>