

<?php $__env->startSection('title', ''); ?>

<?php $__env->startSection('content'); ?>
    <div class="card">
        <div class="card-header bg-success text-white">
            <h5 class="mb-0"><i class="bi bi-journal-bookmark-fill me-1"></i> Daftar Kelas</h5>
            <p class="mb-0 small text-white-50">Manajemen kelas</p>
        </div>
        <div class="card-body">
            <div class="d-flex justify-content-between mb-3">
                <div>
                    <p class="mb-0">Daftar Kelas</p>
                    <?php $activePeriode = \App\Services\PeriodeService::getActive(); ?>
                    <?php if($activePeriode): ?>
                        <small class="text-muted">Tahun Pelajaran: <?php echo e($activePeriode->tahun_pelajaran); ?> &middot; Semester: <?php echo e($activePeriode->semester); ?></small>
                    <?php else: ?>
                        <small class="text-muted">Belum ada periode aktif</small>
                    <?php endif; ?>
                </div>
                <div>
                    <button class="btn btn-primary me-2" data-bs-toggle="modal" data-bs-target="#tambahKelasModal">Tambah Kelas</button>
                    <button class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#tambahPesertaKelasModal">Tambah Peserta</button>
                </div>
            </div>

            <?php if(session('success')): ?>
                <div class="alert alert-success"><?php echo e(session('success')); ?></div>
            <?php endif; ?>
            <?php if(session('error')): ?>
                <div class="alert alert-danger"><?php echo e(session('error')); ?></div>
            <?php endif; ?>

            <div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th style="width:3%">NO</th>
                            <th style="width:30%">Nama Kelas</th>
                            <th style="width:7%">Fase</th>
                            <th style="width:7%">Tingkat</th>
                            <th style="width:7%">Rombel</th>
                            <th style="width:18%">Wali Kelas</th>
                            <th style="width:7%">Jumlah Peserta</th>
                            <th style="width:13%">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $__empty_1 = true; $__currentLoopData = $kelases; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $k): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                            <tr>
                                <td><?php echo e(($kelases->firstItem() ?? 0) + $loop->index); ?></td>
                                <td><?php echo e($k->nama); ?></td>
                                <td><?php echo e($k->fase); ?></td>
                                <td><?php echo e($k->tingkat); ?></td>
                                <td><?php echo e($k->rombel); ?></td>
                                <td><?php echo e(optional($k->walikelas)->name ?? '-'); ?></td>
                                <td class="text-center"><?php echo e($pesertaCounts[$k->id] ?? 0); ?></td>
                                <td class="text-center">
                                    <button class="btn btn-sm btn-primary btn-edit" 
                                        data-id="<?php echo e($k->id); ?>"
                                        data-nama="<?php echo e($k->nama); ?>"
                                        data-fase="<?php echo e($k->fase); ?>"
                                        data-tingkat="<?php echo e($k->tingkat); ?>"
                                        data-rombel="<?php echo e($k->rombel); ?>"
                                        data-walikelas="<?php echo e($k->walikelas_id); ?>"
                                        data-bs-toggle="modal" data-bs-target="#editKelasModal" title="Edit">
                                        <i class="bi bi-pencil" aria-hidden="true"></i>
                                    </button>

                                    <form action="<?php echo e(url('admin/data-umum/kelas/' . $k->id)); ?>" method="POST" class="d-inline" onsubmit="return confirm('Yakin ingin menghapus kelas ini?');">
                                        <?php echo csrf_field(); ?>
                                        <?php echo method_field('DELETE'); ?>
                                        <button class="btn btn-sm btn-danger" title="Hapus">
                                            <i class="bi bi-trash" aria-hidden="true"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                            <tr>
                                <td colspan="7" class="text-center">Belum ada data kelas.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <?php echo $__env->make('admin.data-umum.kelas.create', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
            <?php echo $__env->make('admin.data-umum.kelas.edit', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
            <?php echo $__env->make('admin.data-umum.peserta-didik.create', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
            <?php echo $__env->make('admin.data-umum.kelas.add_peserta', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

            <div class="d-flex justify-content-end mt-3">
                <?php echo e($kelases instanceof \Illuminate\Pagination\LengthAwarePaginator ? $kelases->links() : ''); ?>

            </div>

            <script>
                document.addEventListener('DOMContentLoaded', function () {
                    var editButtons = document.querySelectorAll('.btn-edit');
                    editButtons.forEach(function (btn) {
                        btn.addEventListener('click', function () {
                            var id = this.dataset.id;
                            document.getElementById('edit_nama').value = this.dataset.nama || '';
                            document.getElementById('edit_fase').value = this.dataset.fase || 'A';
                            document.getElementById('edit_tingkat').value = this.dataset.tingkat || '1';
                            document.getElementById('edit_rombel').value = this.dataset.rombel || '';
                            // update edit nama based on tingkat+rombel
                            (function fillEditNama(){
                                var t = document.getElementById('edit_tingkat').value || '';
                                var r = document.getElementById('edit_rombel').value || '';
                                if(t && r) {
                                    document.getElementById('edit_nama').value = 'Kelas ' + t + r;
                                }
                            })();
                            document.getElementById('edit_walikelas_id').value = this.dataset.walikelas || '';
                            var form = document.getElementById('editKelasForm');
                            form.action = '/admin/data-umum/kelas/' + id;
                        });
                    });

                    // auto-fill for create modal
                    var createTingkat = document.getElementById('create_tingkat');
                    var createRombel = document.getElementById('create_rombel');
                    var createNama = document.getElementById('create_nama');
                    function fillCreateNama(){
                        var t = createTingkat ? createTingkat.value : '';
                        var r = createRombel ? createRombel.value : '';
                        if(t && r) {
                            createNama.value = 'Kelas ' + t + r;
                        } else if (createNama) {
                            createNama.value = '';
                        }
                    }
                    if(createTingkat) createTingkat.addEventListener('change', fillCreateNama);
                    if(createRombel) createRombel.addEventListener('change', fillCreateNama);
                    // clear create modal inputs when opening
                    var tambahModalEl = document.getElementById('tambahKelasModal');
                    if (tambahModalEl) {
                        tambahModalEl.addEventListener('show.bs.modal', function () {
                            if(createNama) createNama.value = '';
                            if(createTingkat) createTingkat.value = '';
                            if(createRombel) createRombel.value = '';
                            if(document.getElementById('create_fase')) document.getElementById('create_fase').value = '';
                        });
                    }

                    // auto-fill for edit modal on change
                    var editTingkat = document.getElementById('edit_tingkat');
                    var editRombel = document.getElementById('edit_rombel');
                    var editNama = document.getElementById('edit_nama');
                    function fillEditFromSelects(){
                        var t = editTingkat ? editTingkat.value : '';
                        var r = editRombel ? editRombel.value : '';
                        if(t && r) {
                            editNama.value = 'Kelas ' + t + r;
                        } else if (editNama) {
                            editNama.value = '';
                        }
                    }
                    if(editTingkat) editTingkat.addEventListener('change', fillEditFromSelects);
                    if(editRombel) editRombel.addEventListener('change', fillEditFromSelects);
                });
                // Assignment modal behavior
                (function(){
                    var faseSel = document.getElementById('assign_fase');
                    var tingkatSel = document.getElementById('assign_tingkat');
                    var kelasSel = document.getElementById('assign_kelas');
                    var walikelasInput = document.getElementById('assign_walikelas');
                    var tingkatAwalSel = document.getElementById('assign_tingkat_awal');
                    var pesertaList = document.getElementById('assign_peserta_list');

                    // map kelases into JS array for filtering
                    var kelasOptions = Array.from(kelasSel.querySelectorAll('option')).slice(1).map(function(opt){
                        return {
                            id: opt.value,
                            nama: opt.textContent,
                            fase: opt.dataset.fase,
                            tingkat: opt.dataset.tingkat,
                            rombel: opt.dataset.rombel,
                            walikelas: opt.dataset.walikelas
                        };
                    });

                    function setTingkatOptionsForFase(f){
                        tingkatSel.innerHTML = '<option value="">-- Pilih Tingkat --</option>';
                        var ranges = {A: ['1','2'], B: ['3','4'], C: ['5','6']};
                        var vals = ranges[f] || [];
                        vals.forEach(function(v){
                            var o = document.createElement('option'); o.value = v; o.textContent = v; tingkatSel.appendChild(o);
                        });
                    }

                    // when fase changes, set tingkat options
                    if(faseSel) faseSel.addEventListener('change', function(){ setTingkatOptionsForFase(this.value); });

                    // when tingkat changes, filter kelasSel to show matching kelas
                    if(tingkatSel) tingkatSel.addEventListener('change', function(){
                        var t = this.value;
                        // rebuild kelasSel options
                        kelasSel.innerHTML = '<option value="">-- Pilih Nama Kelas --</option>';
                        kelasOptions.filter(function(k){ return (!t || k.tingkat == t) && (!faseSel.value || k.fase == faseSel.value); }).forEach(function(k){
                            var o = document.createElement('option'); o.value = k.id; o.textContent = k.nama; o.dataset.fase = k.fase; o.dataset.tingkat = k.tingkat; o.dataset.rombel = k.rombel; o.dataset.walikelas = k.walikelas; kelasSel.appendChild(o);
                        });
                    });

                    // when kelas selected, set walikelas display
                    if(kelasSel) kelasSel.addEventListener('change', function(){
                        var opt = this.selectedOptions[0];
                        walikelasInput.value = opt ? (opt.dataset.walikelas || '') : '';
                    });

                    // prepare peserta data from server-side variable
                    var pesertaData = <?php echo json_encode($pesertasForKelas, 15, 512) ?>;

                    function populatePesertaListByTingkatAwal(tingkatAwal){
                        pesertaList.innerHTML = '';
                        var targetList = document.getElementById('assign_peserta_kelas');
                        if(targetList) targetList.innerHTML = '';
                        if(!tingkatAwal) return;
                        var matches = (pesertaData || []).filter(function(p){ return (p.tingkat_awal || '') == tingkatAwal; });
                        matches.forEach(function(p){
                            var o = document.createElement('option'); o.value = p.id; o.textContent = (p.nis ? '['+p.nis+'] ' : '') + (p.nama || p.nama_lengkap || ''); pesertaList.appendChild(o);
                        });
                    }

                    if(tingkatAwalSel) tingkatAwalSel.addEventListener('change', function(){ populatePesertaListByTingkatAwal(this.value); });

                    // move buttons between lists
                    function moveSelected(sourceSel, targetSel){
                        var selected = Array.from(sourceSel.selectedOptions);
                        selected.forEach(function(opt){
                            // avoid duplicates
                            if(!Array.from(targetSel.options).some(function(o){ return o.value == opt.value; })){
                                var newOpt = opt.cloneNode(true);
                                targetSel.appendChild(newOpt);
                            }
                            opt.remove();
                        });
                    }

                    var btnToTarget = document.getElementById('moveToTarget');
                    var btnToSource = document.getElementById('moveToSource');
                    var sourceSel = document.getElementById('assign_peserta_list');
                    var targetSel = document.getElementById('assign_peserta_kelas');
                    if(btnToTarget && sourceSel && targetSel) btnToTarget.addEventListener('click', function(){ moveSelected(sourceSel, targetSel); });
                    if(btnToSource && sourceSel && targetSel) btnToSource.addEventListener('click', function(){ moveSelected(targetSel, sourceSel); });

                    // double-click to move an option between lists
                    if(sourceSel && targetSel){
                        sourceSel.addEventListener('dblclick', function(){ moveSelected(sourceSel, targetSel); });
                        targetSel.addEventListener('dblclick', function(){ moveSelected(targetSel, sourceSel); });
                    }

                    // ensure target options are selected before submit
                    var addPesertaForm = document.querySelector('#tambahPesertaKelasModal form');
                    if(addPesertaForm){
                        addPesertaForm.addEventListener('submit', function(){
                            Array.from(targetSel.options).forEach(function(o){ o.selected = true; });
                        });
                    }

                    // clear modal on show
                    var modalEl = document.getElementById('tambahPesertaKelasModal');
                    if(modalEl) modalEl.addEventListener('show.bs.modal', function(){
                        faseSel.value = ''; tingkatSel.innerHTML = '<option value="">-- Pilih Tingkat --</option>'; kelasSel.innerHTML = '<option value="">-- Pilih Nama Kelas --</option>'; walikelasInput.value = ''; tingkatAwalSel.value = ''; pesertaList.innerHTML = '';
                    });
                })();
            </script>
        </div>
    </div>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('admin.layout', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\App\laravel\laravel\resources\views/admin/data-umum/kelas/index.blade.php ENDPATH**/ ?>