<?php
// Modules Tab Component
// Located at: components/teacher/tab-modules.php
?>
<div id="modules" class="tab-content">
    <!-- Modules Info Card -->
    <div class="card" style="margin-bottom: 25px;">
        <div class="card-body">
            <div class="info-card-badge"
                style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 20px;">
                <div>
                    <h4 style="margin: 0 0 5px 0; color: var(--primary-color);">📚 Modul
                        Pembelajaran</h4>
                    <p style="margin: 0; color: #666; font-size: 0.9rem;">Cipta dan urus
                        nota pembelajaran,
                        bahan-bahan mengajar, dan pautan untuk pelajar anda.</p>
                </div>
                <div style="display: flex; gap: 10px;">
                    <span class="badge badge-info" style="padding: 8px 15px; font-size: 0.9rem;">📖 Subjek
                        Diajar:
                        <?php echo isset($subjectsDisplay) ? htmlspecialchars($subjectsDisplay) : count($teacherSubjects); ?></span>
                </div>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <h3 class="card-title">📚 Modul Pembelajaran</h3>
            <div style="display: flex; gap: 10px; align-items: center;">
                <select class="form-control form-select" id="moduleSubjectFilter" onchange="filterModulesBySubjectV3()"
                    style="width: auto;">
                    <option value="all">Semua Subjek</option>
                    <?php foreach ($teacherSubjects as $subject): ?>
                        <option value="<?php echo htmlspecialchars($subject); ?>">
                            <?php echo htmlspecialchars($subject); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <button class="btn btn-primary btn-sm" onclick="showAddModuleModalV3()">
                    <span>➕</span> Tambah Modul
                </button>
            </div>
        </div>
        <div class="card-body">
            <div id="modulesBySubject" style="display: flex; flex-direction: column; gap: 30px;">
                <p class="text-center text-muted">Memuatkan modul...</p>
            </div>
        </div>
    </div>


</div>

<!-- MODULE MODALS -->
<div class="modal-overlay" id="moduleModal">
    <div class="modal" style="max-width: 750px;">
        <div class="modal-header">
            <h3 class="modal-title">📚 Tambah Modul Baru</h3>
            <button class="modal-close" onclick="closeModal('moduleModal')">×</button>
        </div>
        <div class="modal-body">
            <form id="moduleForm" onsubmit="saveModuleV3(event)">
                <input type="hidden" name="id" id="moduleId">

                <div class="form-group">
                    <label class="form-label">Tajuk Modul <span class="required">*</span></label>
                    <input type="text" class="form-control" name="title" id="moduleTitle" required
                        placeholder="cth: Modul Matematik - Pecahan">
                </div>

                <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                    <div class="form-group">
                        <label class="form-label">Subjek <span class="required">*</span></label>
                        <select class="form-control form-select" name="subject" id="moduleSubject" required
                            onchange="loadStudentsV2ForSelection('module')">
                            <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 class="form-group">
                        <label class="form-label">Akses Modul</label>
                        <select class="form-control form-select" id="moduleAccessType"
                            onchange="toggleStudentSelection('module')">
                            <option value="all">Semua Pelajar</option>
                            <option value="specific">Pelajar Tertentu</option>
                        </select>
                    </div>
                </div>

                <!-- Student Selection Section -->
                <div id="moduleStudentSelection"
                    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="selectAllStudents('module')">Pilih Semua</button>
                            <button type="button" class="btn btn-sm btn-secondary"
                                onclick="deselectAllStudents('module')">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="moduleStudentList">
                        <p class="text-muted text-center">Sila pilih subjek terlebih dahulu</p>
                    </div>
                </div>

                <div class="form-group" style="margin-top: 15px;">
                    <label class="form-label">Penerangan</label>
                    <textarea class="form-control" name="description" id="moduleDescription" rows="3"
                        placeholder="Penerangan ringkas..."></textarea>
                </div>

                <div class="form-group">
                    <label class="form-label">Kandungan/Nota</label>
                    <textarea class="form-control" name="content" id="moduleContent" rows="5"
                        placeholder="Kandungan modul..."></textarea>
                </div>

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

