// app.js - Client side scripts for Team Mania Pro

document.addEventListener("DOMContentLoaded", function() {
    initChat();
    initQRCodeGenerator();
    initNotificationPoll();
});

// 1. Live Chat Polling and Sending
let chatPollInterval = null;
let lastMessageId = 0;

function initChat() {
    const chatHistory = document.getElementById("chat-history");
    if (!chatHistory) return;

    const roomId = chatHistory.dataset.roomId;
    if (!roomId) return;

    const chatForm = document.getElementById("chat-form");
    const chatInput = document.getElementById("chat-input");

    // Scroll to bottom initially
    chatHistory.scrollTop = chatHistory.scrollHeight;

    // Start Polling messages every 2 seconds
    pollMessages(roomId);
    chatPollInterval = setInterval(() => pollMessages(roomId), 2000);

    // Form submission
    if (chatForm) {
        chatForm.addEventListener("submit", function(e) {
            e.preventDefault();
            const message = chatInput.value.trim();
            if (!message) return;

            // Disable input temporarily
            chatInput.disabled = true;

            const formData = new FormData();
            formData.append("room_id", roomId);
            formData.append("message", message);

            fetch("index.php?api=send_chat_message", {
                method: "POST",
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                chatInput.disabled = false;
                if (data.success) {
                    chatInput.value = "";
                    chatInput.focus();
                    pollMessages(roomId); // Instant update
                } else {
                    alert("Nachricht konnte nicht gesendet werden: " + (data.error || "Unbekannter Fehler"));
                }
            })
            .catch(err => {
                chatInput.disabled = false;
                console.error("Error sending message:", err);
            });
        });
    }
}

function pollMessages(roomId) {
    const chatHistory = document.getElementById("chat-history");
    if (!chatHistory) return;

    fetch(`index.php?api=chat_messages&room_id=${roomId}&last_id=${lastMessageId}`)
        .then(res => res.json())
        .then(data => {
            if (data.success && data.messages.length > 0) {
                let shouldScroll = chatHistory.scrollTop + chatHistory.clientHeight >= chatHistory.scrollHeight - 100;
                
                data.messages.forEach(msg => {
                    // Prevent duplicate rendering
                    if (document.getElementById(`msg-${msg.id}`)) return;

                    const msgDiv = document.createElement("div");
                    msgDiv.id = `msg-${msg.id}`;
                    msgDiv.className = `chat-msg ${msg.is_self ? 'chat-msg-sent' : 'chat-msg-received'}`;
                    
                    const senderName = msg.is_self ? 'Du' : `${msg.first_name} ${msg.last_name} (${msg.role_label})`;
                    
                    msgDiv.innerHTML = `
                        <strong>${escapeHTML(senderName)}</strong>
                        <div style="margin-top: 4px;">${escapeHTML(msg.message)}</div>
                        <div class="chat-msg-meta">${escapeHTML(msg.time)}</div>
                    `;
                    
                    chatHistory.appendChild(msgDiv);
                    if (msg.id > lastMessageId) {
                        lastMessageId = msg.id;
                    }
                });

                if (shouldScroll) {
                    chatHistory.scrollTop = chatHistory.scrollHeight;
                }
            }
        })
        .catch(err => console.error("Error fetching messages:", err));
}

// 2. Dynamic QR Code Generator for Notice/Print layout
function initQRCodeGenerator() {
    const qrContainer = document.getElementById("qr-code-img");
    if (!qrContainer) return;

    // Use current URL to construct a scan URL
    const currentUrl = window.location.href;
    // We can use the free global qrserver API to render a secure QR Code image
    const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${encodeURIComponent(currentUrl)}`;
    
    qrContainer.src = qrUrl;
}

// 3. Periodic Notification Poll
function initNotificationPoll() {
    const badge = document.getElementById("notification-badge");
    if (!badge) return;

    const checkNotifications = () => {
        fetch("index.php?api=notifications_unread")
            .then(res => res.json())
            .then(data => {
                if (data.success && data.count > 0) {
                    badge.textContent = data.count;
                    badge.style.display = "inline-flex";
                } else {
                    badge.style.display = "none";
                }
            })
            .catch(err => console.log("Notification check skipped"));
    };

    checkNotifications();
    setInterval(checkNotifications, 10000); // Check every 10 seconds
}

// Helper to escape HTML tags to prevent XSS
function escapeHTML(str) {
    return str.replace(/[&<>'"]/g, 
        tag => ({
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            "'": '&#39;',
            '"': '&quot;'
        }[tag] || tag)
    );
}

// Helper for print command
function triggerPrint() {
    window.print();
}
