<?php $__env->startPush('modals'); ?>
<div class="modal fade" id="modalTambahNilaiIntrakulikuler" tabindex="-1" aria-labelledby="modalTambahNilaiLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST" action="<?php if(request()->is('guru/*')): ?><?php echo e(route('guru.penilaian.intrakulikuler.store')); ?><?php else: ?><?php echo e(route('admin.penilaian.intrakulikuler.store')); ?><?php endif; ?>">
                <?php echo csrf_field(); ?>
                <div class="modal-header" style="background-color:#f3e6ff;color:#3b0b6f;">
                    <h5 class="modal-title" id="modalTambahNilaiLabel">Tambah Penilaian Intrakulikuler</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Kelas</label>
                            <select id="selectKelas" name="kelas_id" class="form-select">
                                <option value="">-- Pilih Kelas --</option>
                                <?php $__currentLoopData = $kelases ?? []; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $kelas): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($kelas->id); ?>"><?php echo e($kelas->nama ?? $kelas->name); ?></option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Peserta Didik</label>
                            <select id="selectPeserta" name="peserta_didik_id" class="form-select" disabled>
                                <option value="">-- Pilih Kelas terlebih dahulu --</option>
                            </select>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Mata Pelajaran</label>
                            <select id="selectMapel" name="mata_pelajaran_id" class="form-select">
                                <option value="">-- Pilih Mata Pelajaran --</option>
                                <?php $__seenMapel = []; ?>
                                <?php $__currentLoopData = $mapels ?? []; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $mapel): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <?php if(in_array($mapel->id, $__seenMapel)): ?>
                                        <?php continue; ?>
                                    <?php endif; ?>
                                    <?php $__seenMapel[] = $mapel->id; ?>
                                    <option value="<?php echo e($mapel->id); ?>"
                                        data-kelas="<?php echo e($mapel->kelas_id ?? ''); ?>"
                                        data-m1="<?php echo e(filled($mapel->materi1) ? 1 : 0); ?>"
                                        data-m2="<?php echo e(filled($mapel->materi2) ? 1 : 0); ?>"
                                        data-m3="<?php echo e(filled($mapel->materi3) ? 1 : 0); ?>"
                                        data-m4="<?php echo e(filled($mapel->materi4) ? 1 : 0); ?>"
                                        data-m5="<?php echo e(filled($mapel->materi5) ? 1 : 0); ?>"
                                        data-m6="<?php echo e(filled($mapel->materi6) ? 1 : 0); ?>"
                                        data-m1-text="<?php echo e(e($mapel->materi1 ?? '')); ?>"
                                        data-m2-text="<?php echo e(e($mapel->materi2 ?? '')); ?>"
                                        data-m3-text="<?php echo e(e($mapel->materi3 ?? '')); ?>"
                                        data-m4-text="<?php echo e(e($mapel->materi4 ?? '')); ?>"
                                        data-m5-text="<?php echo e(e($mapel->materi5 ?? '')); ?>"
                                        data-m6-text="<?php echo e(e($mapel->materi6 ?? '')); ?>"
                                    ><?php echo e($mapel->nama ?? $mapel->name); ?></option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                        </div>

                        <div class="col-12">
                            <label class="form-label">Nilai 1 - 6</label>
                            <div class="row g-2">
                                <div class="col-4 col-md-2">
                                    <label class="form-label small">Nilai 1</label>
                                    <input type="number" name="nilai1" class="form-control" min="0" max="100">
                                </div>
                                <div class="col-4 col-md-2">
                                    <label class="form-label small">Nilai 2</label>
                                    <input type="number" name="nilai2" class="form-control" min="0" max="100">
                                </div>
                                <div class="col-4 col-md-2">
                                    <label class="form-label small">Nilai 3</label>
                                    <input type="number" name="nilai3" class="form-control" min="0" max="100">
                                </div>
                                <div class="col-4 col-md-2">
                                    <label class="form-label small">Nilai 4</label>
                                    <input type="number" name="nilai4" class="form-control" min="0" max="100">
                                </div>
                                <div class="col-4 col-md-2">
                                    <label class="form-label small">Nilai 5</label>
                                    <input type="number" name="nilai5" class="form-control" min="0" max="100">
                                </div>
                                <div class="col-4 col-md-2">
                                    <label class="form-label small">Nilai 6</label>
                                    <input type="number" name="nilai6" class="form-control" min="0" max="100">
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label">N-Sumatif</label>
                            <input type="number" name="n_sumatif" class="form-control" min="0" max="100">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">N-Akhir Semester</label>
                            <input type="number" name="n_akhir_semester" class="form-control" min="0" max="100">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Nilai Akhir</label>
                            <input type="number" name="nilai_akhir" class="form-control" min="0" max="100" step="0.01">
                        </div>

                        <div class="col-12">
                            <label class="form-label">Deskripsi</label>
                            <textarea name="deskripsi" class="form-control" rows="3"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary">Simpan</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