<div class="modal-overlay" id="moduleDetailModal">
    <div class="modal" style="max-width: 600px;">
        <div class="modal-header">
            <h3 class="modal-title">📚 Maklumat Modul</h3>
            <button class="modal-close" onclick="closeModal('moduleDetailModal')">×</button>
        </div>
        <div class="modal-body">
            <h4 id="moduleDetailTitle" style="margin-bottom: 10px;">-</h4>
            <span id="moduleDetailSubject" class="badge badge-primary" style="margin-bottom: 15px;">-</span>

            <div class="form-group">
                <label class="form-label">Penerangan</label>
                <p id="moduleDetailDescription" style="background: #f8f9fa; padding: 10px; border-radius: 8px;">-
                </p>
            </div>

            <div class="form-group">
                <label class="form-label">Kandungan/Nota</label>
                <div id="moduleDetailContent"
                    style="background: #f8f9fa; padding: 15px; border-radius: 8px; max-height: 200px; overflow-y: auto; white-space: pre-wrap;">
                    -</div>
            </div>

            <div class="form-group">
                <label class="form-label">Pautan</label>
                <div id="moduleDetailLinks"></div>
            </div>

            <div style="margin-top: 20px;">
                <button type="button" class="btn btn-secondary" style="width: 100%;"
                    onclick="closeModal('moduleDetailModal')">Tutup</button>
            </div>
        </div>
    </div>
</div>

