<?php
// Forum Tab Component
// Located at: components/teacher/tab-forum.php
?>
<div id="forum" class="tab-content">
    <div class="card"
        style="margin-bottom: 25px; border-radius: 20px; overflow: hidden; border: none; box-shadow: 0 10px 40px rgba(0,0,0,0.05); animation: fadeInDown 0.6s ease-out;">
        <div style="height: 6px; background: linear-gradient(90deg, var(--primary-color) 0%, #764ba2 100%);"></div>
        <div class="card-body" style="padding: 25px;">
            <div style="display: flex; align-items: center; gap: 20px; flex-wrap: wrap;">
                <div
                    style="background: linear-gradient(135deg, var(--primary-color) 0%, #764ba2 100%); width: 60px; height: 60px; border-radius: 16px; display: flex; align-items: center; justify-content: center; font-size: 1.8rem; box-shadow: 0 8px 16px rgba(102, 126, 234, 0.25); color: white;">
                    💬
                </div>
                <div style="flex: 1; min-width: 200px;">
                    <h4 style="margin: 0 0 5px 0; color: #1a1a2e; font-size: 1.4rem; font-weight: 800;">Forum
                        Perbincangan</h4>
                    <p style="margin: 0; color: #6b7280; font-size: 0.95rem; line-height: 1.5;">Ruang interaksi antara
                        guru dan pelajar untuk sesi soal jawab dan perkongsian ilmu secara masa nyata.</p>
                </div>
                <div class="d-none d-md-block">
                    <div
                        style="background: rgba(102, 126, 234, 0.05); padding: 10px 20px; border-radius: 12px; border: 1px dashed rgba(102, 126, 234, 0.3);">
                        <span style="color: var(--primary-color); font-weight: 600; font-size: 0.85rem;">Status: Aktif
                            🟢</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="card"
        style="border-radius: 20px; border: none; box-shadow: 0 10px 40px rgba(0,0,0,0.05); overflow: hidden; animation: fadeInUp 0.6s ease-out 0.2s both;">
        <div class="card-header bg-white"
            style="padding: 20px 25px; border-bottom: 1px solid #f0f0f0; display: flex; justify-content: space-between; align-items: center;">
            <div style="display: flex; align-items: center; gap: 12px;">
                <div
                    style="background: #f0f4ff; width: 35px; height: 35px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: var(--primary-color);">
                    <i class="fas fa-folder-open"></i>
                </div>
                <h3 class="card-title" style="margin: 0; font-size: 1.15rem; font-weight: 700; color: #1a1a2e;">Senarai
                    Topik Perbincangan</h3>
            </div>
            <button class="btn btn-primary btn-sm rounded-pill px-4 py-2 shadow-sm d-flex align-items-center gap-2"
                onclick="showAddForumModalV3()"
                style="background: linear-gradient(135deg, var(--primary-color) 0%, #764ba2 100%); border: none; font-weight: 600; transition: transform 0.2s;">
                <span>➕</span> Topik Baru
            </button>
        </div>
        <div class="card-body" style="padding: 25px;">
            <div id="forumList" style="display: flex; flex-direction: column; gap: 20px;">
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2 text-muted">Memuatkan perbincangan...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- FORUM MODALS -->
<div class="modal-overlay" id="forumModal">
    <div class="modal" style="max-width: 750px;">
        <div class="modal-header">
            <h3 class="modal-title">💬 Tambah Forum</h3>
            <button class="modal-close" onclick="closeModal('forumModal')">×</button>
        </div>
        <div class="modal-body">
            <form id="forumForm" onsubmit="saveForumV3(event)">
                <input type="hidden" name="id" id="forumId">

                <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                    <div class="form-group">
                        <label class="form-label">Tajuk <span class="required">*</span></label>
                        <input type="text" class="form-control" name="title" id="forumTitle" required
                            placeholder="cth: Soalan Matematik">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Subjek <span class="required">*</span></label>
                        <select class="form-control form-select" name="subject" id="forumSubject" required
                            onchange="loadForumStudentList('forum')">
                            <option value="">Pilih Subjek</option>
                            <?php foreach ($teacherSubjects as $subject): ?>
                                <option value="<?php echo htmlspecialchars($subject); ?>">
                                    <?php echo htmlspecialchars($subject); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                    <div class="form-group">
                        <label class="form-label">Sasaran</label>
                        <select class="form-control form-select" name="target_audience" id="forumTarget"
                            onchange="toggleForumStudentSelection('forum')">
                            <option value="all">Semua (Guru & Pelajar)</option>
                            <option value="students">Pelajar Saya Sahaja</option>
                            <option value="teachers">Guru Sahaja</option>
                            <option value="specific">Pelajar Tertentu (Checklist)</option>
                        </select>
                    </div>

                    <!-- Student Selection Section for Forum (Removed intermediate step) -->
                </div>

                <!-- Student Selection Section -->
                <div id="forumStudentSelection"
                    style="display: none; margin-top: 15px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                    <div
                        style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                        <label class="form-label" style="margin: 0;"><strong>Pilih Pelajar:</strong></label>
                        <div>
                            <button type="button" class="btn btn-sm btn-secondary"
                                onclick="selectAllForumStudents('forum')">Pilih Semua</button>
                            <button type="button" class="btn btn-sm btn-secondary"
                                onclick="deselectAllForumStudents('forum')">Batalkan Semua</button>
                        </div>
                    </div>
                    <div style="max-height: 150px; overflow-y: auto; border: 1px solid #ddd; border-radius: 8px; padding: 10px; background: white;"
                        id="forumStudentList">
                        <p class="text-muted text-center">Sila pilih subjek dan sasaran "Pelajar Tertentu" untuk
                            memuatkan senarai pelajar</p>
                    </div>
                </div>

                <div class="form-group" style="margin-top: 15px;">
                    <label class="form-label">Pautan Rujukan (Video/Dokumen)</label>
                    <input type="url" class="form-control" name="link" id="forumLink"
                        placeholder="https://youtube.com/... atau https://docs.google.com/...">
                </div>

                <div class="form-group" style="margin-top: 15px;">
                    <label class="form-label">Lampiran (Imej/PDF)</label>
                    <input type="file" class="form-control" name="attachment" id="forumAttachment"
                        accept="image/jpeg,image/png,application/pdf">
                    <small class="text-muted" style="font-size: 0.8rem;">Pilihan: Muat naik gambar atau document PDF
                        untuk rujukan pelajar.</small>
                </div>

                <div class="form-group">
                    <label class="form-label">Kandungan <span class="required">*</span></label>
                    <textarea class="form-control" name="content" id="forumContent" rows="5" required
                        placeholder="Tulis soalan atau topik..."></textarea>
                </div>

                <div style="margin-top: 20px; display: flex; gap: 10px;">
                    <button type="button" class="btn btn-secondary" style="flex: 1;"
                        onclick="closeModal('forumModal')">Batal</button>
                    <button type="submit" class="btn btn-primary" style="flex: 1;">💾 Simpan Forum</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // Forum Logic V3
    function loadForumV3() {
        console.log('Loading Forum V3...');
        fetch(API_PATH + '?action=get_teacher_forums')
            .then(function (response) { return response.json(); })
            .then(function (result) {
                var container = document.getElementById('forumList');
                if (result.success && result.forums && result.forums.length > 0) {
                    var html = '';
                    // Sort forums: pinned forums first, then by creation date (newest first)
                    result.forums.sort(function(a, b) {
                        if (a.is_pinned === 'Yes' && b.is_pinned !== 'Yes') {
                            return -1;
                        }
                        if (a.is_pinned !== 'Yes' && b.is_pinned === 'Yes') {
                            return 1;
                        }
                        // If both are pinned or both are not, sort by creation date
                        return new Date(b.created_at) - new Date(a.created_at);
                    });
                    result.forums.forEach(function (f) {
                        html += `<div class="card hover-effect" style="border-radius: 16px; border: 1px solid #f0f0f0; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); margin-bottom: 5px; box-shadow: 0 4px 12px rgba(0,0,0,0.03);">`;
                        html += `<div class="card-body" style="padding: 20px;">`;
                        html += `    <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 12px;">`;
                        html += `        <div style="display: flex; align-items: center; gap: 12px;">`;
                        html += `            <div style="width: 45px; height: 45px; background: #f3f4ff; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; color: var(--primary-color);">💬</div>`;
                        html += `            <div>`;
                        html += `                <h4 style="margin: 0; font-size: 1.1rem; color: #1a1a2e; font-weight: 700;">${f.title} ${f.is_pinned === 'Yes' ? '<i class="fas fa-thumbtack text-warning ms-2"></i>' : ''}</h4>`;
                        html += `                <small style="color: #6b7280;">Sertai perbincangan sekarang</small>`;
                        html += `            </div>`;
                        html += `        </div>`;
                        html += `        <span class="badge" style="background: rgba(102, 126, 234, 0.1); color: var(--primary-color); border: 1px solid rgba(102, 126, 234, 0.2); padding: 5px 12px; border-radius: 20px; font-weight: 600; font-size: 0.75rem;">${f.subject}</span>`;
                        html += `    </div>`;
                        html += `    <p style="color: #4b5563; font-size: 0.92rem; line-height: 1.6; margin-bottom: 15px;">${f.content ? (f.content.length > 150 ? f.content.substring(0, 150) + '...' : f.content) : 'Tiada kandungan...'}</p>`;
                        html += `    <div style="display: flex; justify-content: space-between; align-items: center; padding-top: 15px; border-top: 1px dashed #f0f0f0;">`;
                        html += `        <div style="display: flex; align-items: center; gap: 15px;">`;
                        html += `            <small class="text-muted" style="display: flex; align-items: center; gap: 5px;"><i class="far fa-calendar-alt"></i> ${formatDate(f.created_at)}</small>`;
                        html += `            <small class="text-muted" style="display: flex; align-items: center; gap: 5px;"><i class="far fa-comment-dots"></i> Respon: Aktif</small>`;
                        html += `        </div>`;
                        html += `        <div style="display: flex; gap: 10px;">`;
                        html += `            <a href="forum_view.php?id=${f.id}" class="btn btn-outline-primary btn-sm rounded-pill px-4" style="border-color: rgba(102, 126, 234, 0.4); font-weight: 600; color: var(--primary-color);">Buka Forum ➔</a>`;
                        html += `            <button onclick="deleteForumV3(${f.id})" class="btn btn-outline-danger btn-sm rounded-circle" style="width: 32px; height: 32px; display: flex; align-items: center; justify-content: center;"><i class="fas fa-trash-alt"></i></button>`;
                        html += `        </div>`;
                        html += `    </div>`;
                        html += `</div></div>`;
                    });
                    container.innerHTML = html;
                } else {
                    container.innerHTML = '<div style="text-align: center; padding: 30px;"><p class="text-muted">Tiada forum belum dibuat</p><p class="text-muted small">Mulakan perbincangan dengan pelajar anda!</p></div>';
                }
            })
            .catch(function (err) {
                console.error('Error loading forum:', err);
                var container = document.getElementById('forumList');
                if (container) container.innerHTML = '<div class="text-center p-4 text-danger">Gagal memuatkan forum. Sila cuba lagi.</div>';
            });
    }

    function showAddForumModalV3() {
        openModal('forumModal');
        const forumForm = document.getElementById('forumForm');
        const forumId = document.getElementById('forumId');
        if (forumForm) forumForm.reset();
        if (forumId) forumId.value = '';

        // Reset student selection visibility
        const selectionDiv = document.getElementById('forumStudentSelection');
        if (selectionDiv) selectionDiv.style.display = 'none';
    }

    function saveForumV3(event) {
        event.preventDefault();
        var formData = new FormData(document.getElementById('forumForm'));
        var id = document.getElementById('forumId').value;
        formData.append('action', id ? 'update_forum' : 'add_forum');

        // Handle specific students logic
        var targetAudience = document.getElementById('forumTarget').value;
        if (targetAudience === 'specific') {
            // Direct checklist access for 'specific' target
            var selectedStudents = [];
            document.querySelectorAll('#forumStudentList input[type="checkbox"]:checked').forEach(function (cb) {
                selectedStudents.push(cb.value);
            });
            formData.append('selected_students', JSON.stringify(selectedStudents));
        }

        fetch(API_PATH, { method: 'POST', body: formData })
            .then(function (response) { return response.json(); })
            .then(function (result) {
                if (result.success) {
                    showNotificationV2('Forum berjaya disimpan', 'success');
                    closeModal('forumModal');
                    loadForumV3();
                } else {
                    showNotificationV2(result.message, 'error');
                }
            })
            .catch(function (err) {
                showNotificationV2('Ralat sambungan', 'error');
            });
    }

    function deleteForumV3(id) {
        Swal.fire({
            title: 'Adakah anda pasti?',
            text: "Forum ini akan dipadam secara kekal!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Ya, padam!',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                var formData = new FormData();
                formData.append('action', 'delete_forum');
                formData.append('id', id);

                fetch(API_PATH, { method: 'POST', body: formData })
                    .then(function (r) { return r.json(); })
                    .then(function (res) {
                        if (res.success) {
                            showNotificationV2('Forum berjaya dipadam', 'success');
                            loadForumV3();
                        } else {
                            showNotificationV2(res.message, 'error');
                        }
                    })
                    .catch(function (e) {
                        showNotificationV2('Ralat sambungan', 'error');
                    });
            }
        });
    }

    // Simple and reliable student selection logic for forum
    function toggleForumStudentSelection(context) {
        console.log('toggleForumStudentSelection called with context:', context);
        // Get the necessary elements
        var targetSelect = document.getElementById(context + 'Target');
        var container = document.getElementById(context + 'StudentSelection');

        if (!targetSelect || !container) {
            console.error('Required elements not found');
            return;
        }

        // Check if we should show the student list
        var showList = (context === 'forum' && targetSelect.value === 'specific');

        if (showList) {
            container.style.display = 'block';
            loadForumStudentList(context);
        } else {
            container.style.display = 'none';
        }
    }

    function loadForumStudentList(context) {
        console.log('loadForumStudentList called with context:', context);
        var listContainer = document.getElementById(context + 'StudentList');
        var subjectSelect = document.getElementById(context + 'Subject');

        if (!listContainer) {
            console.error('List container not found for context:', context);
            return;
        }

        // Only load if Target is "specific"
        var targetSelect = document.getElementById(context + 'Target');
        if (!targetSelect || targetSelect.value !== 'specific') {
            return;
        }

        var selectedSubject = subjectSelect ? subjectSelect.value : '';

        // Show loading message
        listContainer.innerHTML = '<p class="text-center text-muted"><span class="spinner-border spinner-border-sm"></span> Memuatkan senarai pelajar...</p>';

        var apiUrl = API_PATH + '?action=get_student_management_data';

        var xhr = new XMLHttpRequest();
        xhr.open('GET', apiUrl, true);
        xhr.setRequestHeader('Content-Type', 'application/json');

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    try {
                        var data = JSON.parse(xhr.responseText);
                        if (data.success) {
                            if (data.my_students && data.my_students.length > 0) {
                                // Filter students by subject if selected
                                var studentsToShow = data.my_students;
                                if (selectedSubject) {
                                    studentsToShow = data.my_students.filter(function (s) {
                                        // assigned_subject might be a string or part of required_subjects
                                        return s.assigned_subject === selectedSubject ||
                                            (s.required_subjects && s.required_subjects.includes(selectedSubject));
                                    });
                                }

                                if (studentsToShow.length > 0) {
                                    var html = '';
                                    for (var i = 0; i < studentsToShow.length; i++) {
                                        var student = studentsToShow[i];
                                        html += '<div class="form-check" style="padding: 8px; border-bottom: 1px solid #f0f0f0;">';
                                        html += '<input class="form-check-input" type="checkbox" value="' + student.id + '" id="forum_student_' + student.id + '" style="width: 18px; height: 18px;">';
                                        html += '<label class="form-check-label" for="forum_student_' + student.id + '" style="margin-left: 10px; cursor: pointer;">';
                                        html += '<strong>' + student.full_name + '</strong> <small class="text-muted">(' + (student.grade_level || 'N/A') + ')</small>';
                                        html += '</label>';
                                        html += '</div>';
                                    }
                                    listContainer.innerHTML = html;
                                } else {
                                    listContainer.innerHTML = '<p class="text-center text-muted p-3">Tiada pelajar dijumpai untuk subjek ' + selectedSubject + '.</p>';
                                }
                            } else {
                                listContainer.innerHTML = '<p class="text-center text-muted p-3">Tiada pelajar dijumpai.</p>';
                            }
                        } else {
                            listContainer.innerHTML = '<p class="text-center text-danger p-3">Ralat: ' + (data.message || 'Gagal memuatkan') + '</p>';
                        }
                    } catch (e) {
                        listContainer.innerHTML = '<p class="text-center text-danger p-3">Ralat memproses data.</p>';
                    }
                } else {
                    listContainer.innerHTML = '<p class="text-center text-danger p-3">Ralat pelayan (Status: ' + xhr.status + ').</p>';
                }
            }
        };
        xhr.send();
    }

    function selectAllForumStudents(context) {
        var container = document.getElementById(context + 'StudentList');
        if (container) {
            var checkboxes = container.getElementsByTagName('input');
            for (var i = 0; i < checkboxes.length; i++) {
                if (checkboxes[i].type === 'checkbox') {
                    checkboxes[i].checked = true;
                }
            }
        }
    }

    function deselectAllForumStudents(context) {
        var container = document.getElementById(context + 'StudentList');
        if (container) {
            var checkboxes = container.getElementsByTagName('input');
            for (var i = 0; i < checkboxes.length; i++) {
                if (checkboxes[i].type === 'checkbox') {
                    checkboxes[i].checked = false;
                }
            }
        }
    }

    // Backwards compatibility for other components
    window.loadStudentsV2ForSelection = function (ctx) {
        if (ctx === 'forum') {
            toggleForumStudentSelection(ctx);
        } else if (typeof toggleStudentSelection === 'function') {
            toggleStudentSelection(ctx);
        }
    };

</script>