<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="card">
    <div class="card-header">
        <div class="d-flex align-items-center gap-2">
            <i class="bi bi-person-workspace text-primary"></i>
            <span class="fw-semibold">Setting Mengajar (Guru Mapel)</span>
        </div>
        <div class="text-muted small mt-1">
            Periode Aktif: <strong><?= esc($activePeriod['semester']) ?> - <?= esc($activePeriod['year_name']) ?></strong>
        </div>
    </div>
    <div class="card-body">
        <?php if (session()->getFlashdata('success')): ?>
        <div class="alert alert-success alert-dismissible fade show py-2 small" role="alert">
            <i class="bi bi-check-circle me-1"></i><?= session()->getFlashdata('success') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show py-2 small" role="alert">
            <i class="bi bi-exclamation-circle me-1"></i><?= session()->getFlashdata('error') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label">Pilih Tingkat</label>
                    <select id="grade_id" class="form-select">
                        <option value="">-- Pilih Tingkat --</option>
                        <?php foreach ($grades as $g): ?>
                        <option value="<?= $g['id'] ?>"><?= esc($g['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label">Pilih Kelas</label>
                    <select id="classroom_id" class="form-select" disabled>
                        <option value="">-- Pilih Tingkat Dulu --</option>
                    </select>
                </div>
            </div>
        </div>

        <div id="assignmentPanel" style="display: none;">
            <hr>
            <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
                <h6 class="mb-0">
                    <i class="bi bi-table me-2 text-primary"></i>
                    Setting Guru Mapel - <span id="className"></span>
                </h6>
                <div class="d-flex gap-2">
                    <button type="button" id="btnSyncAsc" class="btn btn-success btn-sm">
                        <i class="bi bi-arrow-repeat me-1"></i>Sync aSc
                    </button>
                    <button type="button" id="btnSyncLocal" class="btn btn-warning btn-sm text-dark">
                        <i class="bi bi-cpu-fill me-1"></i>Sync Jadwal Otomatis
                    </button>
                    <button type="button" id="btnSyncManual" class="btn btn-info btn-sm text-dark">
                        <i class="bi bi-pencil-square me-1"></i>Sync Jadwal Manual
                    </button>
                    <button type="button" id="btnUnsyncAsc" class="btn btn-outline-danger btn-sm">
                        <i class="bi bi-x-circle me-1"></i>Batal Sync
                    </button>
                    <button type="button" id="btnSaveAll" class="btn btn-primary btn-sm">
                        <i class="bi bi-save me-1"></i>Simpan Semua
                    </button>
                </div>
            </div>
            
            <div class="table-responsive">
                <table class="table table-sm table-bordered" id="assignmentTable">
                    <thead class="table-light">
                        <tr>
                            <th width="40">#</th>
                            <th>Mata Pelajaran</th>
                            <th width="250">Guru Pengajar</th>
                        </tr>
                    </thead>
                    <tbody id="assignmentBody">
                        <tr><td colspan="3" class="text-center text-muted py-5">
                            <i class="bi bi-inbox fs-2 d-block mb-2 opacity-25"></i>
                            <small>Pilih kelas terlebih dahulu</small>
                        </td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<script>
$(document).ready(function() {
    let currentClassroomId = null;
    let currentPeriodId = '<?= $activePeriod['id'] ?>';
    
    // Load kelas berdasarkan tingkat
    $('#grade_id').change(function() {
        const gradeId = $(this).val();
        const classroomSelect = $('#classroom_id');
        
        if (!gradeId) {
            classroomSelect.prop('disabled', true).html('<option value="">-- Pilih Tingkat Dulu --</option>');
            $('#assignmentPanel').hide();
            return;
        }
        
        $.ajax({
            url: '/teaching-assignment/get-classrooms',
            method: 'GET',
            data: { grade_id: gradeId },
            dataType: 'json',
            success: function(data) {
                classroomSelect.prop('disabled', false);
                let options = '<option value="">-- Pilih Kelas --</option>';
                $.each(data, function(i, cls) {
                    options += `<option value="${cls.id}">${cls.name}</option>`;
                });
                classroomSelect.html(options);
                classroomSelect.val('');
                $('#assignmentPanel').hide();
            }
        });
    });
    
    // Load mapel dan assignment saat kelas dipilih
    $('#classroom_id').change(function() {
        const classroomId = $(this).val();
        const className = $(this).find('option:selected').text();
        
        if (!classroomId) {
            $('#assignmentPanel').hide();
            return;
        }
        
        currentClassroomId = classroomId;
        $('#className').text(className);
        $('#assignmentPanel').show();
        $('#assignmentBody').html('<tr><td colspan="3" class="text-center py-3"><div class="spinner-border spinner-border-sm text-primary"></div> Memuat data...</td></tr>');
        
        $.ajax({
            url: '/teaching-assignment/get-subjects',
            method: 'GET',
            data: {
                classroom_id: classroomId,
                period_id: currentPeriodId
            },
            dataType: 'json',
            success: function(data) {
                if (data.subjects && data.subjects.length > 0) {
                    renderSimpleTable(data.subjects, data.assignments, data.teachers);
                } else {
                    $('#assignmentBody').html('<tr><td colspan="3" class="text-center text-muted py-5">Belum ada mapel. Silakan atur di menu Setting Mapel Sekolah terlebih dahulu.</td></tr>');
                }
            },
            error: function() {
                $('#assignmentBody').html('<tr><td colspan="3" class="text-center text-danger py-3">Gagal memuat数据</td></tr>');
            }
        });
    });
    
    function renderSimpleTable(subjects, assignments, teachers) {
        let html = '';
        let no = 1;
        
        $.each(subjects, function(i, subject) {
            const selectedTeacher = assignments[subject.id] || '';
            
            html += `
                <tr>
                    <td class="text-center align-middle">${no++}</td>
                    <td class="align-middle">
                        <strong>${escapeHtml(subject.name)}</strong>
                    </td>
                    <td class="align-middle">
                        <select class="form-select form-select-sm teacher-select" 
                            data-subject-id="${subject.id}"
                            style="width: 100%;">
                            <option value="">-- Pilih Guru --</option>
            `;
            
            $.each(teachers, function(j, teacher) {
                const selected = (selectedTeacher == teacher.id) ? 'selected' : '';
                html += `<option value="${teacher.id}" ${selected}>${escapeHtml(teacher.name)}</option>`;
            });
            
            html += `
                        </select>
                    </td>
                </tr>
            `;
        });
        
        $('#assignmentBody').html(html);
        
        $('.teacher-select').select2({
            placeholder: "-- Pilih Guru --",
            allowClear: true,
            width: '100%'
        });
    }
    
    // Sync dari aSc
    $('#btnSyncAsc').click(function() {
        if (!currentClassroomId) return;
        
        const btn = $(this);
        const originalText = btn.html();
        btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span> Loading...');
        
        $.ajax({
            url: '/teaching-assignment/sync-from-asc',
            method: 'GET',
            data: {
                classroom_id: currentClassroomId,
                period_id: currentPeriodId
            },
            dataType: 'json',
            success: function(data) {
                btn.prop('disabled', false).html(originalText);
                if (data.success) {
                    // Reset dulu agar bersih, lalu update dropdowns berdasarkan mappings yang dikembalikan
                    $('.teacher-select').val('').trigger('change');
                    
                    let count = 0;
                    $.each(data.mappings, function(subjectId, teacherId) {
                        const selectEl = $(`.teacher-select[data-subject-id="${subjectId}"]`);
                        if (selectEl.length > 0) {
                            selectEl.val(teacherId).trigger('change');
                            count++;
                        }
                    });
                    
                    if (count > 0) {
                        showToast(`Berhasil mencocokkan ${count} mata pelajaran dari jadwal aSc. Klik 'Simpan Semua' untuk menyimpan.`, 'success');
                    } else {
                        showToast('Tidak ada mata pelajaran di kelas ini yang terpetakan dengan jadwal aSc.', 'warning');
                    }
                } else {
                    showToast(data.message || 'Gagal memuat jadwal aSc.', 'danger');
                }
            },
            error: function() {
                btn.prop('disabled', false).html(originalText);
                showToast('Terjadi kesalahan saat menghubungi server.', 'danger');
            }
        });
    });

    // Sync dari Jadwal Otomatis (Local Generator)
    $('#btnSyncLocal').click(function() {
        if (!currentClassroomId) return;
        
        const btn = $(this);
        const originalText = btn.html();
        btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span> Loading...');
        
        $.ajax({
            url: '/teaching-assignment/sync-from-local',
            method: 'GET',
            data: {
                classroom_id: currentClassroomId,
                period_id: currentPeriodId
            },
            dataType: 'json',
            success: function(data) {
                btn.prop('disabled', false).html(originalText);
                if (data.success) {
                    // Reset dulu agar bersih, lalu update dropdowns berdasarkan mappings yang dikembalikan
                    $('.teacher-select').val('').trigger('change');
                    
                    let count = 0;
                    $.each(data.mappings, function(subjectId, teacherId) {
                        const selectEl = $(`.teacher-select[data-subject-id="${subjectId}"]`);
                        if (selectEl.length > 0) {
                            selectEl.val(teacherId).trigger('change');
                            count++;
                        }
                    });
                    
                    if (count > 0) {
                        showToast(`Berhasil mencocokkan ${count} mata pelajaran dari Jadwal Otomatis. Klik 'Simpan Semua' untuk menyimpan.`, 'success');
                    } else {
                        showToast('Tidak ada beban mengajar di kelas ini yang terpetakan dengan Jadwal Otomatis.', 'warning');
                    }
                } else {
                    showToast(data.message || 'Gagal memuat beban Jadwal Otomatis.', 'danger');
                }
            },
            error: function() {
                btn.prop('disabled', false).html(originalText);
                showToast('Terjadi kesalahan saat menghubungi server.', 'danger');
            }
        });
    });
    
    // Sync dari Jadwal Manual
    $('#btnSyncManual').click(function() {
        if (!currentClassroomId) return;
        
        const btn = $(this);
        const originalText = btn.html();
        btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span> Loading...');
        
        $.ajax({
            url: '/teaching-assignment/sync-from-manual',
            method: 'GET',
            data: {
                classroom_id: currentClassroomId,
                period_id: currentPeriodId
            },
            dataType: 'json',
            success: function(data) {
                btn.prop('disabled', false).html(originalText);
                if (data.success) {
                    // Reset dulu agar bersih, lalu update dropdowns berdasarkan mappings yang dikembalikan
                    $('.teacher-select').val('').trigger('change');
                    
                    let count = 0;
                    $.each(data.mappings, function(subjectId, teacherId) {
                        const selectEl = $(`.teacher-select[data-subject-id="${subjectId}"]`);
                        if (selectEl.length > 0) {
                            selectEl.val(teacherId).trigger('change');
                            count++;
                        }
                    });
                    
                    if (count > 0) {
                        showToast(`Berhasil mencocokkan ${count} mata pelajaran dari Jadwal Manual. Klik 'Simpan Semua' untuk menyimpan.`, 'success');
                    } else {
                        showToast('Tidak ada beban mengajar di kelas ini yang terpetakan dengan Jadwal Manual.', 'warning');
                    }
                } else {
                    showToast(data.message || 'Gagal memuat beban Jadwal Manual.', 'danger');
                }
            },
            error: function() {
                btn.prop('disabled', false).html(originalText);
                showToast('Terjadi kesalahan saat menghubungi server.', 'danger');
            }
        });
    });

    // Batal Sync (Kosongkan dropdown)
    $('#btnUnsyncAsc').click(function() {
        if (!currentClassroomId) return;
        
        if (confirm('Apakah Anda yakin ingin mengosongkan semua pilihan guru di kelas ini? (Klik \'Simpan Semua\' setelah ini untuk menyimpan perubahan)')) {
            $('.teacher-select').val('').trigger('change');
            showToast('Semua pilihan guru telah dikosongkan. Klik \'Simpan Semua\' untuk menyimpannya ke database.', 'warning');
        }
    });

    // Simpan semua
    $('#btnSaveAll').click(function() {
        if (!currentClassroomId) return;
        
        const assignments = {};
        $('.teacher-select').each(function() {
            const subjectId = $(this).data('subject-id');
            const teacherId = $(this).val();
            if (teacherId) {
                assignments[subjectId] = teacherId;
            }
        });
        
        const btn = $(this);
        const originalText = btn.html();
        btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span> Menyimpan...');
        
        $.ajax({
            url: '/teaching-assignment/save',
            method: 'POST',
            data: {
                classroom_id: currentClassroomId,
                period_id: currentPeriodId,
                assignments: assignments,
                '<?= csrf_token() ?>': '<?= csrf_hash() ?>'
            },
            dataType: 'json',
            success: function(data) {
                if (data.success) {
                    showToast(data.message, 'success');
                } else {
                    showToast(data.message || 'Gagal menyimpan', 'danger');
                }
                btn.prop('disabled', false).html(originalText);
            },
            error: function() {
                showToast('Terjadi kesalahan', 'danger');
                btn.prop('disabled', false).html(originalText);
            }
        });
    });
});

function showToast(msg, type) {
    const toast = $(`
        <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 9999">
            <div class="toast align-items-center text-white bg-${type} border-0 show" role="alert">
                <div class="d-flex">
                    <div class="toast-body small">${msg}</div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            </div>
        </div>
    `);
    $('body').append(toast);
    setTimeout(() => toast.remove(), 3000);
}

function escapeHtml(str) {
    if (!str) return '';
    return str.replace(/[&<>]/g, function(m) {
        if (m === '&') return '&amp;';
        if (m === '<') return '&lt;';
        if (m === '>') return '&gt;';
        return m;
    });
}
</script>
<?= $this->endSection() ?>