<script>
    // Modules Logic V3

    function loadModulesV3() {
        console.log('Loading Modules V3...');
        fetch(API_PATH + '?action=get_teacher_modules')
            .then(function (response) { return response.json(); })
            .then(function (result) {
                var container = document.getElementById('modulesBySubject');
                if (result.success && result.modules && result.modules.length > 0) {
                    // Group modules by subject
                    var modulesBySubject = {};
                    result.modules.forEach(function (module) {
                        var subject = module.subject || 'Lain-lain';
                        if (!modulesBySubject[subject]) {
                            modulesBySubject[subject] = [];
                        }
                        modulesBySubject[subject].push(module);
                    });

                    var html = '';
                    Object.keys(modulesBySubject).sort().forEach(function (subject) {
                        html += '<div><h4 style="color: var(--primary-color); margin-bottom: 15px;">📚 ' + subject + '</h4>';
                        html += '<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 15px;">';

                        modulesBySubject[subject].forEach(function (module) {
                            var links = JSON.parse(module.links || '[]');
                            html += '<div class="card"><div class="card-body">';
                            html += '<div style="display: flex; justify-content: space-between; align-items: start;">';
                            html += '<h5 style="margin: 0 0 10px 0;">' + module.title + '</h5>';
                            html += '<span class="badge badge-info">' + subject + '</span></div>';
                            html += '<p class="text-muted" style="margin-bottom: 10px;">' + (module.description || '') + '</p>';
                            html += '<div style="font-size: 0.9rem;">';
                            html += '<span>📎 ' + links.length + ' pautan</span>';
                            html += '<span style="margin-left: 15px;">📅 ' + formatDate(module.created_at) + '</span></div>';
                            html += '<div style="margin-top: 15px; display: flex; gap: 10px;">';
                            html += '<button class="btn btn-secondary btn-sm" onclick="viewModuleDetailsV3(' + module.id + ')">👁️</button>';
                            html += '<button class="btn btn-danger btn-sm" onclick="deleteModuleV3(' + module.id + ')">🗑️</button>';
                            html += '</div></div></div>';
                        });

                        html += '</div></div>';
                    });
                    container.innerHTML = html;
                } else {
                    container.innerHTML = '<div style="text-align: center;"><p class="text-muted">Tiada modul dicipta</p><button class="btn btn-primary" onclick="showAddModuleModalV3()">Tambah Modul Pertama</button></div>';
                }
            })
            .catch(function (err) {
                console.error('Error loading modules:', err);
            });
    }

    function filterModulesBySubjectV3() {
        // Implement client side filtering if needed, or just reload for now as per V2
        loadModulesV3();
    }

    function showAddModuleModalV3() {
        openModal('moduleModal');
        var moduleForm = document.getElementById('moduleForm');
        var moduleId = document.getElementById('moduleId');
        if (moduleForm) moduleForm.reset();
        if (moduleId) moduleId.value = '';
    }

    function viewModuleDetailsV3(moduleId) {
        fetch(API_PATH + '?action=get_teacher_modules')
            .then(function (response) { return response.json(); })
            .then(function (result) {
                if (result.success && result.modules) {
                    var module = result.modules.find(function (m) { return parseInt(m.id) === parseInt(moduleId); });
                    if (module) {
                        var links = JSON.parse(module.links || '[]');
                        document.getElementById('moduleDetailTitle').textContent = module.title;
                        document.getElementById('moduleDetailSubject').textContent = module.subject;
                        document.getElementById('moduleDetailDescription').textContent = module.description || 'Tiada penerangan';
                        document.getElementById('moduleDetailContent').textContent = module.content || 'Tiada kandungan';

                        var linksHtml = '';
                        if (links.length > 0) {
                            links.forEach(function (link) {
                                linksHtml += '<a href="' + link + '" target="_blank" class="btn btn-outline-primary btn-sm" style="margin: 3px;">🔗 ' + link.substring(0, 30) + '...</a>';
                            });
                        } else {
                            linksHtml = '<p class="text-muted">Tiada pautan</p>';
                        }
                        document.getElementById('moduleDetailLinks').innerHTML = linksHtml;
                        openModal('moduleDetailModal');
                    }
                    else {
                        showNotificationV2('Modul tidak dijumpai', 'error');
                    }
                } else {
                    showNotificationV2(result.message || 'Gagal memuatkan modul', 'error');
                }
            })
            .catch(function (error) {
                console.error('Error viewing module:', error);
                showNotificationV2('Ralat sambungan', 'error');
            });
    }

    function saveModuleV3(event) {
        event.preventDefault(); // Define this as it wasn't present in V2 view earlier but implied
        // Logic for saving module
        // Assuming similar logic to saveStudent but for module
        var formData = new FormData(document.getElementById('moduleForm'));
        var id = document.getElementById('moduleId').value;
        formData.append('action', id ? 'update_module' : 'add_module');

        // Handle student selection
        // ... (This logic is usually in backend or handled by specific inputs)

        fetch(API_PATH, { method: 'POST', body: formData })
            .then(res => res.json())
            .then(res => {
                if (res.success) {
                    showNotificationV2('Modul berjaya disimpan', 'success');
                    closeModal('moduleModal');
                    loadModulesV3();
                } else {
                    showNotificationV2(res.message, 'error');
                }
            })
            .catch(e => showNotificationV2('Ralat sambungan', 'error'));
    }

    function deleteModuleV3(id) {
        // Get portal theme color
        const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

        Swal.fire({
            title: 'Padam Modul?',
            text: 'Modul ini akan dipadamkan secara kekal.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: themeColor,
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Padam',
            cancelButtonText: 'Batal',
            borderRadius: '15px',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                var formData = new FormData();
                formData.append('action', 'delete_module');
                formData.append('id', id);

                fetch(API_PATH, { method: 'POST', body: formData })
                    .then(function (response) { return response.json(); })
                    .then(function (res) {
                        if (res.success) {
                            showNotificationV2('Modul berjaya dipadam', 'success');
                            loadModulesV3();
                        } else {
                            showNotificationV2(res.message, 'error');
                        }
                    })
                    .catch(function (err) {
                        showNotificationV2('Ralat sambungan', 'error');
                    });
            }
        });
    }
</script>