(function(){
    const kelasSelect = document.getElementById('selectKelas');
    const pesertaSelect = document.getElementById('selectPeserta');
    const mapelSelect = document.getElementById('selectMapel');
    var baseApi = (window.location.pathname.indexOf('/guru/') === 0) ? '/guru/penilaian' : '/admin/penilaian';

    if (!kelasSelect || !pesertaSelect || !mapelSelect) return;

    pesertaSelect.disabled = true;
    // collect unique mapel options by value to avoid duplicates
    const seen = new Set();
    const mapelOptions = Array.from(mapelSelect.querySelectorAll('option')).filter(function(o){
        if (!o.value) return false; // skip placeholder from stored options
        if (seen.has(o.value)) return false;
        seen.add(o.value);
        return true;
    });

    function resetNilaiInputs() {
        for (let i=1;i<=6;i++){
            const el = document.querySelector('[name="nilai'+i+'"]');
            if (el) { el.value = ''; el.disabled = true; }
        }
        resetComputedFields();
    }

    function resetComputedFields(){
        const sumEl = document.querySelector('[name="n_sumatif"]');
        const semEl = document.querySelector('[name="n_akhir_semester"]');
        const akhirEl = document.querySelector('[name="nilai_akhir"]');
        const descEl = document.querySelector('[name="deskripsi"]');
        if (sumEl) sumEl.value = '';
        if (semEl) semEl.value = '';
        if (akhirEl) akhirEl.value = '';
        if (descEl) descEl.value = '';
    }

    function computeNSumatif(){
        let sum = 0;
        let count = 0;
        for (let i=1;i<=6;i++){
            const el = document.querySelector('[name="nilai'+i+'"]');
            if (!el) continue;
            const val = el.value;
            if (el.disabled) continue;
            if (val === null || val === undefined || String(val).trim() === '') continue;
            const num = parseFloat(val);
            if (!isNaN(num)) { sum += num; count++; }
        }
        const target = document.querySelector('[name="n_sumatif"]');
        if (!target) return;
        if (count === 0) { target.value = ''; computeNilaiAkhir(); return; }
        const avg = sum / count;
        // n-sumatif tanpa desimal (bulatkan)
        target.value = Math.round(avg);
        computeNilaiAkhir();
    }

    function computeNilaiAkhir(){
        const sumatifEl = document.querySelector('[name="n_sumatif"]');
        const semesterEl = document.querySelector('[name="n_akhir_semester"]');
        const akhirEl = document.querySelector('[name="nilai_akhir"]');
        if (!akhirEl || !sumatifEl) return;
        const s = sumatifEl.value;
        const sem = semesterEl ? semesterEl.value : '';
        if (s === null || s === undefined || String(s).trim() === '') { akhirEl.value = ''; return; }
        const sNum = parseFloat(s);
        if (sem === null || sem === undefined || String(sem).trim() === '') {
                akhirEl.value = Math.round(sNum);
            generateDeskripsi();
            return;
        }
        const semNum = parseFloat(sem);
        if (isNaN(semNum)) { akhirEl.value = parseFloat(sNum).toFixed(2); return; }
        const avg = (sNum + semNum) / 2;
            akhirEl.value = Math.round(avg);
        generateDeskripsi();
    }

    function generateDeskripsi(){
        const akhirEl = document.querySelector('[name="nilai_akhir"]');
        const descEl = document.querySelector('[name="deskripsi"]');
        const opt = mapelSelect.options[mapelSelect.selectedIndex];
        if (!akhirEl || !descEl) return;
        const akhirVal = akhirEl.value;
        if (akhirVal === null || akhirVal === undefined || String(akhirVal).trim() === '') { descEl.value = ''; return; }
        const akhirNum = parseFloat(akhirVal);
        if (isNaN(akhirNum)) { descEl.value = ''; return; }

        // gather materi texts and nilai
        const materis = [];
        const nilais = [];
        for (let i=1;i<=6;i++){
            const mText = opt ? (opt.dataset['m'+i+'Text'] || '').trim() : '';
            const nEl = document.querySelector('[name="nilai'+i+'"]');
            const nVal = nEl && !nEl.disabled && String(nEl.value).trim() !== '' ? parseFloat(nEl.value) : null;
            materis[i] = mText !== '' ? mText : null;
            nilais[i] = isNaN(nVal) ? null : nVal;
        }

        const above = [];
        const below = [];
        for (let i=1;i<=6;i++){
            if (!materis[i] || nilais[i] === null) continue;
            if (nilais[i] > akhirNum) above.push(materis[i]);
            else if (nilais[i] < akhirNum) below.push(materis[i]);
        }
        // fallback highest/lowest
        if (above.length === 0){
            let bestIdx = null, bestVal = null;
            for (let i=1;i<=6;i++){
                if (!materis[i] || nilais[i] === null) continue;
                if (bestVal === null || nilais[i] > bestVal){ bestVal = nilais[i]; bestIdx = i; }
            }
            if (bestIdx !== null) above.push(materis[bestIdx]);
        }
        if (below.length === 0){
            let worstIdx = null, worstVal = null;
            for (let i=1;i<=6;i++){
                if (!materis[i] || nilais[i] === null) continue;
                if (worstVal === null || nilais[i] < worstVal){ worstVal = nilais[i]; worstIdx = i; }
            }
            if (worstIdx !== null) below.push(materis[worstIdx]);
        }

        const parts = [];
        const htmlParts = [];
        // derive peserta nickname (first token of selected peserta option)
        let namaPanggilan = '';
        if (typeof pesertaSelect !== 'undefined' && pesertaSelect && pesertaSelect.value) {
            const txt = pesertaSelect.options[pesertaSelect.selectedIndex].text || '';
            namaPanggilan = (txt.split(' ')[0] || txt).trim();
        }
        if (above.length) {
            parts.push('Ananda ' + namaPanggilan + ' mampu dalam ' + above.join(', '));
            htmlParts.push('Ananda ' + namaPanggilan + ' <strong>mampu</strong> dalam ' + above.join(', '));
        }
        if (below.length) {
            parts.push('perlu perhatian dalam ' + below.join(', '));
            htmlParts.push('<strong>perlu perhatian</strong> dalam ' + below.join(', '));
        }
        // set plain-text into textarea so saved value is readable; index view will render bold HTML
        descEl.value = parts.length ? parts.join(' | ') : '';
    }

    resetNilaiInputs();

    // attach input listeners to nilai fields to recompute n_sumatif
    for (let i=1;i<=6;i++){
        const el = document.querySelector('[name="nilai'+i+'"]');
        if (el) {
            el.addEventListener('input', function(){ computeNSumatif(); });
        }
    }
    // recompute nilai akhir when n_akhir_semester changes; also ensure it's an integer
    const nAkhirEl = document.querySelector('[name="n_akhir_semester"]');
    if (nAkhirEl) {
        nAkhirEl.addEventListener('input', function(){ computeNilaiAkhir(); });
        nAkhirEl.addEventListener('blur', function(){
            const v = this.value;
            if (v === null || v === undefined || String(v).trim() === '') return;
            const num = parseFloat(v);
            if (isNaN(num)) { this.value = ''; computeNilaiAkhir(); return; }
            this.value = Math.round(num);
            computeNilaiAkhir();
        });
    }

    kelasSelect.addEventListener('change', function(e){
        const val = this.value;

        // filter mapel options to those matching kelas (or empty kelas)
        mapelSelect.innerHTML = '';
        const placeholder = document.createElement('option');
        placeholder.value = '';
        placeholder.textContent = '-- Pilih Mata Pelajaran --';
        mapelSelect.appendChild(placeholder);

        mapelOptions.forEach(function(opt){
            const optKelas = opt.dataset.kelas || '';
            if (!val || optKelas === '' || String(optKelas) === String(val)) {
                mapelSelect.appendChild(opt.cloneNode(true));
            }
        });

        // reset peserta list and nilai inputs
        pesertaSelect.innerHTML = '<option value="">-- Memuat peserta --</option>';
        pesertaSelect.disabled = true;
        resetNilaiInputs();
        resetComputedFields();

        if (!val) {
            pesertaSelect.innerHTML = '<option value="">-- Pilih Kelas terlebih dahulu --</option>';
            pesertaSelect.disabled = true;
            return;
        }

        fetch(baseApi + '/peserta-kelas/' + encodeURIComponent(val))
            .then(res => res.json())
            .then(data => {
                pesertaSelect.innerHTML = '<option value="">-- Pilih Peserta Didik --</option>';
                if (Array.isArray(data) && data.length) {
                    data.forEach(function(item){
                        const name = item.nama ?? item.name ?? (item.nama_lengkap ?? 'Peserta ' + (item.id ?? ''));
                        const opt = document.createElement('option');
                        opt.value = item.id;
                        opt.textContent = name;
                        pesertaSelect.appendChild(opt);
                    });
                    pesertaSelect.disabled = false;
                } else {
                    pesertaSelect.innerHTML = '<option value="">-- Tidak ada peserta --</option>';
                    pesertaSelect.disabled = true;
                }
            }).catch(err => {
                pesertaSelect.innerHTML = '<option value="">-- Gagal memuat peserta --</option>';
                pesertaSelect.disabled = true;
                console.error('Gagal memuat peserta:', err);
            });
    });

    mapelSelect.addEventListener('change', function(){
        const opt = mapelSelect.options[mapelSelect.selectedIndex];
        resetNilaiInputs();
        if (!opt || !opt.dataset) return;
        for (let i=1;i<=6;i++){
            const has = opt.dataset['m'+i] === '1';
            const el = document.querySelector('[name="nilai'+i+'"]');
            if (el) {
                el.disabled = !has;
                if (!has) el.value = '';
            }
        }
        // recompute n_sumatif after enabling/disabling fields
        computeNSumatif();
        // if no nilai present, ensure computed fields cleared
        const anyEnabled = Array.from({length:6}).some((_,i)=>{
            const el = document.querySelector('[name="nilai'+(i+1)+'"]');
            return el && !el.disabled && String(el.value).trim() !== '';
        });
        if (!anyEnabled) resetComputedFields();
    });

    // Clear computed fields when modal opens so defaults are empty
    const modalEl = document.getElementById('modalTambahNilaiIntrakulikuler');
    if (modalEl) {
        modalEl.addEventListener('show.bs.modal', function () {
            const form = modalEl.querySelector('form');
            if (form) form.reset();
            // reset selects and computed fields
            pesertaSelect.innerHTML = '<option value="">-- Pilih Kelas terlebih dahulu --</option>';
            pesertaSelect.disabled = true;
            mapelSelect.innerHTML = '';
            const placeholder = document.createElement('option'); placeholder.value = ''; placeholder.textContent = '-- Pilih Mata Pelajaran --'; mapelSelect.appendChild(placeholder);
            resetNilaiInputs();
            resetComputedFields();
        });
    }
})();
</script>
<?php $__env->stopPush(); ?>
<?php /**PATH C:\App\laravel\laravel\resources\views/admin/penilaian/intrakulikuler/create.blade.php ENDPATH**/ ?>