@extends('admin.layout')

@section('title', '')

@section('content')
    <div class="card">
        <div class="card-header" style="background-color:#6f42c1; color:#fff;">
            <div>
                <h5 class="mb-0"><i class="bi bi-star me-2"></i>Penilaian Ekstrakulikuler</h5>
                <small class="text-warning">Kelola kegiatan ekstrakulikuler dan penilaian non-akademik</small>
            </div>
        </div>
        <div class="card-body">
            @php
                $activePeriode = \App\Models\Periode::where('status', \App\Models\Periode::STATUS_AKTIF)->first();
                $tahunPel = $activePeriode->tahun_pelajaran ?? '-';
                $semester = $activePeriode->semester ?? '-';
            @endphp
            <div class="d-flex justify-content-between align-items-start mt-2">
                <div>
                    <h6 class="mb-1">Daftar Penilaian Kualitatif Non-Akademis Peserta Didik</h6>
                    <div class="small text-danger">Tahun Pelajaran: <strong>{{ $tahunPel }}</strong> &nbsp;|&nbsp; Semester: <strong>{{ $semester }}</strong></div>
                </div>
                <div>
                    <button class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#addNilaiModal"><i class="bi bi-plus-lg me-1"></i> Tambah nilai</button>
                </div>
            </div>
            {{-- Filters: Kelas & Peserta Didik for ekstrakulikuler --}}
            <div class="row mt-3">
                <div class="col-md-4">
                    <label class="form-label">Kelas</label>
                    <select name="filter_kelas" class="form-select">
                        <option value="">-- Pilih Kelas --</option>
                        @foreach($kelasList ?? [] as $k)
                            <option value="{{ $k->id }}">{{ $k->nama ?? $k->nama_kelas ?? $k->nama }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Peserta Didik</label>
                    <select name="filter_peserta" class="form-select" disabled>
                        <option value="">-- Pilih Kelas terlebih dahulu --</option>
                    </select>
                </div>
                
            </div>
            <div class="row mt-2">
                <div class="col-12">
                    <div class="alert alert-info mb-3" id="ekstraInfo">
                        Silakan pilih <strong>Kelas</strong> dan <strong>Peserta Didik</strong> untuk menampilkan data.
                    </div>
                </div>
            </div>
            @php
                $records = $records ?? ($penilaians ?? collect());
            @endphp

            <div class="table-responsive mt-3" id="ekstraTableWrap">
                <table class="table table-bordered table-striped">
                    <thead class="table-light">
                        <tr>
                            <th>Nama Peserta Didik</th>
                            <th>Kelas</th>
                            <th>Kategori</th>
                            <th>Ekstrakulikuler</th>
                            <th>Nilai</th>
                            <th>Deskripsi</th>
                            <th style="width:140px">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($records as $r)
                            <tr data-kelas="{{ data_get($r, 'kelas_id', '') }}" data-peserta="{{ data_get($r, 'peserta_didik_id', '') }}">
                                <td>{{ data_get($r, 'nama', data_get($r, 'student_name', '-')) }}</td>
                                <td>{{ data_get($r, 'kelas', data_get($r, 'class', '-')) }}</td>
                                <td>{{ data_get($r, 'kategori', '') }}</td>
                                <td>{{ data_get($r, 'ekstrakulikuler', data_get($r, 'activity', '-')) }}</td>
                                <td>{{ data_get($r, 'nilai', data_get($r, 'score', '-')) }}</td>
                                <td class="text-start">{{ data_get($r, 'deskripsi', data_get($r, 'description', '-')) }}</td>
                                <td>
                                    @if(request()->is('guru/*') || (auth()->check() && optional(auth()->user())->role === 'guru'))
                                        <button type="button" class="btn btn-sm btn-primary btn-icon me-1 btn-edit"
                                            data-bs-toggle="modal" data-bs-target="#editNilaiModal"
                                            data-id="{{ data_get($r, 'id', '') }}"
                                            data-kelas_id="{{ data_get($r, 'kelas_id', '') }}"
                                            data-peserta_id="{{ data_get($r, 'peserta_didik_id', '') }}"
                                            data-ekstra_id="{{ data_get($r, 'ekstrakulikuler_id', '') }}"
                                            data-nilai="{{ data_get($r, 'nilai', '') }}"
                                            data-deskripsi="{{ htmlspecialchars(data_get($r, 'deskripsi', data_get($r, 'description', '')), ENT_QUOTES) }}"
                                            title="Edit"><i class="bi bi-pencil"></i></button>
                                        <form action="@if(request()->is('guru/*')){{ url('guru/penilaian/ekstrakulikuler/'.data_get($r, 'id', '')) }}@else{{ url('admin/penilaian/ekstrakulikuler/'.data_get($r, 'id', '')) }}@endif" method="POST" style="display:inline-block" onsubmit="return confirm('Hapus data ini?');">
                                            @csrf
                                            @method('DELETE')
                                            <button class="btn btn-sm btn-danger btn-icon" title="Hapus"><i class="bi bi-trash"></i></button>
                                        </form>
                                    @else
                                        <button type="button" class="btn btn-sm btn-outline-primary btn-edit"
                                            data-bs-toggle="modal" data-bs-target="#editNilaiModal"
                                            data-id="{{ data_get($r, 'id', '') }}"
                                            data-kelas_id="{{ data_get($r, 'kelas_id', '') }}"
                                            data-peserta_id="{{ data_get($r, 'peserta_didik_id', '') }}"
                                            data-ekstra_id="{{ data_get($r, 'ekstrakulikuler_id', '') }}"
                                            data-nilai="{{ data_get($r, 'nilai', '') }}"
                                            data-deskripsi="{{ htmlspecialchars(data_get($r, 'deskripsi', data_get($r, 'description', '')), ENT_QUOTES) }}"
                                        >Edit</button>
                                        <form action="@if(request()->is('guru/*')){{ url('guru/penilaian/ekstrakulikuler/'.data_get($r, 'id', '')) }}@else{{ url('admin/penilaian/ekstrakulikuler/'.data_get($r, 'id', '')) }}@endif" method="POST" style="display:inline-block" onsubmit="return confirm('Hapus data ini?');">
                                            @csrf
                                            @method('DELETE')
                                            <button class="btn btn-sm btn-outline-danger">Hapus</button>
                                        </form>
                                    @endif
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="7" class="text-center text-muted">Belum ada data penilaian ekstrakulikuler.</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
            @include('admin.penilaian.ekstrakulikuler.create')
            @include('admin.penilaian.ekstrakulikuler.edit')
        </div>
    </div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function(){
    var kelasSelect = document.querySelector('select[name="kelas_id"]');
    var pesertaSelect = document.querySelector('select[name="peserta_didik_id"]');

    // filtering selects on the index card
    var filterKelas = document.querySelector('select[name="filter_kelas"]');
    var filterPeserta = document.querySelector('select[name="filter_peserta"]');
    var baseApi = (window.location.pathname.indexOf('/guru/') === 0) ? '/guru/penilaian' : '/admin/penilaian';
    var ekstraTableWrap = document.getElementById('ekstraTableWrap');
    var ekstraInfo = document.getElementById('ekstraInfo');

    function updateTableVisibilityAndFilter(){
        if (!filterKelas || !filterPeserta) return;
        var k = filterKelas.value;
        var p = filterPeserta.value;
        if (!ekstraTableWrap) return;
        var rows = ekstraTableWrap.querySelectorAll('tbody tr');

        // hide table unless both selected
        if (!k || !p) {
            if (ekstraInfo) ekstraInfo.style.display = '';
            ekstraTableWrap.style.display = 'none';
            return;
        }

        // hide info and show table; filter rows by data attributes
        if (ekstraInfo) ekstraInfo.style.display = 'none';
        ekstraTableWrap.style.display = '';
        rows.forEach(function(row){
            var rk = row.getAttribute('data-kelas') || '';
            var rp = row.getAttribute('data-peserta') || '';
            var match = (String(rk) === String(k)) && (String(rp) === String(p));
            row.style.display = match ? '' : 'none';
        });
    }

    if (filterKelas && filterPeserta) {
        filterPeserta.disabled = true;
        filterKelas.addEventListener('change', function(){
            var val = this.value;
            filterPeserta.innerHTML = '<option value="">-- Pilih Peserta --</option>';
            filterPeserta.disabled = true;
            if (!val) {
                updateTableVisibilityAndFilter();
                return;
            }
            // load peserta for kelas
            fetch(baseApi + '/peserta-kelas/' + encodeURIComponent(val), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                .then(function(res){ if(!res.ok) throw new Error('Network'); return res.json(); })
                .then(function(data){
                    if (!Array.isArray(data)) return;
                    data.forEach(function(p){
                        var opt = document.createElement('option'); opt.value = p.id; opt.textContent = p.nama || p.name || ('#'+p.id);
                        filterPeserta.appendChild(opt);
                    });
                    if (data.length > 0) filterPeserta.disabled = false;
                    updateTableVisibilityAndFilter();
                })
                .catch(function(){ /* ignore */ });
        });

        filterPeserta.addEventListener('change', function(){
            updateTableVisibilityAndFilter();
        });
    }

    // initial state: hide table until both selected
    updateTableVisibilityAndFilter();

    if (!kelasSelect || !pesertaSelect) return;

    // ensure peserta disabled initially
    pesertaSelect.disabled = true;

    kelasSelect.addEventListener('change', function(){
        var val = this.value;
        // reset peserta options
        pesertaSelect.innerHTML = '<option value="">-- Pilih Peserta --</option>';
        pesertaSelect.disabled = true;
        if (!val) return;

        fetch(baseApi + "/peserta-kelas/" + encodeURIComponent(val), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function(res){ if (!res.ok) throw new Error('Network response was not ok'); return res.json(); })
            .then(function(data){
                if (!Array.isArray(data)) return;
                data.forEach(function(p){
                    var opt = document.createElement('option');
                    opt.value = p.id;
                    opt.textContent = p.nama || p.name || ('#' + p.id);
                    pesertaSelect.appendChild(opt);
                });
                if (data.length > 0) pesertaSelect.disabled = false;
            })
            .catch(function(err){ console.error('Failed to load peserta:', err); });
    });

    // handle filling description based on nilai (A/B/C) and selected ekstrakulikuler
    var ekstraSelect = document.querySelector('select[name="ekstrakulikuler_id"]');
    var deskripsiElem = document.querySelector('textarea[name="deskripsi"]');
    var nilaiRadios = document.querySelectorAll('input[name="nilai"]');

    function getEkstraKeterangan() {
        if (!ekstraSelect) return '';
        var opt = ekstraSelect.options[ekstraSelect.selectedIndex];
        if (!opt) return '';
        return opt.dataset.keterangan || opt.getAttribute('data-keterangan') || '';
    }

    function currentNilaiPrefix(val){
        // mapping: A -> Mahir, B -> Cakap, C -> Berkembang
        if (val === 'A') return 'Mahir';
        if (val === 'B') return 'Cakap';
        return 'Berkembang';
    }

    function updateDeskripsiFromNilai(){
        if (!deskripsiElem) return;
        var selectedNilai = null;
        nilaiRadios.forEach(function(r){ if(r.checked) selectedNilai = r.value; });
        var ekstraK = getEkstraKeterangan();
        if (!selectedNilai) return;
        var prefix = currentNilaiPrefix(selectedNilai);
        var combined = prefix + ' ' + (ekstraK || '');
        deskripsiElem.value = combined.trim();
    }

    if (nilaiRadios && nilaiRadios.length) {
        nilaiRadios.forEach(function(r){ r.addEventListener('change', updateDeskripsiFromNilai); });
    }
    if (ekstraSelect) {
        ekstraSelect.addEventListener('change', updateDeskripsiFromNilai);
    }

    // Fill edit modal when it's shown (use relatedTarget to get triggering button)
    var editModalEl = document.getElementById('editNilaiModal');
    if (editModalEl) {
        editModalEl.addEventListener('show.bs.modal', function(event){
            var btn = event.relatedTarget;
            if (!btn) return;
            var id = btn.getAttribute('data-id') || '';
            var kelasId = btn.getAttribute('data-kelas_id') || '';
            var pesertaId = btn.getAttribute('data-peserta_id') || '';
            var ekstraId = btn.getAttribute('data-ekstra_id') || '';
            var nilai = btn.getAttribute('data-nilai') || '';
            var deskripsi = btn.getAttribute('data-deskripsi') || '';

            var form = document.getElementById('formEditNilai');
            if (!form) return;
            var editBase = (window.location.pathname.indexOf('/guru/') === 0) ? '/guru/penilaian/ekstrakulikuler/' : '/admin/penilaian/ekstrakulikuler/';
            form.action = editBase + encodeURIComponent(id);
            var idInput = form.querySelector('input[name="id"]'); if (idInput) idInput.value = id;

            var kelasSel = form.querySelector('select[name="kelas_id"]');
            var pesertaSel = form.querySelector('select[name="peserta_didik_id"]');
            var ekstraSel = form.querySelector('select[name="ekstrakulikuler_id"]');
            var deskripsiEl = form.querySelector('textarea[name="deskripsi"]');
            var nilaiRad = form.querySelectorAll('input[name="nilai"]');

            if (kelasSel) kelasSel.value = kelasId;

            if (pesertaSel) {
                pesertaSel.innerHTML = '<option value="">-- Pilih Peserta --</option>';
                pesertaSel.disabled = true;
                if (kelasId) {
                    fetch(baseApi + '/peserta-kelas/' + encodeURIComponent(kelasId), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                        .then(function(res){ if(!res.ok) throw new Error('Network'); return res.json(); })
                        .then(function(data){
                            data.forEach(function(p){
                                var opt = document.createElement('option'); opt.value = p.id; opt.textContent = p.nama || p.name || ('#'+p.id);
                                pesertaSel.appendChild(opt);
                            });
                            if (pesertaId) pesertaSel.value = pesertaId;
                            pesertaSel.disabled = false;
                        })
                        .catch(function(){ /* ignore */ });
                }
            }

            if (ekstraSel) ekstraSel.value = ekstraId;
            if (deskripsiEl) deskripsiEl.value = deskripsi;
            if (nilaiRad && nilaiRad.length) {
                nilaiRad.forEach(function(r){ r.checked = (r.value === nilai); });
            }
        });
    }
});
</script>
@endpush
