@extends('admin.layout')

@section('title', '')

@section('content')
<div class="row">
    <div class="col-12">
        <div class="p-3 rounded-top text-white d-flex align-items-center" style="background-color:#000;">
            <i class="bi bi-folder2-open fs-3 me-3"></i>
            <div>
                <h5 class="mb-0">Dokumen Rapot</h5>
                <small class="text-white-50">Halaman Pencetakan Hasil Belajar Peserta didik.</small>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-12">
        <!-- Baris tambahan untuk isi konten (menempel ke banner) -->
        <div class="card" style="border-top-left-radius:0;border-top-right-radius:0;margin-top:0;">
            <div class="card-body">
                @php
                    try {
                        $kelasList = \App\Models\Kelas::orderBy('nama')->get();
                    } catch (\Throwable $e) {
                        $kelasList = collect();
                    }

                    try {
                        $pesertas = class_exists(\App\Models\DidikPokok::class) ? \App\Models\DidikPokok::orderBy('nama')->get() : collect();
                    } catch (\Throwable $e) {
                        $pesertas = collect();
                    }
                    try {
                        $sekolah = class_exists(\App\Models\Sekolah::class) ? \App\Models\Sekolah::first() : null;
                    } catch (\Throwable $e) {
                        $sekolah = null;
                    }
                @endphp

                @php
                    try {
                        $activePeriode = \App\Services\PeriodeService::getActive();
                    } catch (\Throwable $e) {
                        $activePeriode = null;
                    }
                @endphp

                <h4 class="mb-1">Pelaporan Hasil Belajar Peserta Didik</h4>
                @if($activePeriode)
                    <div class="mb-3 text-danger">Tahun Pelajaran: {{ $activePeriode->tahun_pelajaran }} &middot; Semester: {{ $activePeriode->semester }}</div>
                @else
                    <div class="mb-3 text-danger">Tahun Pelajaran: - &middot; Semester: -</div>
                @endif

                <div class="row g-3 align-items-end">
                    <div class="col-md-6">
                        <label for="kelasSelect" class="form-label">Pilih Kelas</label>
                        <select id="kelasSelect" class="form-select">
                            <option value="">-- Pilih Kelas --</option>
                            @foreach($kelasList as $k)
                                <option value="{{ $k->id }}">{{ $k->nama }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="col-md-6">
                        <label for="pesertaSelect" class="form-label">Pilih Peserta Didik</label>
                        <select id="pesertaSelect" class="form-select" disabled>
                            <option value="">-- Pilih kelas terlebih dahulu --</option>
                        </select>
                    </div>
                </div>

                <div class="mt-3" id="rapotActions" style="display:none;">
                    <button id="btnGenerate" class="btn btn-primary">Lanjutkan</button>
                </div>

                <div id="rapotPreviewContainer" class="mt-4"></div>

                <style>
                    .rapot-preview { font-size:11px; }
                    .rapot-preview .card-body{ padding: .5rem; font-size:11px; }
                    .rapot-preview table th { background:#f0f0f0; }
                    .rapot-preview table td{ padding: .125rem .5rem; vertical-align: top; }
                    .rapot-preview .text-center{ margin-bottom: .25rem; }
                    .rapot-preview .fw-bold{ font-size:1rem; }
                    .rapot-preview .ekstra-table{ font-size:11px; }
                    .rapot-preview .absensi-table, .rapot-preview .wali-table { font-size:11px; }
                    .rapot-preview .ekstra-table td, .rapot-preview .absensi-table td, .rapot-preview .wali-table td { padding:.125rem .5rem; vertical-align:middle; }
                </style>

                <script>
                    (function(){
                        @php
                            $__peserta_list = [];
                            foreach($pesertas as $__p) {
                                $__peserta_list[] = [
                                    'id' => $__p->id ?? null,
                                    'nama' => $__p->nama ?? null,
                                    'kelas' => $__p->kelas ?? null,
                                    'rombel' => $__p->rombel ?? null,
                                    'fase' => $__p->fase ?? null,
                                    'nis' => $__p->nis ?? null,
                                    'nisn' => $__p->nisn ?? null,
                                    'alamat' => $__p->alamat ?? null,
                                    'nama_ayah' => $__p->nama_ayah ?? null,
                                ];
                            }
                        @endphp

                        @php
                            // expose kelas list and mata pelajaran map for JS
                            try {
                                $__kelas_list = [];
                                foreach($kelasList as $__k) {
                                    $__kelas_list[] = ['id' => $__k->id, 'nama' => $__k->nama, 'rombel' => $__k->rombel ?? null];
                                }
                            } catch (\Throwable $e) {
                                $__kelas_list = [];
                            }

                            try {
                                $__mata_map = [];
                                if (class_exists(\App\Models\MataPelajaran::class)) {
                                    $__mp_rows = \App\Models\MataPelajaran::orderBy('urutan')->orderBy('nama')->get();
                                    foreach($__mp_rows as $__m) {
                                        $__mata_map[$__m->kelas_id][] = ['id' => $__m->id, 'nama' => $__m->nama];
                                    }
                                }
                            } catch (\Throwable $e) {
                                $__mata_map = [];
                            }
                        @endphp

                        @php
                            try {
                                $__penilaian_map = [];
                                if (class_exists(\App\Models\PenilaianIntrakulikuler::class)) {
                                    $__penilaian_rows = \App\Models\PenilaianIntrakulikuler::with('mata_pelajaran')->get();
                                    foreach($__penilaian_rows as $__r) {
                                            $pid = $__r->peserta_didik_id ?? null;
                                            if (is_null($pid)) continue;
                                            $__penilaian_map[$pid][] = [
                                                'mata_id' => $__r->mata_pelajaran_id ?? null,
                                                'mata' => optional($__r->mata_pelajaran)->nama ?? null,
                                                'nilai_akhir' => $__r->nilai_akhir ?? $__r->n_akhir_semester ?? null,
                                                'deskripsi' => $__r->deskripsi ?? null,
                                            ];
                                        }
                                } else {
                                    $__penilaian_map = [];
                                }
                            } catch (\Throwable $e) {
                                $__penilaian_map = [];
                            }
                        @endphp

                        @php
                            $__sekolah_js = null;
                            try {
                                if (isset($sekolah) && $sekolah) {
                                    $__sekolah_js = [
                                        'nama' => $sekolah->nama ?? null,
                                        'alamat' => $sekolah->alamat ?? null,
                                        'tanggal_rapot_1' => $sekolah->tanggal_rapot_1 ?? null,
                                        'tanggal_rapot_2' => $sekolah->tanggal_rapot_2 ?? null,
                                    ];
                                }
                            } catch (\Throwable $e) {
                                $__sekolah_js = null;
                            }
                        @endphp

                        const peserta = @json($__peserta_list);
                        const sekolah = @json($__sekolah_js);
                        const activePeriode = @json($activePeriode ? ['tahun_pelajaran' => $activePeriode->tahun_pelajaran, 'semester' => $activePeriode->semester] : null);
                        const kelasListJs = @json($__kelas_list);
                        const mataMap = @json($__mata_map);

                        const byKelas = {};
                        peserta.forEach(p => {
                            const key = p.kelas || '';
                            if (!byKelas[key]) byKelas[key] = [];
                            byKelas[key].push(p);
                        });

                        // build kelasById map for quick name lookup
                        const kelasById = {};
                        kelasListJs.forEach(k => { kelasById[k.id] = k; });

                        const penilaianMap = @json($__penilaian_map);

                        const kelasSel = document.getElementById('kelasSelect');
                        const pesertaSel = document.getElementById('pesertaSelect');
                        const rapotActions = document.getElementById('rapotActions');

                        kelasSel.addEventListener('change', function(){
                            const val = this.value;
                            pesertaSel.innerHTML = '';
                            if (!val) {
                                pesertaSel.disabled = true;
                                pesertaSel.innerHTML = '<option>-- Pilih kelas terlebih dahulu --</option>';
                                rapotActions.style.display = 'none';
                                return;
                            }

                            // val is kelas_id; find kelas name and use it to fetch peserta
                            const kelasInfo = kelasById[val] || null;
                            const kelasName = kelasInfo ? kelasInfo.nama : '';
                            const list = byKelas[kelasName] || [];
                            if (list.length === 0) {
                                pesertaSel.disabled = true;
                                pesertaSel.innerHTML = '<option>-- Tidak ada peserta untuk kelas ini --</option>';
                                rapotActions.style.display = 'none';
                                return;
                            }

                            pesertaSel.disabled = false;
                            const opt = document.createElement('option');
                            opt.value = '';
                            opt.textContent = '-- Pilih Peserta --';
                            pesertaSel.appendChild(opt);
                            list.forEach(p => {
                                const o = document.createElement('option');
                                o.value = p.id;
                                o.textContent = p.nama;
                                pesertaSel.appendChild(o);
                            });
                            rapotActions.style.display = 'block';
                        });

                        document.getElementById('btnGenerate').addEventListener('click', function(e){
                            e.preventDefault();
                            const pesertaId = pesertaSel.value;
                            if (!pesertaId) {
                                alert('Pilih peserta didik terlebih dahulu.');
                                return;
                            }

                            let pesertaObj = peserta.find(p => String(p.id) === String(pesertaId));
                            const container = document.getElementById('rapotPreviewContainer');

                            const periodeText = activePeriode ? (activePeriode.tahun_pelajaran + ' \u00B7 ' + activePeriode.semester) : '-';

                            const htmlStart = `
                                <div class="card rapot-preview">
                                    <div class="card-body">
                                        <div class="mt-3">
                                            <button id="btnPrint" class="btn btn-success me-2">Cetak</button>
                                            <button id="btnClosePreview" class="btn btn-secondary">Tutup</button>
                                        </div>
                                        <div class="text-center fw-bold" style="font-size:1.15rem;">LAPORAN HASIL BELAJAR ( Rapor)</div>
                                        <div class="row mt-3">
                                            <div class="col-md-5">
                                                <table class="table table-borderless mb-0 small">
                                                    <tr><td style="width:90px">Nama</td><td style="width:10px">:</td><td>${pesertaObj ? pesertaObj.nama : '-'}</td></tr>
                                                    <tr><td>NIS/NISN</td><td>:</td><td>${pesertaObj ? ((pesertaObj.nis||'-') + ' / ' + (pesertaObj.nisn||'-')) : '-'}</td></tr>
                                                    <tr><td>Sekolah</td><td>:</td><td>${sekolah ? (sekolah.nama || '-') : '-'}</td></tr>
                                                    <tr><td>Alamat</td><td>:</td><td>${sekolah ? (sekolah.alamat || '-') : (pesertaObj ? (pesertaObj.alamat || '-') : '-')}</td></tr>
                                                </table>
                                            </div>
                                            <div class="col-md-7">
                                                <table class="table table-borderless mb-0 small" style="white-space:nowrap">
                                                    <tr><td style="width:90px">Kelas</td><td style="width:10px">:</td><td>${(kelasById[kelasSel.value] ? kelasById[kelasSel.value].nama : kelasSel.value) || '-'}</td></tr>
                                                    <tr><td>Fase</td><td>:</td><td>${pesertaObj ? (pesertaObj.fase || '-') : '-'}</td></tr>
                                                    <tr><td>Semester</td><td>:</td><td>${activePeriode ? activePeriode.semester : '-'}</td></tr>
                                                    <tr><td>Tahun Pelajaran</td><td>:</td><td style="white-space:nowrap;min-width:180px">${activePeriode ? activePeriode.tahun_pelajaran : '-'}</td></tr>
                                                </table>
                                            </div>
                                        </div>
                                        <hr />
                                        <div class="table-responsive mt-2">
                                            <table class="table table-sm table-bordered">
                                                <thead>
                                                    <tr>
                                                        <th style="width:5%; text-align:center">NO</th>
                                                        <th style="width:25%; text-align:center">Mata Pelajaran</th>
                                                        <th style="width:10%; text-align:center">Nilai Akhir</th>
                                                        <th style="width:60%; text-align:center">Capaian Kompetensi</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                `;
                            // fetch data per peserta/kelas from server
                            const kelasId = kelasSel.value;
                            fetch('/admin/dokumen/rapot/data?peserta_id=' + encodeURIComponent(pesertaId) + '&kelas_id=' + encodeURIComponent(kelasId), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                                .then(r => r.json())
                                .then(data => {
                                    let html = htmlStart;
                                    const mataList = data.mata || [];
                                    const penRows = data.penilaian || [];
                                    if (mataList.length === 0) {
                                        html += `<tr><td colspan="4" class="text-center">Tidak ada daftar mata pelajaran untuk kelas ini.</td></tr>`;
                                    } else {
                                        mataList.forEach((m, idx) => {
                                            const found = penRows.find(pr => String(pr.mata_id) === String(m.id));
                                            const descText = found ? (found.deskripsi || '-') : '-';
                                            const descSafe = String(descText)
                                                .replace(/\b(mampu)\b/gi, '<strong>$1</strong>')
                                                .replace(/\b(perlu perhatian)\b/gi, '<strong>$1</strong>');
                                            html += `<tr>`+
                                                `<td style="text-align:center">${idx+1}</td>`+
                                                `<td>${m.nama || '-'}</td>`+
                                                `<td style="text-align:center">${found && (found.nilai_akhir !== null) ? found.nilai_akhir : '-'}</td>`+
                                                `<td>${descSafe}</td>`+
                                            `</tr>`;
                                        });
                                    }

                                    html += `
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            `;

                                            // kokurikuler paragraph (aggregated)
                                            const kokuriText = data.kokurikuler || null;
                                            if (kokuriText) {
                                                html += `
                                                    <div style="border:1px solid #000; margin-top:12px; margin-bottom:8px;">
                                                        <div style="background:#f0f0f0; text-align:center; padding:6px; font-weight:bold; border-bottom:1px solid #000">Kokurikuler</div>
                                                        <div style="padding:8px; font-size:11px;">${kokuriText}</div>
                                                    </div>`;
                                            }

                                            // after main table, append ekstrakulikuler table
                                            let ekstraList = data.ekstrakulikuler || [];
                                            // sort by kategori order: wajib 1, wajib 2, wajib 3, pilihan
                                            try {
                                                const orderMap = { 'wajib 1': 1, 'wajib 2': 2, 'wajib 3': 3, 'pilihan': 4 };
                                                ekstraList.sort((a,b) => {
                                                    const ka = (a.kategori||a.kat||'').toString().toLowerCase().trim();
                                                    const kb = (b.kategori||b.kat||'').toString().toLowerCase().trim();
                                                    const oa = orderMap[ka] || 5;
                                                    const ob = orderMap[kb] || 5;
                                                    if (oa !== ob) return oa - ob;
                                                    const na = (a.ekstrakulikuler||a.nama||'').toString().toLowerCase();
                                                    const nb = (b.ekstrakulikuler||b.nama||'').toString().toLowerCase();
                                                    return na < nb ? -1 : (na > nb ? 1 : 0);
                                                });
                                            } catch(e) { /* ignore */ }
                                            if (ekstraList.length > 0) {
                                                let ekstraHtml = `
                                                    <div style="border:1px solid #000; margin-top:12px; margin-bottom:8px;">
                                                        <table class="ekstra-table" style="width:100%; border-collapse:collapse; font-size:11px;">
                                                            <thead>
                                                                            <tr>
                                                                                <th style="width:5%; text-align:center; background:#f0f0f0; border:1px solid #000;">NO</th>
                                                                                <th style="text-align:center; background:#f0f0f0; border:1px solid #000;">Ekstrakulikuler</th>
                                                                                <th style="text-align:center; background:#f0f0f0; border:1px solid #000;">Keterangan</th>
                                                                            </tr>
                                                                        </thead>
                                                            <tbody>`;
                                                ekstraList.forEach((e, idx) => {
                                                    const nama = e.ekstrakulikuler || (e.demensi || '-');
                                                    const desc = e.deskripsi || e.keterangan || '-';
                                                    ekstraHtml += `<tr>`+
                                                        `<td style="text-align:center; border:1px solid #000;">${idx+1}</td>`+
                                                        `<td style="border:1px solid #000;">${nama}</td>`+
                                                        `<td style="border:1px solid #000;">${desc}</td>`+
                                                    `</tr>`;
                                                });
                                                ekstraHtml += `</tbody></table></div>`;
                                                html += ekstraHtml;

                                                // attendance + wali kelas notes (preview)
                                                html += `
                                                            <div class="row mt-3">
                                                        <div class="col-md-6">
                                                            <table class="table table-bordered small absensi-table">
                                                                <thead><tr><th colspan="3" class="text-center" style="background:#f0f0f0; border:1px solid #000">Ketidakhadiran</th></tr></thead>
                                                                <tbody>
                                                                    <tr><td>Sakit</td><td class="text-center">${ (data.absensi && (data.absensi.sakit !== undefined)) ? data.absensi.sakit : '-' }</td><td>hari</td></tr>
                                                                    <tr><td>Izin</td><td class="text-center">${ (data.absensi && (data.absensi.izin !== undefined)) ? data.absensi.izin : '-' }</td><td>hari</td></tr>
                                                                    <tr><td>Tanpa Keterangan</td><td class="text-center">${ (data.absensi && (data.absensi.tanpa_keterangan !== undefined)) ? data.absensi.tanpa_keterangan : '-' }</td><td>hari</td></tr>
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <table class="table table-bordered small wali-table">
                                                                <thead><tr><th style="background:#f0f0f0; border:1px solid #000">Catatan Wali Kelas</th></tr></thead>
                                                                <tbody><tr><td style="height:110px"></td></tr></tbody>
                                                            </table>
                                                        </div>
                                                    </div>
                                                `;
                                            }

                                            // use server-provided tanggal_rapot when available
                                            const sekolahInfo = data.sekolah || {};
                                            const guruInfo = data.guru || {};
                                            const tanggal_rapot = data.tanggal_rapot || '-';

                                            html += `<div style="margin-top:10px; text-align:right; font-size:11px;">${tanggal_rapot}</div>`;

                                            html += `
                                                <div class="row mt-4" style="font-size:11px;">
                                                    <div class="col-md-4 text-center">
                                                        <div>Mengetahui,</div>
                                                        <div>Orangtua / Wali Murid</div>
                                                        <div style="height:70px"></div>
                                                        <div style="text-decoration:underline; font-weight:bold">${pesertaObj ? (pesertaObj.nama_ayah || '-') : '-'}</div>
                                                    </div>
                                                    <div class="col-md-4 text-center">
                                                        <div>Mengetahui,</div>
                                                        <div>Kepala Sekolah</div>
                                                        <div style="height:70px"></div>
                                                        <div style="text-decoration:underline; font-weight:bold">${sekolahInfo.kepala_sekolah || (sekolah ? (sekolah.nama || '-') : '-')}</div>
                                                        <div>NIP: ${sekolahInfo.nip || '-'}</div>
                                                    </div>
                                                    <div class="col-md-4 text-center">
                                                        <div style="margin-top:15px">Wali Kelas</div>
                                                        <div style="height:70px"></div>
                                                        <div style="text-decoration:underline; font-weight:bold">${guruInfo.nama || '-'}</div>
                                                        <div>NIP: ${guruInfo.nip || '-'}</div>
                                                    </div>
                                                </div>
                                            `;

                                            container.innerHTML = html;
                                    container.scrollIntoView({ behavior: 'smooth' });

                                    document.getElementById('btnClosePreview').addEventListener('click', function(){
                                        container.innerHTML = '';
                                    });

                                    document.getElementById('btnPrint').addEventListener('click', function(){
                                        const url = '/admin/dokumen/rapot/cetak?peserta_id=' + encodeURIComponent(pesertaId) + '&kelas=' + encodeURIComponent(kelasSel.value || '');
                                        window.open(url, '_blank');
                                    });
                                }).catch(err => {
                                    alert('Gagal memuat data penilaian.');
                                });
                            
                        });
                    })();
                </script>
            </div>
        </div>
    </div>
</div>
@endsection