<div class="modal fade" id="modalBeriNilai" tabindex="-1" aria-labelledby="modalBeriNilaiLabel" 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.kokurikuler.store')); ?><?php elseif(\Illuminate\Support\Facades\Route::has('admin.penilaian.kokurikuler.store')): ?><?php echo e(route('admin.penilaian.kokurikuler.store')); ?><?php else: ?>#<?php endif; ?>">
        <?php echo csrf_field(); ?>
        <div class="modal-header" style="background-color:#f3e6ff;color:#3b0b6f;">
          <h5 class="modal-title" id="modalBeriNilaiLabel">Penilaian Profil Lulusan</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="mb-3">
            <label class="form-label">Kelas</label>
            <select name="kelas_id" id="kelasSelect" class="form-select" required>
              <option value="">-- Pilih Kelas --</option>
              <?php if(isset($kelasList) && count($kelasList)): ?>
                <?php $__currentLoopData = $kelasList; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $k): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                  <option value="<?php echo e($k->id); ?>"><?php echo e(data_get($k, 'nama_kelas') ?? data_get($k, 'nama')); ?></option>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
              <?php endif; ?>
            </select>
          </div>

          <div class="mb-3">
            <label class="form-label">Nama Peserta Didik</label>
            <select name="peserta_didik_id" id="pesertaSelect" class="form-select" required disabled>
              <option value="">-- Pilih Kelas terlebih dahulu --</option>
            </select>
          </div>

          <div class="row">
            <div class="col-md-6 mb-3">
              <label class="form-label">Demensi</label>
              <?php if(isset($demensiList) && $demensiList->count()): ?>
                <select name="demensi" id="demensiSelect" class="form-select" required>
                  <option value="">-- Pilih Demensi --</option>
                  <?php $__currentLoopData = $demensiList; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $d): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <option value="<?php echo e($d->id); ?>"><?php echo e(data_get($d, 'nama_demensi') ?? $d->nama_demensi ?? ('Demensi '.$d->id)); ?></option>
                  <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>
              <?php else: ?>
                <input type="text" name="demensi" class="form-control" required>
              <?php endif; ?>
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">Sub Demensi</label>
              <select name="sub_demensi" id="subDemensiSelect" class="form-select" disabled style="display:none;"></select>
              <input type="text" name="sub_demensi" id="subDemensiInput" class="form-control" style="display:none;" placeholder="Masukkan Sub Demensi">
            </div>
          </div>

          <div class="row">
            <div class="col-md-4 mb-3">
              <label class="form-label">Nilai</label>
              <div class="d-flex align-items-center">
                <div class="btn-group" role="group" aria-label="Nilai pilihan">
                  <input type="radio" class="btn-check" name="nilai" id="nilaiBK" value="BK" autocomplete="off" required>
                  <label class="btn btn-outline-primary btn-sm" for="nilaiBK">BK</label>

                  <input type="radio" class="btn-check" name="nilai" id="nilaiCK" value="CK" autocomplete="off">
                  <label class="btn btn-outline-primary btn-sm" for="nilaiCK">CK</label>

                  <input type="radio" class="btn-check" name="nilai" id="nilaiMH" value="MH" autocomplete="off">
                  <label class="btn btn-outline-primary btn-sm" for="nilaiMH">MH</label>
                </div>
              </div>
              <div class="form-text mt-1">BK = Berkembang, CK = Cakap, MH = Mahir</div>
            </div>
            <div class="col-md-8 mb-3">
              <label class="form-label">Deskripsi</label>
              <textarea name="deskripsi" id="deskripsiField" class="form-control" rows="3" placeholder="Deskripsi otomatis atau ketik manual"></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>

