<?php
// Modules Tab Component
// Located at: components/teacher/tab-modules.php
?>
<div id="modules" class="tab-content">
    <!-- Modules Info Card -->
    <!-- Modules Info Card -->
    <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;">Modul
                        Pembelajaran
                    </h4>
                    <p style="margin: 0; color: #6b7280; font-size: 0.95rem; line-height: 1.5;">Cipta dan urus nota
                        pembelajaran, bahan-bahan mengajar, dan pautan untuk pelajar anda.</p>
                </div>
                <div style="display: flex; gap: 10px;">
                    <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;">📖 Subjek
                            Diajar:
                            <?php echo isset($subjectsDisplay) ? htmlspecialchars($subjectsDisplay) : count($teacherSubjects); ?></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-book"></i>
                </div>
                <h3 class="card-title" style="margin: 0; font-size: 1.15rem; font-weight: 700; color: #1a1a2e;">Senarai
                    Modul</h3>
            </div>
            <div style="display: flex; gap: 10px; align-items: center;">
                <select class="form-control form-select" id="moduleSubjectFilter" onchange="filterModulesBySubjectV3()"
                    style="width: auto; border-radius: 20px; padding: 5px 15px; border-color: #e2e8f0;">
                    <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 rounded-pill px-4 py-2 shadow-sm d-flex align-items-center gap-2"
                    onclick="showAddModuleModalV3()"
                    style="background: linear-gradient(135deg, var(--primary-color) 0%, #764ba2 100%); border: none; font-weight: 600; transition: transform 0.2s;">
                    <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)" enctype="multipart/form-data">
                <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 (Checklist)</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 class="form-group" style="margin-top: 15px;">
                    <label class="form-label">Pautan & Lampiran</label>

                    <!-- Dynamic Links -->
                    <div id="linkInputsContainer">
                        <div class="input-group mb-2" style="display: flex; gap: 5px; margin-bottom: 5px;">
                            <input type="url" name="links[]" class="form-control" placeholder="https://..."
                                style="flex: 1;">
                        </div>
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-primary mb-3" onclick="addLinkInput()"
                        style="margin-bottom: 15px;">+ Tambah Pautan URL</button>

                    <!-- File Upload -->
                    <div style="border: 1px dashed #ccc; padding: 15px; border-radius: 8px; background: #f9f9f9;">
                        <label class="form-label small" style="margin-bottom: 5px; display: block;">Muat Naik Fail (PDF,
                            Doc, Imej)</label>
                        <input type="file" name="module_attachments[]" class="form-control" multiple>
                        <small class="text-muted" style="display: block; margin-top: 5px;">Anda boleh memilih beberapa
                            fail serentak.</small>
                    </div>
                </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">Akses Kepada</label>
                <p id="moduleDetailAccess" style="background: #f8f9fa; padding: 10px; border-radius: 8px;">-</p>
            </div>

            <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 || '[]');
                            var accessText = module.for_all_students === 'Yes' ? 'Semua Pelajar' : (module.student_names || 'Tiada pelajar dipilih');
                            var displayAccess = accessText;
                            if (displayAccess.length > 50) displayAccess = displayAccess.substring(0, 47) + '...';
                            
                            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: 5px;">' + (module.description || '') + '</p>';
                            html += '<p style="font-size: 0.85rem; color: #64748b; margin-bottom: 10px;" title="' + accessText + '">';
                            html += '<strong>Akses:</strong> ' + displayAccess + '</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 = '';

        // Reset Link Inputs
        var container = document.getElementById('linkInputsContainer');
        if (container) {
            container.innerHTML = `
                <div class="input-group mb-2" style="display: flex; gap: 5px; margin-bottom: 5px;">
                    <input type="url" name="links[]" class="form-control" placeholder="https://..." style="flex: 1;">
                </div>
            `;
        }
    }

    function addLinkInput() {
        var container = document.getElementById('linkInputsContainer');
        var div = document.createElement('div');
        div.className = 'input-group mb-2';
        div.style.cssText = 'display: flex; gap: 5px; margin-bottom: 5px;';
        div.innerHTML = `
            <input type="url" name="links[]" class="form-control" placeholder="https://..." style="flex: 1;">
            <button type="button" class="btn btn-outline-danger" onclick="this.parentElement.remove()" style="border: 1px solid #dc3545; color: #dc3545; background: white; border-radius: 4px; cursor: pointer;">×</button>
        `;
        container.appendChild(div);
    }

    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 || '[]');
                        var accessText = module.for_all_students === 'Yes' ? 'Semua Pelajar' : (module.student_names || 'Tiada pelajar dipilih');
                        document.getElementById('moduleDetailTitle').textContent = module.title;
                        document.getElementById('moduleDetailSubject').textContent = module.subject;
                        document.getElementById('moduleDetailAccess').textContent = accessText;
                        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) {
                                var href = link;
                                // If local file (not http), prepend ../ to go up from teacher/ dir
                                if (!link.match(/^https?:\/\//) && !link.startsWith('../')) {
                                    href = '../' + link;
                                }
                                var displayLink = link.split('/').pop(); // Show filename if local, or truncated url
                                if (link.match(/^https?:\/\//)) displayLink = link.substring(0, 30) + '...';
                                
                                linksHtml += '<a href="' + href + '" target="_blank" class="btn btn-outline-primary btn-sm" style="margin: 3px;">🔗 ' + displayLink + '</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();
        var formData = new FormData(document.getElementById('moduleForm'));
        
        // Debug: Log FormData contents
        console.log('FormData created');
        for (var pair of formData.entries()) {
            console.log(pair[0] + ': ', pair[1]);
        }
        
        // Debug: Check file inputs
        var fileInputs = document.querySelectorAll('input[type="file"]');
        fileInputs.forEach(function(input, index) {
            console.log('File input ' + index + ' files:', input.files);
            if (input.files && input.files.length > 0) {
                for (var i = 0; i < input.files.length; i++) {
                    console.log('File ' + i + ': ' + input.files[i].name + ' (' + input.files[i].size + ' bytes)');
                }
            }
        });
        
        var id = document.getElementById('moduleId').value;
        formData.append('action', id ? 'update_module' : 'add_module');

        var accessType = document.getElementById('moduleAccessType').value;
        formData.append('for_all_students', accessType === 'all' ? 'Yes' : 'No');
        if (accessType === 'specific') {
            document.querySelectorAll('#moduleStudentList input[type="checkbox"]:checked').forEach(function (cb) {
                formData.append('module_students[]', cb.value);
            });
        }

        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>
