<?php
/**
 * Bilik Tutor Component
 * Shared file room and chat for teachers
 */
?>

<div class="bilik-tutor-container">
    <!-- Header Section -->
    <div class="card premium-gradient" style="margin-bottom: 25px; color: white;">
        <div class="card-body" style="padding: 25px;">
            <div
                style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px;">
                <div>
                    <h2 style="margin: 0; font-weight: 800; letter-spacing: -0.5px;">🏢 Bilik Tutor</h2>
                    <p style="margin: 5px 0 0 0; opacity: 0.9; font-size: 0.95rem;">Ruang kolaborasi dan perkongsian
                        fail sesama guru/tutor.</p>
                </div>
                <div
                    style="background: rgba(255,255,255,0.2); padding: 10px 20px; border-radius: 15px; backdrop-filter: blur(5px);">
                    <span style="font-weight: 600;">Bilangan Fail: <span id="tutorFileCount">0</span></span>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content Layout -->
    <div class="tutor-grid">
        <!-- Section 1: File Room -->
        <div class="tutor-section file-room">
            <div class="card h-100">
                <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
                    <h3 class="card-title">📂 Ruang Fail</h3>
                    <div style="display: flex; flex-direction: column; align-items: flex-end; gap: 5px;">
                        <button class="btn btn-primary btn-sm"
                            onclick="document.getElementById('tutorFileUpload').click()"
                            style="height: 44px; display: flex; align-items: center; gap: 8px;">
                            <span>📤</span> Muat Naik
                        </button>
                        <small style="color: #888; font-size: 0.7rem;">PDF, Word, Excel, PPT, Imej, ZIP</small>
                    </div>
                    <input type="file" id="tutorFileUpload" style="display: none;"
                        accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.jpg,.jpeg,.png,.zip"
                        onchange="handleTutorFileUpload(this)">
                </div>
                <div class="card-body">
                    <!-- File Filters -->
                    <div class="file-filters" style="display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap;">
                        <div style="flex: 1; min-width: 200px; position: relative;">
                            <span
                                style="position: absolute; left: 15px; top: 50%; transform: translateY(-50%); opacity: 0.5;">🔍</span>
                            <input type="text" id="tutorFileSearch" class="form-control" placeholder="Cari nama fail..."
                                style="height: 44px; padding-left: 45px; border-radius: 12px; background: #f8fafc; border: 1px solid #e2e8f0; font-size: 0.9rem;"
                                onkeyup="filterTutorFiles()">
                        </div>
                        <select id="tutorFileTypeFilter" class="form-control"
                            style="width: auto; height: 44px; border-radius: 12px; background: #f8fafc; border: 1px solid #e2e8f0; padding: 0 15px; font-size: 0.9rem; cursor: pointer;"
                            onchange="filterTutorFiles()">
                            <option value="">Semua Jenis</option>
                            <option value="pdf">📕 PDF</option>
                            <option value="doc,docx">📘 Word</option>
                            <option value="xls,xlsx">📗 Excel</option>
                            <option value="ppt,pptx">📙 PowerPoint</option>
                            <option value="jpg,jpeg,png">🖼️ Imej</option>
                            <option value="zip">📦 ZIP</option>
                        </select>
                    </div>

                    <div id="tutorFileList" class="file-list">
                        <p class="text-center text-muted py-4">Memuatkan fail...</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Section 2: Chat Room -->
        <div class="tutor-section chat-room">
            <div class="card h-100" style="display: flex; flex-direction: column;">
                <div class="card-header">
                    <h3 class="card-title">💬 Ruang Sembang</h3>
                </div>
                <div class="card-body chat-messages-container" id="tutorChatMessages">
                    <p class="text-center text-muted py-4">Memuatkan sembang...</p>
                </div>
                <div class="card-footer" style="padding: 15px; border-top: 1px solid #eee;">
                    <form onsubmit="sendTutorChatMessage(event)" class="chat-input-row"
                        style="display: flex; gap: 10px; align-items: center;">
                        <input type="text" id="tutorChatInput" class="form-control" placeholder="Tulis mesej..."
                            style="height: 44px; flex: 1; border-radius: 22px; padding: 0 20px;" autocomplete="off">
                        <button type="submit" class="btn btn-primary"
                            style="width: 44px; height: 44px; border-radius: 50%; padding: 0; display: flex; align-items: center; justify-content: center;">
                            <span>➡️</span>
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    /* Bilik Tutor Styling */
    .bilik-tutor-container {
        animation: fadeIn 0.5s ease;
    }

    .tutor-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 25px;
        height: calc(100vh - 350px);
        min-height: 500px;
    }

    .tutor-section {
        min-width: 0;
        /* Help with flex/grid overflow */
    }

    .file-list {
        display: flex;
        flex-direction: column;
        gap: 12px;
        max-height: 100%;
        overflow-y: auto;
        padding-right: 5px;
    }

    .file-item {
        display: flex;
        align-items: center;
        padding: 12px 15px;
        background: #f8fafc;
        border-radius: 12px;
        border: 1px solid #edf2f7;
        transition: all 0.2s ease;
    }

    .file-item:hover {
        background: #f1f5f9;
        transform: translateY(-2px);
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
    }

    .file-icon {
        font-size: 1.5rem;
        margin-right: 15px;
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: white;
        border-radius: 10px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }

    .file-info {
        flex: 1;
        min-width: 0;
    }

    .file-name {
        font-weight: 600;
        color: #2d3748;
        margin: 0;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: block;
    }

    .file-meta {
        font-size: 0.75rem;
        color: #718096;
    }

    .chat-messages-container {
        flex: 1;
        overflow-y: auto;
        padding: 20px;
        background: #fafafa;
        display: flex;
        flex-direction: column;
        gap: 15px;
    }

    .chat-bubble {
        max-width: 85%;
        padding: 12px 16px;
        border-radius: 18px;
        position: relative;
        font-size: 0.95rem;
        line-height: 1.4;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }

    .chat-bubble.mine {
        align-self: flex-end;
        background: var(--primary-color);
        color: white;
        border-bottom-right-radius: 4px;
    }

    .chat-bubble.others {
        align-self: flex-start;
        background: white;
        color: #333;
        border-bottom-left-radius: 4px;
        border: 1px solid #edf2f7;
    }

    .chat-sender {
        font-size: 0.75rem;
        font-weight: 700;
        margin-bottom: 4px;
        display: block;
    }

    .chat-time {
        font-size: 0.7rem;
        opacity: 0.7;
        margin-top: 4px;
        display: block;
        text-align: right;
    }

    /* Scrollbar styling */
    .chat-messages-container::-webkit-scrollbar,
    .file-list::-webkit-scrollbar {
        width: 6px;
    }

    .chat-messages-container::-webkit-scrollbar-thumb,
    .file-list::-webkit-scrollbar-thumb {
        background: #e2e8f0;
        border-radius: 10px;
    }

    /* Tablet & iPad Pro (Portrait) */
    @media (max-width: 1024px) {
        .tutor-grid {
            grid-template-columns: 1fr;
            height: auto;
        }

        .chat-room {
            height: 500px;
        }
    }

    /* Mobile Devices */
    @media (max-width: 768px) {
        .tutor-grid {
            gap: 15px;
        }

        .card-header {
            padding: 15px;
        }

        .chat-room {
            height: 450px;
        }
    }
