<div class="content-wrapper bg-white pt-4">
    <section class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-6">
                    <h1><?= $judul ?></h1>
                </div>
                <div class="col-6">
                    <a href="<?= base_url('cbtcetak') ?>" type="button" class="btn btn-sm btn-danger float-right">
                        <i class="fas fa-arrow-circle-left"></i><span
                                class="d-none d-sm-inline-block ml-1">Kembali</span>
                    </a>
                </div>
            </div>
        </div>
    </section>

    <section class="content">
        <div class="container-fluid">
            <div class="card my-shadow">
                <div class="card-header">
                    <h6 class="card-title">Setting Kop</h6>
                    <button class="card-tools btn btn-sm bg-primary text-white" onclick="submitKop()">
                        <i class="fas fa-save mr-1"></i> Simpan
                    </button>
                </div>
                <div class="card-body">
                    <?= form_open('', array('id' => 'set-kop')) ?>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Header 1</label>
                                <textarea id="header-1" class="form-control" name="header_1" rows="2"
                                          placeholder="Header baris 1"
                                          required><?= isset($kop->header_1) ? $kop->header_1 : '' ?></textarea>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Header 2</label>
                                <textarea id="header-2" class="form-control" name="header_2" rows="2"
                                          placeholder="Header baris 2"
                                          required><?= isset($kop->header_2) ? $kop->header_2 : '' ?></textarea>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Header 3</label>
                                <textarea id="header-3" class="form-control" name="header_3" rows="2"
                                          placeholder="Header baris 3"
                                          required><?= isset($kop->header_3) ? $kop->header_3 : '' ?></textarea>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Header 4</label>
                                <textarea id="header-4" class="form-control" name="header_4" rows="2"
                                          placeholder="Header baris 4"
                                          required><?= isset($kop->header_4) ? $kop->header_4 : '' ?></textarea>
                            </div>
                        </div>
                    </div>
                    <?= form_close() ?>
                </div>
            </div>

            <div class="card my-shadow">
                <div class="card-header">
                    <div class="card-title">
                        <h6>Cetak Sekaligus</h6>
                    </div>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-12 col-sm-5 mb-3" id="by-mapel">
                            <label>Mapel</label>
                            <?php
                            echo form_dropdown('mapel', $mapel_jadwal, null, 'id="mapel" class="form-control"'); ?>
                        </div>
                        <div class="col-sm-3 col-6 mb-3 pb-2 align-self-end">
                            <div id="loading-page" class="d-none">
                                <i class="fa fa-spinner fa-spin mr-2"></i> Memuat...
                            </div>
                            <div id="info-page" class="d-none"></div>
                        </div>
                        <div class="col-sm-4 col-6 mb-3 align-self-end text-right">
                            <button class="btn bg-success text-white" id="btn-print-all">
                                <i class="fa fa-print"></i><span class="ml-1">Cetak Semua</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card my-shadow">
                <div class="card-header">
                    <div class="card-title">
                        <h6>Cetak</h6>
                    </div>
                    <div id="selector" class="card-tools btn-group">
                        <button type="button" class="btn active btn-primary">By Ruang</button>
                        <button type="button" class="btn btn-outline-primary">By Kelas</button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-6 col-sm-3 d-none" id="by-kelas">
                            <label>Kelas</label>
                            <?php
                            echo form_dropdown(
                                'kelas',
                                $kelas,
                                null,
                                'id="kelas" class="form-control"'
                            ); ?>
                        </div>
                        <div class="col-6 col-sm-3" id="by-ruang">
                            <label>Ruang</label>
                            <?php
                            echo form_dropdown(
                                'ruang',
                                $ruang,
                                null,
                                'id="ruang" class="form-control"'
                            ); ?>
                        </div>
                        <div class="col-6 col-sm-3">
                            <label>Sesi</label>
                            <?php
                            echo form_dropdown(
                                'sesi',
                                $sesi,
                                null,
                                'id="sesi" class="form-control"'
                            ); ?>
                        </div>
                        <div class="col-6 col-md-3 mb-3">
                            <label>Jadwal</label>
                            <?php
                            echo form_dropdown('mapel', $mapel_jadwal, null, 'id="mapel-jadwal" class="form-control"');
                            ?>
                        </div>
                        <div class="col-6 col-md-3 mb-3 d-none" id="select-tgl">
                            <label>Tanggal</label>
                            <select name="tanggal" id="mapel-tgl" class="form-control select2"></select>
                        </div>
                    </div>
                    <hr>
                    <div class="d-flex justify-content-between">
                        <div class="flex-grow-1 mr-3">
                            <div class="alert alert-default-danger d-none" id="empty-jadwal">
                            </div>
                        </div>
                        <div class="text-right">
                            <button class="btn bg-success text-white" id="btn-print">
                                <i class="fa fa-print"></i><span class="ml-1">Cetak</span>
                            </button>
                        </div>
                    </div>
                    <br>
                    <div class="p-4 bg-gray-light">
                        <div style="display: flex; justify-content: center; align-items: center;">
                            <div id="print-preview" style="width: 21cm; min-height: 29cm;" class="border my-shadow p-5 bg-white">
                                <table id="table-header-print"
                                       style="width: 100%; border: 0;">
                                    <tr>
                                        <td style="width:15%;">
                                            <img alt="logo kiri" id="prev-logo-kanan-print"
                                                 src="<?= isset($kop->logo_kiri) ? base_url() . $kop->logo_kiri : '' ?>"
                                                 style="width:85px; height:85px; margin: 6px;">
                                        </td>
                                        <td style="width:70%; text-align: center;">
                                            <div style="line-height: 1.1; font-family: 'Times New Roman'; font-size: 14pt"><?= isset($kop->header_1) ? $kop->header_1 : '' ?></div>
                                            <div style="line-height: 1.1; font-family: 'Times New Roman'; font-size: 16pt">
                                                <b><?= isset($kop->header_2) ? $kop->header_2 : '' ?></b></div>
                                            <div style="line-height: 1.2; font-family: 'Times New Roman'; font-size: 13pt"><?= isset($kop->header_3) ? $kop->header_3 : '' ?></div>
                                            <div style="line-height: 1.2; font-family: 'Times New Roman'; font-size: 12pt"><?= isset($kop->header_4) ? $kop->header_4 : '' ?></div>
                                        </td>
                                        <td style="width:15%;">
                                            <img alt="logo kanan" id="prev-logo-kiri-print"
                                                 src="<?= isset($kop->logo_kanan) ? base_url() . $kop->logo_kanan : '' ?>"
                                                 style="width:85px; height:85px; margin: 6px; border-style: none">
                                        </td>
                                    </tr>
                                </table>
                                <hr style="border: 1px solid; margin-bottom: 6px">
                                <br>
                                <br>
                                <div style="text-align: justify; font-family: 'Times New Roman'">
                                    Pada hari ini <span class="editable bg-gray-light" id="edit-hari"
                                                        style="display: inline-block;min-width: 20px"><?= buat_tanggal(date('D')) ?></span>
                                    tanggal <span class="editable bg-gray-light" id="edit-tanggal"
                                                  style="display: inline-block;min-width: 20px"><?= buat_tanggal(date('d')) ?></span>
                                    bulan <span class="editable bg-gray-light" id="edit-bulan"
                                                style="display: inline-block;min-width: 20px"><?= buat_tanggal(date('M')) ?></span>
                                    tahun <span class="editable bg-gray-light" id="edit-tahun"
                                                style="display: inline-block;min-width: 20px"><?= buat_tanggal(date('Y')) ?></span>
                                    telah diselenggarakan <span class="editable bg-gray-light" id="edit-jenis-ujian"
                                                                style="display: inline-block;min-width: 20px">............................................</span>
                                    untuk Mata Pelajaran <span class="editable bg-gray-light" id="edit-mapel"
                                                               style="display: inline-block;min-width: 20px">.....................................</span>
                                    dari pukul <span class="editable bg-gray-light" id="edit-waktu-mulai"
                                                     style="display: inline-block;min-width: 20px">.............</span>
                                    sampai dengan pukul <span class="editable bg-gray-light" id="edit-waktu-akhir"
                                                              style="display: inline-block;min-width: 20px">...........</span>
                                </div>
                                <br>
                                <table style="width: 100%;font-family: 'Times New Roman';">
                                    <tr>
                                        <td style="width: 30px;">1.</td>
                                        <td style="width: 30%;">
                                            Pada Sekolah/Madrasah
                                        </td>
                                        <td>:</td>
                                        <td class="editable bg-gray-light"
                                            id="edit-nama_sekolah"><?= isset($kop->sekolah) ? $kop->sekolah : '' ?></td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                        <td id="title-ruang">
                                            Ruang
                                        </td>
                                        <td>:</td>
                                        <td class="editable bg-gray-light" id="edit-ruang">
                                            .................................................................
                                        </td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                        <td>Sesi</td>
                                        <td>:</td>
                                        <td class="editable bg-gray-light" id="edit-sesi">
                                            .................................................................
                                        </td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                        <td>
                                            Jumlah Peserta Seharusnya
                                        </td>
                                        <td>:</td>
                                        <td class="editable bg-gray-light" id="edit-jml-peserta">
                                            .................................................................
                                        </td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                        <td>
                                            Jumlah Peserta Hadir
                                        </td>
                                        <td>:</td>
                                        <td class="editable bg-gray-light" id="edit-hadir">
                                            .................................................................
                                        </td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                        <td>
                                            Jumlah Peserta Tidak Hadir
                                        </td>
                                        <td>:</td>
                                        <td class="editable bg-gray-light" id="edit-tidak-hadir">
                                            .................................................................
                                        </td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                        <td>
                                            Nomor Peserta Tidak Hadir
                                        </td>
                                        <td>:</td>
                                        <td class="editable bg-gray-light" id="edit-username">
                                            .................................................................
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="padding-top: 12px">2.</td>
                                        <td style="padding-top: 12px" colspan="3">
                                            Catatan selama <span class="editable bg-gray-light" id="edit-nama-ujian"
                                                                 style="display: inline-block;min-width: 20px">.......</span>
                                            berlangsung :
                                        </td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                        <td colspan="3" style="height: 100px; border: 1px solid black; padding: 12px"
                                            class="editable bg-gray-light" id="edit-catatan"></td>
                                    </tr>
                                </table>
                                <br>
                                <br>
                                <br>
                                <br>
                                <div id="berita-ttd">
                                    <table style="width:90%; font-family: 'Times New Roman';">
                                        <tr>
                                            <th></th>
                                            <th></th>
                                            <th></th>
                                            <th></th>
                                            <th style="text-align: center">TTD</th>
                                        </tr>
                                        <tr>
                                            <td style="width: 30px;">1.</td>
                                            <td>Pengawas 1</td>
                                            <td>:</td>
                                            <td class="editable bg-gray-light" id="edit-pengawas1">_________________________</td>
                                            <td style="padding-left: 20px" rowspan="2">1. _________________________</td>
                                        </tr>
                                        <tr>
                                            <td></td>
                                            <td>
                                                NIP/NUPTK
                                            </td>
                                            <td>:</td>
                                            <td class="editable bg-gray-light">_________________________</td>
                                        </tr>
                                        <tr>
                                            <td style="padding-top: 12px">2.</td>
                                            <td style="padding-top: 12px">Pengawas 2</td>
                                            <td style="padding-top: 12px">:</td>
                                            <td style="padding-top: 12px" class="editable bg-gray-light" id="edit-pengawas2">_________________________</td>
                                            <td style="padding-left: 20px" rowspan="2">2. _________________________</td>
                                        </tr>
                                        <tr>
                                            <td></td>
                                            <td>
                                                NIP/NUPTK
                                            </td>
                                            <td>:</td>
                                            <td class="editable bg-gray-light">_________________________</td>
                                        </tr>
                                        <tr>
                                            <td style="padding-top: 12px">3.</td>
                                            <td style="padding-top: 12px">
                                                Kepala Sekolah
                                            </td>
                                            <td style="padding-top: 12px">:</td>
                                            <td style="padding-top: 12px"
                                                class="editable bg-gray-light"><?= isset($kop->kepsek) && $kop->kepsek != '' ? $kop->kepsek : '_________________________' ?></td>
                                            <td style="padding-left: 20px" rowspan="2">3. _________________________</td>
                                        </tr>
                                        <tr>
                                            <td></td>
                                            <td>
                                                NIP/NUPTK
                                            </td>
                                            <td>:</td>
                                            <td class="editable bg-gray-light"><?= isset($kop->nip) && $kop->nip != '' ? $kop->nip : '_________________________' ?></td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="overlay d-none" id="loading">
                    <div class="spinner-grow"></div>
                </div>
            </div>

            <div id="all-print-preview" class="m-4 d-none"></div>
        </div>
    </section>
