<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">
            <?= form_open('', array('id' => 'set-kop')) ?>
            <div class="card my-shadow">
                <div class="card-header">
                    <h6 class="card-title">Setting Kop Daftar Kehadiran</h6>
                    <button type="submit" class="card-tools btn btn-sm bg-primary text-white">
                        <i class="fas fa-save mr-1"></i> Simpan
                    </button>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Header 1</label>
                                <input class="form-control" name="header_1" placeholder="Header 1"
                                       value="<?= isset($kop->header_1) ? $kop->header_1 : '' ?>" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Header 2</label>
                                <input class="form-control" name="header_2" placeholder="Header 2"
                                       value="<?= isset($kop->header_2) ? $kop->header_2 : '' ?>" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Header 3</label>
                                <input class="form-control" name="header_3" placeholder="Header 3"
                                       value="<?= isset($kop->header_3) ? $kop->header_3 : '' ?>" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Header 4</label>
                                <input class="form-control" name="header_4" placeholder="Header 4"
                                       value="<?= isset($kop->header_4) ? $kop->header_4 : '' ?>" required>
                            </div>
                        </div>
                        <div class="col-md-4 d-none">
                            <div class="form-group">
                                <label>Proktor</label>
                                <input id="input-proktor" class="form-control" name="proktor" placeholder="Proktor"
                                       value="<?= isset($kop->proktor) ? $kop->proktor : '' ?>">
                            </div>
                        </div>
                        <div class="col-md-4 d-none">
                            <div class="form-group">
                                <label>Pengawas</label>
                                <input id="input-pengawas-1" class="form-control" name="pengawas_1"
                                       placeholder="Pengawas 1"
                                       value="<?= isset($kop->pengawas_1) ? $kop->pengawas_1 : '' ?>">
                            </div>
                        </div>
                        <div class="col-md-4 d-none">
                            <div class="form-group">
                                <label>Pengawas 2</label>
                                <input id="input-pengawas-2" class="form-control" name="pengawas_2"
                                       placeholder="Pengawas 2"
                                       value="<?= isset($kop->pengawas_2) ? $kop->pengawas_2 : '' ?>">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?= form_close() ?>

            <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-md-6 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-md-3 col-sm-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-md-3 col-sm-6 mb-3 align-self-end">
                            <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 Per Ruang/Kelas</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-md-3 mb-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-md-3 mb-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-md-3 mb-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="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>
                    <br>
                    <div class="d-flex justify-content-center bg-gray-light" style="min-height: 300mm">
                        <div id="print-preview" class="m-4">
                        </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>
    // --- 1. CONFIGURATION & STATE ---
    const config = {
        headers: {
            h1: <?= json_encode($kop->header_1 ?? '') ?>,
            h2: <?= json_encode($kop->header_2 ?? '') ?>,
            h3: <?= json_encode($kop->header_3 ?? '') ?>,
            h4: <?= json_encode($kop->header_4 ?? '') ?>
        },
        images: {
            logoLeft: "<?= isset($kop->logo_kiri) ? base_url() . $kop->logo_kiri : '' ?>",
            logoRight: "<?= isset($kop->logo_kanan) ? base_url() . $kop->logo_kanan : '' ?>",
            signature: "<?= isset($kop->tanda_tangan) ? base_url() . $kop->tanda_tangan : '' ?>"
        },
        apiUrl: "<?= base_url() ?>",
        rowsPerPage: 28, // Konstanta pengganti magic number '28'
    };

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

    // --- 2. HELPER FUNCTIONS ---
    const handleNull = (value) => (value == null || value == "0" || value == "") ? "-" : value;

    const handleTanggal = (tgl) => {
        if (handleNull(tgl) === "-") return "-";
        const days = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jum'at", "Sabtu"];
        const months = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"];
        const d = new Date(tgl);
        return `${days[d.getDay()]}, ${d.getDate()} ${months[d.getMonth()]} ${d.getFullYear()}`;
    };

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

    // --- 3. HTML GENERATORS (RENDERERS) ---
    const generateHeaderKop = (isAllPrint = false) => {
        const kop = isAllPrint ? config.headers : config.headers; // Bisa disesuaikan jika ada beda data
        return `
            <table style="width: 100%; border: 0;">
                <tr>
                    <td style="width:15%;"><img src="${config.images.logoLeft}" 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">${kop.h1}</div>
                        <div style="line-height: 1.1; font-family: 'Times New Roman'; font-size: 16pt"><b>${kop.h2}</b></div>
                        <div style="line-height: 1.2; font-family: 'Times New Roman'; font-size: 13pt">${kop.h3}</div>
                        <div style="line-height: 1.2; font-family: 'Times New Roman'; font-size: 12pt">${kop.h4}</div>
                    </td>
                    <td style="width:15%;"><img src="${config.images.logoRight}" style="width:85px; height:85px; margin: 6px; border-style: none"></td>
                </tr>
            </table>
            <hr style="border: 1px solid; margin-bottom: 6px">
        `;
    };

    // Fungsi untuk membuat baris tabel siswa
    const createRowStudent = (index, student, isMultiPage) => {
        const genap = (index + 1) % 2 === 0;
        const forGenap = genap ? (index + 1) + '.' : '';
        const forGanjil = genap ? '' : (index + 1) + '.';
        const height = isMultiPage ? '23px' : '20px';

        return `
            <tr style="font-family: 'Times New Roman'; font-size: 10pt">
                <td class="ts" style="line-height: 1.1;border: 1px solid black; text-align: center;">${index + 1}</td>
                <td class="ts" style="line-height: 1.1;border: 1px solid black; text-align: center; padding-left: 5px">${handleNull(student.nomor_peserta)}</td>
                <td class="ts" style="line-height: 1.1;border: 1px solid black; padding-left: 5px">${student.nama}</td>
                <td class="ts" style="line-height: 1.1;border: 1px solid black;text-align: center;">${student.kode_kelas}</td>
                <td class="ts" style="line-height: 1.1;border-bottom: 1px solid black;width:50px;padding-left: 5px">${forGanjil}</td>
                <td class="ts" style="line-height: 1.1;border-bottom: 1px solid black;width:100px;padding-left: 5px">${forGenap}</td>
                <td class="ts" style="line-height: 1.1;border: 1px solid black;"> </td>
            </tr>
        `;
    };

    // --- 4. CORE LOGIC: PREVIEW & DATA PROCESSING ---
    function createPrintPreview(data) {
        $('#print-preview').html('');
        const opsiTgl = $('#select-tgl');
        const mplTgl = $('#mapel-tgl');

        opsiTgl.addClass('d-none');
        mplTgl.html('');

        state.arrSiswa = data.siswa;
        state.info = data.info;

        const { sesi, ruang } = data.info;
        const alokasiJadwal = alokasiJam(data, false);
        console.log('alokasiJadwal', alokasiJadwal);

        // Filter Jadwal sesuai mode (By Ruang/By Kelas)
        for (const tanggal in alokasiJadwal) {
            const arrJadwal = alokasiJadwal[tanggal];
            for (const jadwal of arrJadwal) {
                let match;
                if (state.printBy === 2) {
                    match = jadwal.kelas_id.includes(data.info.kelas.id_kelas) &&
                        jadwal.id_mapel === data.info.mapel &&
                        jadwal.sesi_id === sesi.id_sesi;
                } else {
                    match = jadwal.id_mapel === data.info.mapel &&
                        jadwal.sesi_id === sesi.id_sesi &&
                        jadwal.ruang_id === ruang.id_ruang;
                }

                if (match) {
                    const exists = 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 (!exists) state.currJadwal.push(jadwal);
                }
            }
        }

        const kelasTitle = state.printBy === 2 ? 'Kelas' : 'Ruang';
        const kelasVal = state.printBy === 2 ? data.info.kelas.nama_kelas : ruang.nama_ruang + ' (' + ruang.kode_ruang + ')';

        if (state.currJadwal.length === 0) {
            $('#print-preview').html(`<b>Tidak ada data jadwal untuk ${kelasTitle} ${kelasVal} sesi ${sesi.nama_sesi}, atau ALOKASI WAKTU belum diatur</b>`);
            $('#loading').addClass('d-none');
            return;
        }

        if (state.currJadwal.length > 1) {
            opsiTgl.removeClass('d-none');
            mplTgl.prepend("<option value='' selected='selected'>Pilih Tanggal</option>");
            state.currJadwal.forEach(jadwal => {
                mplTgl.append(`<option value="${jadwal.jadwal.tgl_mulai}">${formatTanggalShort(jadwal.jadwal.tgl_mulai)}</option>`);
            });
        } else {
            buildTable(state.currJadwal[0], data.info);
        }

        $('#loading').addClass('d-none');

    }

    function buildTable(jadwal, info) {
        const { sesi } = info;
        const all_siswa_ruang = state.arrSiswa.filter(e => jadwal.ids_siswa.includes(e.id_siswa));
        all_siswa_ruang.sort((a, b) => (a.nomor_peserta || "").localeCompare(b.nomor_peserta || "", undefined, {numeric: true}));

        const pages = Math.ceil(all_siswa_ruang.length / config.rowsPerPage);
        const kelasTitle = state.printBy === 2 ? 'Kelas' : 'Ruang';
        const kelasVal = state.printBy === 2 ? info.kelas.nama_kelas : jadwal.nama_ruang + ' (' + jadwal.kode_ruang + ')';

        document.title = 'Daftar Hadir ' + (jadwal?.jadwal?.kode || '') + ' ' + kelasVal + ' ' + sesi.nama_sesi;

        // Ambil data pengawas
        const getPengawas = (arr) => {
            if ($.isArray(arr[0])) return { p1: arr[0]?.[0], p2: arr[0]?.[1] }; // Struktur lama/nested
            return { p1: arr[0], p2: arr[1] }; // Struktur flat
        };

        let pengawasData = { p1: {nama_guru: '', nip: ''}, p2: {nama_guru: '', nip: ''} };
        if (jadwal.pengawas && jadwal.pengawas.length > 0) {
            const raw = getPengawas(jadwal.pengawas);
            pengawasData.p1 = raw.p1 || {nama_guru: '', nip: ''};
            pengawasData.p2 = raw.p2 || {nama_guru: '', nip: ''};
        }

        let card = '';

        for (let a = 0; a < pages; a++) {
            const start = a * config.rowsPerPage;
            const end = (a + 1) < pages ? start + config.rowsPerPage : all_siswa_ruang.length;

            card += `
                <div class="border my-shadow mb-3 p-4 bg-white">
                    <div style="justify-content: center;width: 200mm; height: 290mm;padding: 15px;">
                        ${generateHeaderKop()}

                        <div style="display: flex;align-items: stretch;">
                            <div style="flex: 50%">
                                <table style="width: 100%; border: 0;">
                                    <tbody>
                                        <tr style="line-height: 1.1;font-family: 'Times New Roman';">
                                            <td>${kelasTitle}</td><td>:</td><td>${kelasVal}</td>
                                        </tr>
                                        <tr style="line-height: 1.1;font-family: 'Times New Roman';">
                                            <td>Sesi</td><td>:</td><td>${jadwal.nama_sesi}</td>
                                        </tr>
                                        <tr style="line-height: 1.1;font-family: 'Times New Roman';">
                                            <td>Waktu</td><td>:</td><td>${jadwal.dari} s/d ${jadwal.sampai}</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            <div style="flex: 50%">
                                <table style="width: 100%; border: 0;">
                                    <tbody>
                                        <tr style="line-height: 1.1;font-family: 'Times New Roman';">
                                            <td>Hari/Tanggal</td><td>:</td><td>${handleTanggal(jadwal.jadwal.tgl_mulai)}</td>
                                        </tr>
                                        <tr style="line-height: 1.1;font-family: 'Times New Roman';">
                                            <td>Mata Pelajaran</td><td>:</td><td>${jadwal.nama_mapel}</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <br>
                        <table style="width: 100%; border-collapse: collapse">
                            <tr style="font-family: 'Times New Roman';">
                                <th style="border: 1px solid black; width: 40px; height: 40px; text-align: center;">No.</th>
                                <th style="border: 1px solid black; text-align: center; width: 200px">No Peserta</th>
                                <th style="border: 1px solid black; text-align: center;">Nama</th>
                                <th style="border: 1px solid black; text-align: center;">Kelas</th>
                                <th colspan="2" style="border: 1px solid black; text-align: center;">Tanda Tangan</th>
                                <th style="border: 1px solid black; text-align: center;width: 80px;">Ket.</th>
                            </tr>
            `;

            for (let i = start; i < end; i++) {
                card += createRowStudent(i, all_siswa_ruang[i], pages > 1);
            }

            card += `</table>`;

            // Footer (hanya di halaman terakhir)
            if (a === (pages - 1)) {
                card += `
                    <br><br>
                    <table style="width: 100%">
                        <tr style="line-height: 1.1;font-family: 'Times New Roman';font-size: 10pt">
                            <td style="width: 40%; text-align: left">
                                <table style="border: 1px solid black; border-collapse: collapse">
                                    <tr><td style="padding-left: 5px;">Jumlah peserta yang seharusnya hadir</td><td>:</td><td style="padding-right: 5px"><u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</u> orang</td></tr>
                                    <tr><td style="border-bottom: 1px solid black;padding-left: 5px;">Jumlah peserta yang tidak hadir</td><td style="border-bottom: 1px solid black;">:</td><td style="border-bottom: 1px solid black; padding-right: 5px"><u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</u> orang</td></tr>
                                    <tr><td style="padding-left: 5px;">Jumlah peserta hadir</td><td>:</td><td style="padding-right: 5px"><u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</u> orang</td></tr>
                                </table>
                            </td>
                `;

                // Logika kolom Pengawas
                const colWidth = pengawasData.p2.nama_guru ? '30%' : '30%';
                const spacer = pengawasData.p2.nama_guru ? `
                    <td style="width: ${colWidth}; padding-left: 10px">
                        Pengawas 1<br><br><br><br><u>${pengawasData.p1.nama_guru}</u><br>Nip: ${pengawasData.p1.nip}
                    </td>` : `<td style="width: 30%; padding-left: 10px"></td>`;

                const lastCol = pengawasData.p2.nama_guru ? `
                    <td style="width: ${colWidth}">
                        Pengawas 2<br><br><br><br><u>${pengawasData.p2.nama_guru}</u><br>Nip: ${pengawasData.p2.nip}
                    </td>` : `
                    <td style="width: ${colWidth}">
                        Pengawas<br><br><br><br><u>${pengawasData.p1.nama_guru}</u><br>Nip: ${pengawasData.p1.nip}
                    </td>`;

                card += spacer + lastCol + `</tr></table>`;
            }

            card += `</div></div><div style="page-break-after: always"></div>`;
        }

        if (all_siswa_ruang.length > 0) {
            $('#print-preview').html(card);
            // Apply height logic
            if (pages > 1) $('.ts').height('23px');
            else $('.ts').height('20px');
        } else {
            $('#print-preview').html(`<b>Tidak ada data siswa di ruangan ${jadwal?.ruang?.nama_ruang} ${jadwal?.sesi?.nama_sesi}, atau nomor peserta belum diatur</b>`);
        }
    }

    // --- LOGIC UNTUK CETAK SEMUA (ALL PREVIEW) ---
    function populateAllPreview(data) {
        $('#all-print-preview').html('');
        let allPages = 0;
        const alokasiSesi = alokasiJam(data, true);

        for (const key in alokasiSesi) {
            for (const group of alokasiSesi[key]) {
                const all_siswa_ruang = data.siswa.filter(e => group.ids_siswa.includes(e.id_siswa));
                const pages = Math.ceil(all_siswa_ruang.length / config.rowsPerPage);

                // Sort Siswa
                all_siswa_ruang.sort((a, b) => a.nama.localeCompare(b.nama, undefined, {numeric: true}));
                all_siswa_ruang.sort((a, b) => a.id_kelas - b.id_kelas);

                for (let a = 0; a < pages; a++) {
                    const start = a * config.rowsPerPage;
                    const end = (a + 1) < pages ? start + config.rowsPerPage : all_siswa_ruang.length;

                    // Logic Pengawas All Print
                    const p1 = group.pengawas[0] || {nama_guru: '', nip: ''};
                    const p2 = group.pengawas[1] || {nama_guru: '', nip: ''};

                    const pengawasSection = p2.nama_guru ? `
                        <td style="width: 28%; padding-left: 7px">Pengawas 1<br><br><br><br><u>${p1.nama_guru}</u><br>Nip: ${p1.nip}</td>
                        <td style="width: 28%">Pengawas 2<br><br><br><br><u>${p2.nama_guru}</u><br>Nip: ${p2.nip}</td>
                    ` : `
                        <td style="width: 28%; padding-left: 7px"></td>
                        <td style="width: 28%">Pengawas<br><br><br><br><u>${p1.nama_guru}</u><br>Nip: ${p1.nip}</td>
                    `;

                    let rowsHtml = '';
                    for (let i = start; i < end; i++) {
                        rowsHtml += createRowStudent(i, all_siswa_ruang[i], pages > 1);
                    }

                    // Template Halaman Cetak
                    const pageHtml = `
                        <div class="mb-3 bg-white page-print" style="width: 210mm; height: 290mm;">
                            ${generateHeaderKop(true)}

                            <div style="display: flex;align-items: stretch;">
                                <div style="flex: 50%">
                                    <table style="width: 100%; border: 0;">
                                        <tbody>
                                            <tr style="line-height: 1.1; font-family: 'Times New Roman';">
                                                <td>Ruang</td><td>:</td><td>${group.nama_ruang} (${group.kode_ruang})</td>
                                            </tr>
                                            <tr style="line-height: 1.1; font-family: 'Times New Roman';">
                                                <td>Sesi</td><td>:</td><td>${group.nama_sesi}</td>
                                            </tr>
                                            <tr style="line-height: 1.1; font-family: 'Times New Roman';">
                                                <td>Waktu</td><td>:</td><td>${group.dari} s/d ${group.sampai}</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                                <div style="flex: 50%">
                                    <table style="width: 100%; border: 0;">
                                        <tbody>
                                            <tr style="line-height: 1.1; font-family: 'Times New Roman';">
                                                <td>Hari/Tanggal</td><td>:</td><td>${handleTanggal(group.jadwal.tgl_mulai)}</td>
                                            </tr>
                                            <tr style="line-height: 1.1; font-family: 'Times New Roman';">
                                                <td>Mata Pelajaran</td><td>:</td><td>${group.nama_mapel}</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <br>
                            <table style="width: 99%; border-collapse: collapse;">
                                <thead>
                                    <tr style="font-family: 'Times New Roman';">
                                        <th style="border: 1px solid black; width: 40px; height: 40px; text-align: center;">No.</th>
                                        <th style="border: 1px solid black; width: 200px; text-align: center;">No. Peserta</th>
                                        <th style="border: 1px solid black; text-align: center;">Nama</th>
                                        <th style="border: 1px solid black; text-align: center;">Kelas</th>
                                        <th colspan="2" style="border: 1px solid black; text-align: center;">Tanda Tangan</th>
                                        <th style="border: 1px solid black; width: 80px; text-align: center;">Ket.</th>
                                    </tr>
                                </thead>
                                <tbody>${rowsHtml}</tbody>
                            </table>
                    `;

                    let finalHtml = pageHtml;

                    // Footer Only Last Page
                    if (a === (pages - 1)) {
                        finalHtml += `
                            <br><br>
                            <table style="width: 100%">
                                <tr style="line-height: 1.1;font-family: 'Times New Roman';font-size: 10pt">
                                    <td style="width: 44%; text-align: left">
                                        <table style="border: 1px solid black; border-collapse: collapse">
                                            <tr><td style="padding-left: 5px;">Jumlah peserta yang seharusnya hadir</td><td>:</td><td style="padding-right: 5px"><u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</u> orang</td></tr>
                                            <tr><td style="border-bottom: 1px solid black;padding-left: 5px;">Jumlah peserta yang tidak hadir</td><td style="border-bottom: 1px solid black;">:</td><td style="border-bottom: 1px solid black; padding-right: 5px"><u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</u> orang</td></tr>
                                            <tr><td style="padding-left: 5px;">Jumlah peserta hadir</td><td>:</td><td style="padding-right: 5px"><u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</u> orang</td></tr>
                                        </table>
                                    </td>
                                    ${pengawasSection}
                                </tr>
                            </table>
                        `;
                    }

                    finalHtml += `</div><div style="page-break-after: always"></div>`;
                    $('#all-print-preview').append(finalHtml);
                    allPages++;
                }
            }
        }

        $('#loading-page').addClass('d-none');
        $('#info-page').removeClass('d-none');
        $('#info-page').text(`${allPages} Halaman`);
    }

    // --- BACKEND LOGIC REFACTOR (LOGIC SAMA, SYNTAX LEBIH RAPI) ---
    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 (state.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;
    }

    // --- 5. INITIALIZATION & EVENT LISTENERS ---
    $(document).ready(function () {
        ajaxcsrf();

        // Element Selectors
        const el = {
            mapel: $("#mapel"),
            mapelJadwal: $("#mapel-jadwal"),
            ruang: $("#ruang"),
            sesi: $("#sesi"),
            kelas: $("#kelas"),
            preview: $('#print-preview'),
            allPreview: $('#all-print-preview'),
            loading: $('#loading'),
            loadingPage: $('#loading-page'),
            infoPage: $('#info-page'),
            mplTgl: $('#mapel-tgl')
        };

        // Initialize Select2
        $('select').select2({ width: '100%', theme: 'bootstrap4' });

        // Default Options
        el.mapel.prepend("<option value='' selected='selected'>Pilih Mapel</option>");
        el.mapelJadwal.prepend("<option value='' selected='selected'>Pilih Jadwal</option>");
        el.ruang.prepend("<option value='' selected='selected'>Pilih Ruang</option>");
        el.sesi.prepend("<option value='' selected='selected'>Pilih Sesi</option>");
        el.kelas.prepend("<option value='' selected='selected'>Pilih Kelas</option>");

        // Function: Load Data for "Cetak Sekaligus"
        const loadAllSiswaRuang = (mapel) => {
            if (!mapel) return;
            el.loadingPage.removeClass('d-none');
            el.infoPage.addClass('d-none');
            $.ajax({
                type: "GET",
                url: config.apiUrl + "cbtcetak/getalljadwal?mapel=" + mapel,
                success: populateAllPreview,
                error: (xhr) => {
                    el.loadingPage.addClass('d-none');
                    el.infoPage.removeClass('d-none').text('Error');
                    console.error(xhr.responseText);
                }
            });
        };

        // Function: Load Data for Preview Tunggal (Ruang/Kelas)
        const loadPreviewData = () => {
            const ruang = el.ruang.val();
            const sesi = el.sesi.val();
            const jadwal = el.mapelJadwal.val();
            const kelas = el.kelas.val();

            const isValid = state.printBy === 1 ? (ruang && sesi && jadwal) : (kelas && sesi && jadwal);
            if (!isValid) return;

            el.loading.removeClass('d-none');

            // Gunakan endpoint yang sesuai dengan mode
            const url = state.printBy === 1
                ? `${config.apiUrl}cbtcetak/getruang?ruang=${ruang}&sesi=${sesi}&mapel=${jadwal}`
                : `${config.apiUrl}cbtcetak/getkelas?kelas=${kelas}&sesi=${sesi}&mapel=${jadwal}`;

            $.ajax({
                type: "GET",
                url: url,
                success: createPrintPreview,
                error: (xhr) => {
                    el.loading.addClass('d-none');
                    console.error(xhr.responseText);
                }
            });
        };

        // --- EVENT HANDLERS ---
        // Cetak Sekaligus
        $("#btn-print-all").click(function () {
            if (!el.mapel.val()) return Swal.fire("ERROR", "Isi Mapel terlebih dulu", "error");
            document.title = 'Daftar Hadir ' + el.mapel.find("option:selected").text();
            el.allPreview.print(document.title);
        });

        el.mapel.change(function () { loadAllSiswaRuang($(this).val()); });

        // Cetak Per Ruang/Kelas
        $("#btn-print").click(function () {
            const isEmpty = state.printBy === 2
                ? (!el.kelas.val() || !el.sesi.val() || !el.mapelJadwal.val())
                : (!el.ruang.val() || !el.sesi.val() || !el.mapelJadwal.val());

            if (isEmpty) return Swal.fire("ERROR", "Isi semua pilihan terlebih dulu", "error");
            el.preview.print(document.title);
        });

        el.mapelJadwal.change(loadPreviewData);
        el.sesi.change(loadPreviewData);
        el.ruang.change(loadPreviewData);
        el.kelas.change(loadPreviewData);

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

            const isByRuang = $('#by-kelas').is(':hidden');
            if (isByRuang) {
                // Switch ke Mode Kelas
                $('#by-kelas').removeClass('d-none');
                $('#by-ruang').addClass('d-none');
                state.printBy = 2;
            } else {
                // Switch ke Mode Ruang
                $('#by-kelas').addClass('d-none');
                $('#by-ruang').removeClass('d-none');
                state.printBy = 1;
            }
            loadPreviewData();
        });

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

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

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

        el.mplTgl.on('change', function() {
            const tgl = $(this).val();
            const jadwalSelected = state.currJadwal.find(e => e.jadwal.tgl_mulai === tgl);
            jadwalSelected ? buildTable(jadwalSelected, state.info) : $('#print-preview').html(`<b>Tidak ada data jadwal...</b>`);
        });

    });
</script>