<script>
  // baseApi used by AJAX calls; define once at script top so other handlers can use it
  var baseApi = (window.location.pathname.indexOf('/guru/') === 0) ? '/guru/penilaian' : '/admin/penilaian';

  document.addEventListener('DOMContentLoaded', function () {
    const kelasSelect = document.getElementById('kelasSelect');
    const pesertaSelect = document.getElementById('pesertaSelect');

    if (!kelasSelect || !pesertaSelect) return;

    function resetPeserta(message = '-- Pilih Kelas terlebih dahulu --') {
      pesertaSelect.innerHTML = `<option value="">${message}</option>`;
      pesertaSelect.setAttribute('disabled', 'disabled');
    }

    // initialize
    resetPeserta();

    kelasSelect.addEventListener('change', function () {
      const kelasId = this.value;
      pesertaSelect.innerHTML = '';
      if (!kelasId) {
        resetPeserta();
        return;
      }

      // fetch peserta for kelas via AJAX
      fetch(baseApi + `/peserta-kelas/${encodeURIComponent(kelasId)}`)
        .then(resp => resp.json())
        .then(data => {
          if (!Array.isArray(data) || data.length === 0) {
            resetPeserta('-- Tidak ada peserta di kelas ini --');
            return;
          }

          pesertaSelect.innerHTML = '';
          data.forEach(pd => {
            const opt = document.createElement('option');
            opt.value = pd.id;
            opt.textContent = pd.nama + (pd.nis ? ` (${pd.nis})` : '');
            pesertaSelect.appendChild(opt);
          });
          pesertaSelect.removeAttribute('disabled');
        })
        .catch(() => {
          resetPeserta('-- Gagal memuat peserta --');
        });
    });
    // demensi -> sub-demensi
    const demensiSelect = document.getElementById('demensiSelect');
    const subDemensiSelect = document.getElementById('subDemensiSelect');
    const subDemensiInput = document.getElementById('subDemensiInput');

    if (demensiSelect) {
      demensiSelect.addEventListener('change', function () {
        const demId = this.value;
        // hide both while loading
        if (!subDemensiSelect || !subDemensiInput) return;
        subDemensiSelect.style.display = 'none';
        subDemensiInput.style.display = 'none';
        subDemensiSelect.innerHTML = '';

        if (!demId) {
          // show text input fallback
          subDemensiInput.style.display = '';
          subDemensiInput.removeAttribute('disabled');
          return;
        }

        fetch(baseApi + `/demensi/${encodeURIComponent(demId)}/sub-demensi`)
          .then(r => r.json())
          .then(list => {
            if (!Array.isArray(list) || list.length === 0) {
              // fallback to free text
              subDemensiInput.style.display = '';
              subDemensiInput.removeAttribute('disabled');
              subDemensiSelect.style.display = 'none';
              return;
            }

            // populate select
            subDemensiSelect.innerHTML = '';
            const placeholder = document.createElement('option');
            placeholder.value = '';
            placeholder.textContent = '-- Pilih Sub Demensi --';
            subDemensiSelect.appendChild(placeholder);
            list.forEach(s => {
              const o = document.createElement('option');
              o.value = s;
              o.textContent = s;
              subDemensiSelect.appendChild(o);
            });
            subDemensiSelect.style.display = '';
            subDemensiSelect.removeAttribute('disabled');
            subDemensiInput.style.display = 'none';
            subDemensiInput.setAttribute('disabled', 'disabled');
          })
          .catch(() => {
            subDemensiInput.style.display = '';
            subDemensiInput.removeAttribute('disabled');
          });
      });
    }
    // nilai radio -> deskripsi
    const deskripsiField = document.getElementById('deskripsiField');
    function applyDeskripsiMap(map, kode) {
      if (!deskripsiField) return;
      let val = '';
      if (map) {
        if (kode === 'BK') val = map.berkembang ?? map['berkembang'] ?? map.BK ?? '';
        if (kode === 'CK') val = map.cakap ?? map['cakap'] ?? map.CK ?? '';
        if (kode === 'MH') val = map.mahir ?? map['mahir'] ?? map.MH ?? '';
      }
      deskripsiField.value = val;
    }

    function fetchAndApplyDeskripsi(kode) {
      const demId = demensiSelect ? demensiSelect.value : '';
      let subVal = '';
      if (subDemensiSelect && subDemensiSelect.style.display !== 'none') subVal = subDemensiSelect.value;
      if (subDemensiInput && subDemensiInput.style.display !== 'none') subVal = subDemensiInput.value;

      if (!demId) {
        applyDeskripsiMap(null, kode);
        return;
      }

      const url = baseApi + `/demensi/${encodeURIComponent(demId)}/deskripsi${subVal ? '?sub='+encodeURIComponent(subVal) : ''}`;
      fetch(url)
        .then(r => r.json())
        .then(map => applyDeskripsiMap(map, kode))
        .catch(() => applyDeskripsiMap(null, kode));
    }

    ['nilaiBK','nilaiCK','nilaiMH'].forEach(id => {
      const el = document.getElementById(id);
      if (!el) return;
      el.addEventListener('change', function () {
        if (!this.checked) return;
        const kode = this.value;
        fetchAndApplyDeskripsi(kode);
      });
    });

    // update deskripsi when sub-demensi changes and a nilai is already selected
    if (subDemensiSelect) {
      subDemensiSelect.addEventListener('change', function () {
        const selected = document.querySelector('input[name="nilai"]:checked');
        if (!selected) return;
        fetchAndApplyDeskripsi(selected.value);
      });
    }
    if (subDemensiInput) {
      subDemensiInput.addEventListener('input', function () {
        const selected = document.querySelector('input[name="nilai"]:checked');
        if (!selected) return;
        fetchAndApplyDeskripsi(selected.value);
      });
    }
  });
</script>
<?php /**PATH C:\App\laravel\laravel\resources\views/admin/penilaian/kokurikuler/create.blade.php ENDPATH**/ ?>