</div>

<script src="<?= base_url() ?>/assets/app/js/print-area.js"></script>

<script>
    (function($) {
        // --- 1. KONFIGURASI DAN STATE ---
        const config = {
            baseUrl: typeof base_url !== 'undefined' ? base_url : '',
            kop: {
                kepsek: "<?= isset($kop->kepsek) && $kop->kepsek != "" ? $kop->kepsek : "_________________________" ?>",
                nip: "<?= isset($kop->nip) && $kop->nip != "" ? $kop->nip : "_________________________" ?>",
                header1: "<?= $kop->header_1 ?? "" ?>",
                header2: "<?= $kop->header_2 ?? "" ?>",
                header3: "<?= $kop->header_3 ?? "" ?>",
                header4: "<?= $kop->header_4 ?? "" ?>"
            },
            allJadwal: JSON.parse(JSON.stringify(<?= json_encode($jadwal ?? []) ?>))
        };

        let state = {
            printBy: 1, // 1 = Ruang, 2 = Kelas
            currJadwal: [],
            arrSiswa: [],
            info: null
        };

        const DOM = {
            opsiMapel: $("#mapel"),
            opsiJadwal: $("#mapel-jadwal"),
            opsiRuang: $("#ruang"),
            opsiSesi: $("#sesi"),
            opsiKelas: $("#kelas"),
            opsiTgl: $('#select-tgl'),
            mplTgl: $('#mapel-tgl'),
            empty: $('#empty-jadwal'),
            loadingPage: $('#loading-page'),
            infoPage: $('#info-page'),
            allPrintPreview: $('#all-print-preview')
        };

        // --- 2. HELPER FUNCTIONS ---

        function handleNull(value) {
            return (value == null || value == "0" || value == "") ? "-" : value;
        }

        function handleTanggal(tgl) {
            const hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jum'at", "Sabtu"];
            const bulans = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"];

            if (handleNull(tgl) !== "-") {
                const d = new Date(tgl);
                return {
                    HARI: hari[d.getDay()],
                    TANGGAL: d.getDate(),
                    BULAN: bulans[d.getMonth()],
                    TAHUN: d.getFullYear(),
                }
            }
            return null;
        }

        function formatTanggal(dateString) {
            const date = new Date(dateString);
            return date.toLocaleDateString('id-ID', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
        }

        // Helper untuk membuat elemen DOM agar tidak terlalu verbose
        function createEl(tag, options = {}) {
            const el = document.createElement(tag);
            if (options.className) el.className = options.className;
            if (options.style) Object.assign(el.style, options.style);
            if (options.text) el.textContent = options.text;
            if (options.html) el.innerHTML = options.html;
            if (options.props) Object.keys(options.props).forEach(key => el[key] = options.props[key]);
            return el;
        }

        // --- 3. LOGIKA UTAMA ---
        function populateBeritaAcara(data) {
            console.log("response", data);
            DOM.allPrintPreview.html('');
            const kop = data.kop.kop_berita;
            const alokasiSesi = alokasiJam(data, true);
            let allPages = 0;

            for (const key in alokasiSesi) {
                for (const group of alokasiSesi[key]) {
                    const pageContainer = createEl('div', {
                        className: 'mb-3 bg-white page-print',
                        style: { width: "21cm", minHeight: "29cm", pageBreakAfter: 'always' }
                    });

                    // 1. Header Section
                    pageContainer.appendChild(createHeaderSection(kop));

                    // 2. Content Paragraph
                    const tgl = handleTanggal(group.jadwal.tgl_mulai);
                    const paragraph = createEl('div', {
                        style: { marginBottom: "12px", textAlign: "justify", fontFamily: "'Times New Roman'" },
                        html: `Pada hari ini <b>${tgl?.HARI}</b> tanggal <b>${tgl?.TANGGAL}</b> bulan <b>${tgl?.BULAN}</b> tahun <b>${tgl?.TAHUN}</b>
                        telah diselenggarakan <b>${group.jadwal.nama_jenis}</b> untuk Mata Pelajaran <b>${group.jadwal.nama_mapel}</b>
                        dari pukul <b>${group.dari}</b> sampai dengan pukul <b>${group.sampai}</b>`
                    });
                    pageContainer.appendChild(paragraph);

                    // 3. Data Table
                    const all_siswa_ruang = data.siswa.filter(e => group.ids_siswa.includes(e.id_siswa));
                    pageContainer.appendChild(createInfoTable(kop, group, all_siswa_ruang));

                    // 4. Signature Table
                    pageContainer.appendChild(createSignatureTable(group, kop));

                    DOM.allPrintPreview.append(pageContainer);
                    allPages++;
                }
            }

            DOM.loadingPage.addClass('d-none');
            DOM.infoPage.removeClass('d-none');
            DOM.infoPage.text(`${allPages} Halaman`);
            document.title = 'Berita Acara ' + DOM.opsiMapel.find('option:selected').text() + '.pdf';
        }

        function createHeaderSection(kop) {
            const table = createEl('table', { style: { width: "100%", border: "0" } });
            const row = createEl('tr');

            // Helper untuk membuat kolom logo
            const createLogoTd = (src) => {
                const td = createEl('td', { style: { width: "15%" } });
                const img = createEl('img', {
                    props: { src: config.baseUrl + src, alt: "logo" },
                    style: { width: "85px", height: "85px", margin: "6px" }
                });
                td.appendChild(img);
                return td;
            };

            // Helper untuk membuat teks header
            const createHeaderTd = (text, size, weight = 'normal') => {
                return createEl('div', {
                    style: { lineHeight: size < 14 ? "1.2" : "1.1", fontFamily: "'Times New Roman'", fontSize: size + "pt", fontWeight: weight },
                    text: text
                });
            };

            const centerTd = createEl('td', { style: { width: "70%", textAlign: "center" } });
            centerTd.appendChild(createHeaderTd(kop?.header_1 || 'Header 1', 14));
            centerTd.appendChild(createHeaderTd(kop?.header_2 || 'Header 2', 16, 'bold'));
            centerTd.appendChild(createHeaderTd(kop?.header_3 || 'Header 3', 13));
            centerTd.appendChild(createHeaderTd(kop?.header_4 || 'Header 4', 12));

            row.appendChild(createLogoTd(kop?.logo_kiri));
            row.appendChild(centerTd);
            row.appendChild(createLogoTd(kop?.logo_kanan));
            table.appendChild(row);

            const container = createEl('div');
            container.appendChild(table);
            container.appendChild(createEl('hr', { style: { border: "1px solid", marginBottom: "50px" } }));
            return container;
        }

        function createInfoTable(kop, group, siswaList) {
            const table = createEl('table', { style: { width: "100%", fontFamily: "'Times New Roman'" } });

            // Helper untuk baris data sederhana
            const addRow = (num, label, content) => {
                const tr = createEl('tr');
                tr.appendChild(createEl('td', { style: { width: "30px" }, text: num }));
                tr.appendChild(createEl('td', { style: { width: "30%" }, text: label }));
                tr.appendChild(createEl('td', { text: ":" }));
                tr.appendChild(createEl('td', { text: content }));
                table.appendChild(tr);
            };

            addRow("1.", "Pada Sekolah/Madrasah", kop?.sekolah || 'Nama Sekolah');
            addRow("", "Ruang", group.nama_ruang);
            addRow("", "Sesi", group.nama_sesi);
            addRow("", "Jumlah Peserta Seharusnya", siswaList.length);
            addRow("", "Jumlah Peserta Hadir", ".................................................................");
            addRow("", "Jumlah Peserta Tidak Hadir", ".................................................................");
            addRow("", "Nomor Peserta Tidak Hadir", ".................................................................");

            // Baris Catatan
            const noteRow = createEl('tr');
            noteRow.appendChild(createEl('td', { style: { paddingTop: "12px" }, text: "2." }));
            noteRow.appendChild(createEl('td', {
                props: { colSpan: "3" },
                style: { paddingTop: "12px" },
                html: `Catatan selama <b>${group.jadwal.nama_jenis}</b> berlangsung :`
            }));
            table.appendChild(noteRow);

            const noteRow2 = createEl('tr');
            noteRow2.appendChild(createEl('td')); // Kosong
            const noteCell = createEl('td', {
                props: { colSpan: "3" },
                style: { height: "100px", border: "1px solid black", padding: "12px" }
            });
            noteRow2.appendChild(noteCell);
            table.appendChild(noteRow2);

            return table;
        }

        function createSignatureTable(group, kop) {
            const table = createEl('table', { style: { width: "90%", fontFamily: "'Times New Roman'", marginTop: "100px" } });

            // Header TTD
            const headRow = createEl('tr');
            for (let i = 0; i < 5; i++) {
                const th = createEl('th', {
                    text: (i === 4 ? "TTD" : ""),
                    style: { textAlign: i === 4 ? "center" : "left" }
                });
                headRow.appendChild(th);
            }
            table.appendChild(headRow);

            let data = [
                { label: "Pengawas 1", val: group?.pengawas[0]?.nama_guru || 'Pengawas', nip: group?.pengawas[0]?.nip || '_________________________', id: "1." },
            ];

            if (group.pengawas[1]?.nama_guru) {
                data.push({ label: "Pengawas 2", val: group.pengawas[1].nama_guru, nip: group.pengawas[1].nip || '_________________________', id: "2." });
            }

            const kepalasekolahIdx = data.length + 1 > 2 ? "3." : "2.";
            data.push({ label: "Kepala Sekolah", val: kop?.kepsek, nip: kop?.nip || "_________________________", id: kepalasekolahIdx });

            data.forEach((item, index) => {
                const isHeader = index % 2 === 0;
                const paddingTop = isHeader ? "12px" : "0";

                const tr = createEl('tr');
                tr.appendChild(createEl('td', { style: { paddingTop }, text: item.id }));
                tr.appendChild(createEl('td', { style: { paddingTop }, text: item.label }));
                tr.appendChild(createEl('td', { style: { paddingTop }, text: ":" }));
                tr.appendChild(createEl('td', { style: { paddingTop }, text: item.val }));

                if (isHeader) {
                    const ttdCell = createEl('td', {
                        props: { rowSpan: 2 },
                        style: { paddingLeft: '20px' },
                        text: `${item.id} _________________________`
                    });
                    tr.appendChild(ttdCell);
                }

                table.appendChild(tr);

                // Baris NIP
                const nipTr = createEl('tr');
                nipTr.appendChild(createEl('td')); // No
                nipTr.appendChild(createEl('td', { text: "NIP/NUPTK" }));
                nipTr.appendChild(createEl('td', { text: ":" }));
                nipTr.appendChild(createEl('td', { text: item.nip }));
                table.appendChild(nipTr);
            });

            return table;
        }

        // --- 4. AJAX & DATA FETCHING ---
        function loadDataPeserta(type, idKelas, idRuang, idSesi, idMapel) {
            const isRuang = type === 'ruang';
            const url = config.baseUrl + (isRuang ? "cbtcetak/getruang" : "cbtcetak/getkelas");

            if ((!isRuang && !idKelas) || (isRuang && !idRuang) || !idSesi || !idMapel) return;

            $('#loading').removeClass('d-none');
            DOM.empty.addClass('d-none');
            DOM.opsiTgl.addClass('d-none');
            DOM.mplTgl.html('');

            const params = isRuang
                ? `?ruang=${idRuang}&sesi=${idSesi}&mapel=${idMapel}`
                : `?kelas=${idKelas}&sesi=${idSesi}&mapel=${idMapel}`;

            $.ajax({
                type: "GET",
                url: url + params,
                success: function (response) {
                    state.info = response.info;
                    state.arrSiswa = response.siswa;
                    $('#loading').addClass('d-none');

                    const sesi = response.info.sesi;
                    const ruang = response.info.ruang;
                    const kelas = response.info.kelas;

                    const alokasiJadwal = alokasiJam(response, false);
                    state.currJadwal = []; // Reset current jadwal

                    // Cari jadwal yang cocok
                    for (const tanggal in alokasiJadwal) {
                        const arrJadwal = alokasiJadwal[tanggal];
                        for (const jadwal of arrJadwal) {
                            let match = false;
                            if (isRuang) {
                                match = jadwal.id_mapel === response.info.mapel &&
                                    jadwal.sesi_id === sesi.id_sesi &&
                                    jadwal.ruang_id === ruang.id_ruang;
                            } else {
                                match = jadwal.kelas_id.includes(kelas.id_kelas) &&
                                    jadwal.id_mapel === response.info.mapel &&
                                    jadwal.sesi_id === sesi.id_sesi;
                            }

                            if (match) {
                                const found = state.currJadwal.find(e =>
                                    e.id_mapel === jadwal.id_mapel &&
                                    e.sesi_id === jadwal.sesi_id &&
                                    e.ruang_id === jadwal.ruang_id &&
                                    e.jadwal.tgl_mulai === jadwal.jadwal.tgl_mulai
                                );
                                if (!found) state.currJadwal.push(jadwal);
                            }
                        }
                    }

                    if (state.currJadwal.length === 0) {
                        const mapelText = DOM.opsiJadwal.find('option:selected').text();
                        const locText = isRuang
                            ? `${ruang.nama_ruang} (${ruang.kode_ruang})`
                            : kelas.nama_kelas;

                        DOM.empty.html(`Tidak ada jadwal <b>${mapelText}</b> untuk ${isRuang ? 'Ruang' : 'Kelas'} <b>${locText}</b> sesi <b>${sesi.nama_sesi}</b>`);
                        DOM.empty.removeClass('d-none');
                        return;
                    }

                    if (state.currJadwal.length > 1) {
                        DOM.opsiTgl.removeClass('d-none');
                        DOM.mplTgl.prepend("<option value='' selected='selected'>Pilih Tanggal</option>");
                        state.currJadwal.forEach(j => {
                            DOM.mplTgl.append(`<option value="${j.jadwal.tgl_mulai}">${formatTanggal(j.jadwal.tgl_mulai)}</option>`);
                        });
                    } else {
                        applyJadwal(state.currJadwal[0]);
                    }
                },
                error: function (xhr) {
                    $('#loading').addClass('d-none');
                    console.error("Error:", xhr.responseText);
                }
            });
        }

        function loadAllSiswaRuang(mapel) {
            if (!mapel) return;
            DOM.loadingPage.removeClass('d-none');
            DOM.infoPage.addClass('d-none');

            setTimeout(function () {
                $.ajax({
                    type: "GET",
                    url: config.baseUrl + "cbtcetak/getalljadwal?mapel=" + mapel,
                    success: function (response) {
                        populateBeritaAcara(response);
                    },
                    error: function (xhr) {
                        DOM.loadingPage.addClass('d-none');
                        DOM.infoPage.removeClass('d-none');
                        DOM.infoPage.text(`Error`);
                        console.error("Error", xhr.responseText);
                    }
                });
            }, 500);
        }

        // --- 5. ALGORITMA ALOKASI JAM (Dikumpulkan namun Logika Dipertahankan) ---
        function alokasiJam(data, is_all) {
            const timeToMinutes = (time) => {
                if (!time || !time.includes(':')) return 0;
                const [h, m] = time.split(':').map(Number);
                return h * 60 + m;
            };
            const minutesToTime = (totalMinutes) => {
                const hours = Math.floor(totalMinutes / 60);
                const minutes = totalMinutes % 60;
                return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
            };

            const sesis = Array.isArray(data.all_ruang) ? data.all_ruang : [];
            const results = processAndGroupData(data, is_all);
            const resultsArray = {};

            for (const key in results) {
                resultsArray[key] = [];
                const alokasi = results[key];

                // Jika tidak ada alokasi sama sekali, skip
                if (!alokasi.alokasi || alokasi.alokasi.length === 0) {
                    continue;
                }

                const mapelByJamKe = {};

                // PERUBAHAN: Normalisasi jam_ke di sini sebelum diproses
                alokasi.alokasi.forEach(mapel => {
                    let jamKe = mapel.jam_ke;

                    // Jika jam_ke adalah 0, null, atau string kosong, kita paksa menjadi '1'
                    // Ini agar data tetap muncul di jam pertama.
                    if (!jamKe || jamKe == 0) {
                        jamKe = '1';
                    }

                    if (!mapelByJamKe[jamKe]) {
                        mapelByJamKe[jamKe] = [];
                    }

                    mapelByJamKe[jamKe].push({
                        ...mapel,
                        ...alokasi.ruang_sesi,
                        siswa: alokasi.siswaRuang,
                        // Update jam_ke di object mapel agar sinkron dengan key mapelByJamKe
                        jam_ke: jamKe
                    });
                });

                // Hitung maxJamKe berdasarkan jam_ke yang sudah dinormalisasi
                const jamKeys = Object.keys(mapelByJamKe).map(Number);
                let maxJamKe = jamKeys.length > 0 ? Math.max(...jamKeys) : 1;

                sesis.forEach(sesi => {
                    const totalDuration = timeToMinutes(sesi.waktu_akhir) - timeToMinutes(sesi.waktu_mulai);

                    // Hitung durasi per slot
                    const durationPerSlot = totalDuration / maxJamKe;

                    // Loop dari 1 sampai maxJamKe
                    for (let i = 1; i <= maxJamKe; i++) {
                        const jamKe = String(i);
                        const startMinutes = timeToMinutes(sesi.waktu_mulai) + (i - 1) * durationPerSlot;
                        const start_time = minutesToTime(startMinutes);
                        const end_time = minutesToTime(startMinutes + durationPerSlot);

                        if (mapelByJamKe[jamKe]) {
                            mapelByJamKe[jamKe].forEach(mapel => {
                                const found = resultsArray[key].find(m =>
                                    m.jadwal?.id_jadwal === mapel.jadwal.id_jadwal &&
                                    m?.jam_ke === mapel.jam_ke
                                );

                                if (!found) {
                                    resultsArray[key].push({
                                        ...mapel,
                                        dari: start_time,
                                        sampai: end_time,
                                        durasi: durationPerSlot
                                    });
                                }
                            });
                        }
                    }
                });
            }
            return resultsArray;
        }

        function processAndGroupData(data, is_all) {
            const allSesi = data.all_ruang || [];
            const jsonData = data.all_tgl || [];
            const grouped = {};

            for (const tgl in jsonData) {
                jsonData[tgl].forEach(jadwal => {
                    jadwal.bank_kelas = jadwal.bank_kelas.map(String);
                    const ruangFiltered = allSesi.filter(r => r.kelas_id.some(id => jadwal.bank_kelas.includes(id.toString())));

                    ruangFiltered.forEach(ruang => {
                        const siswaRuang = data.siswa.filter(s => {
                            if (is_all) {
                                return s.ruang_id === ruang.ruang_id && s.sesi_id === ruang.sesi_id && jadwal.bank_kelas.includes(s.id_kelas);
                            } else {
                                if (config.printBy === 2) {
                                    return s.sesi_id === ruang.sesi_id && jadwal.bank_kelas.includes(s.id_kelas);
                                } else {
                                    return s.ruang_id === ruang.ruang_id && s.sesi_id === ruang.sesi_id && jadwal.bank_kelas.includes(s.id_kelas);
                                }
                            }
                        });

                        const key = `${tgl}-${ruang.ruang_id}-${ruang.sesi_id}`;
                        if (!grouped[key]) {
                            grouped[key] = { key, ruang_sesi: ruang, siswaRuang, jam_ke: [], id_mapel: [], alokasi: [] };
                        }

                        if (!grouped[key].id_mapel.includes(jadwal.id_mapel)) grouped[key].id_mapel.push(jadwal.id_mapel);

                        //const pengawasJadwal = data.all_pengawas.find(p => p.id_jadwal === jadwal.id_jadwal && p.id_ruang === ruang.ruang_id && p.id_sesi === ruang.sesi_id) || { guru: [], id_guru: '', jam_ke: '' };
                        const pengawasJadwal = (data.all_pengawas || []).find(p =>
                            p.id_jadwal === jadwal.id_jadwal &&
                            p.id_ruang === ruang.ruang_id &&
                            p.id_sesi === ruang.sesi_id
                        ) || {
                            pengawas: [],      // Penting: Default array kosong agar render tabel tidak error
                            jam_ke: jadwal.jam_ke || '1', // Ambil jam_ke dari jadwal jika tersedia
                            id_guru: ''
                        };

                        if (!grouped[key].jam_ke.includes(pengawasJadwal.jam_ke)) grouped[key].jam_ke.push(pengawasJadwal.jam_ke);

                        if (!grouped[key].alokasi.find(a => a.id_mapel === jadwal.id_mapel && a.jam_ke === jadwal.jam_ke)) {
                            grouped[key].alokasi.push({ id_mapel: jadwal.id_mapel, nama_mapel: jadwal.nama_mapel, jam_ke: pengawasJadwal.jam_ke, pengawas: pengawasJadwal.pengawas, jadwal });
                        }
                    });
                });
            }
            return grouped;
        }

        // --- 6. LOGIKA UI & EVENT HANDLERS ---
        function applyJadwal(jadwal) {
            const tgl = handleTanggal(jadwal.jadwal.tgl_mulai);
            const all_siswa_ruang = state.arrSiswa.filter(e => jadwal.ids_siswa.includes(e.id_siswa));

            // Update DOM elements
            $('#edit-hari').html('<b>' + tgl.HARI + '</b>');
            $('#edit-tanggal').html('<b>' + tgl.TANGGAL + '</b>');
            $('#edit-bulan').html('<b>' + tgl.BULAN + '</b>');
            $('#edit-tahun').html('<b>' + tgl.TAHUN + '</b>');
            $('#edit-jml-peserta').html('<b>' + all_siswa_ruang.length + '</b>');

            $('#edit-jenis-ujian').html('<b>' + jadwal.jadwal.nama_jenis + '</b>');
            $('#edit-nama-ujian').html('<b>' + jadwal.jadwal.nama_jenis + '<b>');
            $('#edit-waktu-mulai').html('<b>' + jadwal.dari + '</b>');
            $('#edit-waktu-akhir').html('<b>' + jadwal.sampai + '</b>');
            $('#edit-mapel').html('<b>' + jadwal.jadwal.nama_mapel + '</b>');

            previewTTD(jadwal.pengawas);
            document.title = 'Berita Acara ' + jadwal.jadwal.kode + ' ' + $('#edit-ruang').text() + ' ' + $('#edit-sesi').text();
        }

        function previewTTD(pengawas) {
            let nomor = 1;
            const p1 = pengawas[0] || {};
            const p2 = pengawas[1] || {};
            const hasP2 = !!pengawas[1];

            const title_p1 = hasP2 ? 'Pengawas 1' : 'Pengawas';

            let table = `
                <table style="width:90%; font-family: 'Times New Roman';">
                    <tr>
                        <th></th><th></th><th></th><th></th>
                        <th style="text-align: center">TTD</th>
                    </tr>
                    <tr>
                        <td style="width: 30px;">1.</td>
                        <td>${title_p1}</td>
                        <td>:</td>
                        <td class="editable bg-gray-light" id="edit-pengawas1">${p1.nama_guru || ''}</td>
                        <td style="padding-left: 20px" rowspan="2">1. _________________________</td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>NIP/NUPTK</td>
                        <td>:</td>
                        <td class="editable bg-gray-light">${p1.nip || '_________________________'}</td>
                    </tr>
            `;

            if (hasP2) {
                nomor = 2;
                table += `
                    <tr>
                        <td style="padding-top: 12px">2.</td>
                        <td style="padding-top: 12px">Pengawas 2</td>
                        <td style="padding-top: 12px">:</td>
                        <td style="padding-top: 12px" class="editable bg-gray-light" id="edit-pengawas2">${p2.nama_guru}</td>
                        <td style="padding-left: 20px" rowspan="2">2. _________________________</td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>NIP/NUPTK</td>
                        <td>:</td>
                        <td class="editable bg-gray-light">${p2.nip || '_________________________'}</td>
                    </tr>
                `;
            }

            const ksNomor = hasP2 ? 3 : 2;
            table += `
                <tr>
                    <td style="padding-top: 12px">${ksNomor}.</td>
                    <td style="padding-top: 12px">Kepala Sekolah</td>
                    <td style="padding-top: 12px">:</td>
                    <td style="padding-top: 12px" class="editable bg-gray-light">${config.kop.kepsek}</td>
                    <td style="padding-left: 20px" rowspan="2">${ksNomor}. _________________________</td>
                </tr>
                <tr>
                    <td></td>
                    <td>NIP/NUPTK</td>
                    <td>:</td>
                    <td class="editable bg-gray-light">${config.kop.nip}</td>
                </tr>
            </table>`;

            $('#berita-ttd').html(table);
            $('.editable').attr('contentEditable', true);
        }

        function submitKop() {
            $('#set-kop').submit();
        }

        // --- 7. INITIALIZATION ---
        $(document).ready(function () {
            ajaxcsrf();

            // Inisialisasi Select2
            DOM.opsiKelas.select2({ width: '100%', theme: 'bootstrap4' });
            DOM.opsiRuang.select2({ width: '100%', theme: 'bootstrap4' });
            DOM.opsiSesi.select2({ width: '100%', theme: 'bootstrap4' });
            DOM.opsiJadwal.select2({ width: '100%', theme: 'bootstrap4' });

            // Default Select Option
            const defaultOption = "<option value='' selected='selected'>Pilih [LABEL]</option>";
            DOM.opsiMapel.prepend(defaultOption.replace('[LABEL]', 'Mapel'));
            DOM.opsiJadwal.prepend(defaultOption.replace('[LABEL]', 'Jadwal'));
            DOM.opsiRuang.prepend(defaultOption.replace('[LABEL]', 'Ruang'));
            DOM.opsiSesi.prepend(defaultOption.replace('[LABEL]', 'Sesi'));
            DOM.opsiKelas.prepend(defaultOption.replace('[LABEL]', 'Kelas'));

            $('.editable').attr('contentEditable', true);

            // Event Listeners

            // 1. Load All Siswa Ruang (Berita Acara Global)
            DOM.opsiMapel.change(function () {
                loadAllSiswaRuang($(this).val());
            });

            // 2. Load Data Peserta Per Ruang/Kelas
            DOM.opsiKelas.change(function () {
                $('#edit-ruang').text($(this).find('option:selected').text());
                loadDataPeserta('kelas', $(this).val(), null, DOM.opsiSesi.val(), DOM.opsiJadwal.val());
            });

            DOM.opsiRuang.change(function () {
                $('#edit-ruang').text($(this).find('option:selected').text());
                loadDataPeserta('ruang', null, $(this).val(), DOM.opsiSesi.val(), DOM.opsiJadwal.val());
            });

            DOM.opsiSesi.change(function () {
                $('#edit-sesi').text($(this).find('option:selected').text());
                if (state.printBy === 1) {
                    loadDataPeserta('ruang', null, DOM.opsiRuang.val(), $(this).val(), DOM.opsiJadwal.val());
                } else {
                    loadDataPeserta('kelas', DOM.opsiKelas.val(), null, $(this).val(), DOM.opsiJadwal.val());
                }
            });

            DOM.opsiJadwal.change(function () {
                if (state.printBy === 1) {
                    loadDataPeserta('ruang', null, DOM.opsiRuang.val(), DOM.opsiSesi.val(), $(this).val());
                } else {
                    loadDataPeserta('kelas', DOM.opsiKelas.val(), null, DOM.opsiSesi.val(), $(this).val());
                }
            });

            DOM.mplTgl.on('change', function () {
                const tgl = $(this).val();
                const jadwalSelected = state.currJadwal.find(e => e.jadwal.tgl_mulai === tgl);
                if (jadwalSelected) {
                    applyJadwal(jadwalSelected, state.info);
                }
            });

            // 3. Print Buttons
            $("#btn-print-all").click(async function () {
                if (!DOM.opsiMapel.val()) {
                    Swal.fire({ title: "ERROR", text: "Isi Mapel terlebih dulu", icon: "error" });
                    return;
                }
                DOM.allPrintPreview.print(document.title);
            });

            $("#btn-print").click(function () {
                $('#print-preview').print(document.title);
            });

            // 4. Header Inputs Change Events (Refactored Loop)
            ['header-1', 'header-2', 'header-3', 'header-4'].forEach((id, index) => {
                $(`#${id}`).on("change keyup paste", function () {
                    // Logic update jika diperlukan, saat ini hanya tracking value lama
                    // Di versi lama: oldVal = currentVal
                    // Konfigurasi state update bisa dilakukan di sini
                    const val = $(this).val();
                    const key = `header${index + 1}`; // header1, header2...
                    config.kop[key] = val;
                });
            });

            // 5. Submit Kop
            $('#set-kop').on('submit', function (e) {
                e.preventDefault();
                e.stopImmediatePropagation();

                Swal.fire({
                    text: "Silahkan tunggu....",
                    button: false,
                    closeOnClickOutside: false,
                    onOpen: () => Swal.showLoading()
                });

                $.ajax({
                    url: config.baseUrl + 'cbtcetak/savekopberita',
                    type: 'POST',
                    processData: false,
                    contentType: false,
                    data: new FormData(this),
                    success: function (response) {
                        Swal.fire({
                            title: 'Sukses', text: "Template KOP berhasil disimpan", icon: 'success',
                        }).then(() => window.location.href = config.baseUrl + 'cbtcetak/beritaacara');
                    },
                    error: function (xhr) {
                        const err = JSON.parse(xhr.responseText);
                        Swal.fire({ title: "Error", text: err.Message, icon: "error" });
                    }
                });
            });

            // 6. Switcher (Ruang/Kelas)
            $('#selector button').click(function () {
                $(this).addClass('active').siblings().addClass('btn-outline-primary').removeClass('active btn-primary');

                const isRuangView = $('#by-kelas').is(':hidden');

                if (isRuangView) {
                    // Switch to Kelas
                    $('#by-kelas').removeClass('d-none');
                    $('#by-ruang').addClass('d-none');
                    $('#title-ruang').text('Kelas');
                    state.printBy = 2;
                    loadDataPeserta('kelas', DOM.opsiKelas.val(), null, DOM.opsiSesi.val(), DOM.opsiJadwal.val());
                } else {
                    // Switch to Ruang
                    $('#by-kelas').addClass('d-none');
                    $('#by-ruang').removeClass('d-none');
                    $('#title-ruang').text('Ruang');
                    state.printBy = 1;
                    loadDataPeserta('ruang', null, DOM.opsiRuang.val(), DOM.opsiSesi.val(), DOM.opsiJadwal.val());
                }
            });
        });

    })(jQuery);
</script>