</style>

<script>
    let tutorChatInterval;

    /**
     * Main data loader for Tutor Room
     */
    async function loadTutorRoomData() {
        await Promise.all([
            loadTutorFiles(),
            loadTutorChat()
        ]);

        // Set refresh interval for chat (every 5 seconds)
        if (tutorChatInterval) clearInterval(tutorChatInterval);
        tutorChatInterval = setInterval(loadTutorChat, 5000);
    }

    let allTutorFiles = [];

    /**
     * Load shared files
     */
    async function loadTutorFiles() {
        const list = document.getElementById('tutorFileList');
        try {
            const res = await fetch('../api.php?action=get_tutor_files');
            const data = await res.json();

            if (data.success) {
                allTutorFiles = data.files || [];
                document.getElementById('tutorFileCount').textContent = allTutorFiles.length;
                displayTutorFiles(allTutorFiles);
            }
        } catch (e) {
            console.error("Load Files Error:", e);
        }
    }

    /**
     * Display files in the list
     */
    function displayTutorFiles(files) {
        const list = document.getElementById('tutorFileList');

        if (files.length === 0) {
            list.innerHTML = `<div class="text-center py-5 text-muted">
                <span style="font-size: 3rem; display: block;">📂</span>
                <p>Tiada fail dijumpai.</p>
            </div>`;
            return;
        }

        let html = '';
        files.forEach(f => {
            const icon = getFileEmoji(f.file_type);
            html += `
                <div class="file-item animate__animated animate__fadeIn">
                    <div class="file-icon">${icon}</div>
                    <div class="file-info">
                        <span class="file-name" title="${f.file_name}">${f.file_name}</span>
                        <div class="file-meta">Oleh ${f.teacher_name} • ${new Date(f.created_at).toLocaleDateString('ms-MY')}</div>
                    </div>
                    <a href="../${f.file_path}" download class="btn btn-secondary btn-sm" style="width: 44px; height: 44px; display: flex; align-items: center; justify-content: center; border-radius: 50%;">
                        <span>⬇️</span>
                    </a>
                </div>
            `;
        });
        list.innerHTML = html;
    }

    /**
     * Filter files based on search and type
     */
    function filterTutorFiles() {
        const searchTerm = document.getElementById('tutorFileSearch').value.toLowerCase();
        const typeFilter = document.getElementById('tutorFileTypeFilter').value;
        const allowedTypes = typeFilter ? typeFilter.split(',') : [];

        const filtered = allTutorFiles.filter(f => {
            const matchSearch = f.file_name.toLowerCase().includes(searchTerm);
            const matchType = allowedTypes.length === 0 || allowedTypes.includes(f.file_type.toLowerCase());
            return matchSearch && matchType;
        });

        displayTutorFiles(filtered);
    }

    /**
     * Handle new file upload
     */
    async function handleTutorFileUpload(input) {
        if (!input.files || input.files.length === 0) return;

        const file = input.files[0];
        const formData = new FormData();
        formData.append('action', 'upload_tutor_file');
        formData.append('file', file);

        // Show loading state
        Swal.fire({
            title: 'Memuat naik...',
            didOpen: () => { Swal.showLoading(); },
            allowOutsideClick: false
        });

        try {
            const res = await fetch('../api.php', { method: 'POST', body: formData });
            const data = await res.json();

            if (data.success) {
                Swal.fire('Berjaya!', 'Fail telah dikongsi.', 'success');
                loadTutorFiles();
            } else {
                Swal.fire('Gagal!', data.message || 'Ralat berlaku.', 'error');
            }
        } catch (e) {
            Swal.fire('Ralat!', 'Masalah sambungan server.', 'error');
        }
        input.value = ''; // Reset input
    }

    /**
     * Load chat messages
     */
    async function loadTutorChat() {
        const container = document.getElementById('tutorChatMessages');
        const isAtBottom = container.scrollHeight - container.scrollTop <= container.clientHeight + 100;

        try {
            const res = await fetch('../api.php?action=get_tutor_messages');
            const data = await res.json();

            if (data.success) {
                if (data.messages.length === 0) {
                    container.innerHTML = `<div class="text-center py-5 text-muted">Mula bersembang dengan rakan guru yang lain!</div>`;
                    return;
                }

                // Simple diff check to prevent unnecessary re-rendering and flickering
                const currentHtml = container.innerHTML;
                let html = '';
                data.messages.forEach(m => {
                    const isMine = m.teacher_id == <?php echo $_SESSION['user_id']; ?>;
                    const time = new Date(m.created_at).toLocaleTimeString('ms-MY', { hour: '2-digit', minute: '2-digit' });

                    html += `
                    <div class="chat-bubble ${isMine ? 'mine' : 'others'}">
                        ${!isMine ? `<span class="chat-sender">${m.profile_emoji} ${m.teacher_name}</span>` : ''}
                        <div>${m.message}</div>
                        <span class="chat-time">${time}</span>
                    </div>
                `;
                });

                if (html !== container.dataset.lastHtml) {
                    container.innerHTML = html;
                    container.dataset.lastHtml = html;
                    if (isAtBottom) {
                        container.scrollTop = container.scrollHeight;
                    }
                }
            }
        } catch (e) {
            console.error("Chat Error:", e);
        }
    }

    /**
     * Send chat message
     */
    async function sendTutorChatMessage(e) {
        e.preventDefault();
        const input = document.getElementById('tutorChatInput');
        const msg = input.value.trim();
        if (!msg) return;

        input.value = '';
        const formData = new FormData();
        formData.append('action', 'send_tutor_message');
        formData.append('message', msg);

        try {
            const res = await fetch('../api.php', { method: 'POST', body: formData });
            const data = await res.json();
            if (data.success) {
                loadTutorChat();
            }
        } catch (e) {
            console.error("Send Msg Error:", e);
        }
    }

    /**
     * Helper to get emoji by file type
     */
    function getFileEmoji(ext) {
        const map = {
            'pdf': '📕',
            'docx': '📘',
            'doc': '📘',
            'xls': '📗',
            'xlsx': '📗',
            'ppt': '📙',
            'pptx': '📙',
            'jpg': '🖼️',
            'jpeg': '🖼️',
            'png': '🖼️',
            'zip': '📦'
        };
        return map[ext.toLowerCase()] || '📄';
    }

    // Clear interval when switching tabs (handled by teacher/index.php switchTab calling this)
    // But for safety, we could use a MutationObserver or similar if needed.
</script>