<?php
/**
 * Created by IntelliJ IDEA.
 * User: multazam
 * Date: 07/07/20
 * Time: 17:20
 */
?>

<div class="content-wrapper bg-white">
    <section class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1><?= $judul ?></h1>
                </div>
            </div>
        </div>
    </section>

    <section class="content">
        <div class="container-fluid">
            <div class="card card-default my-shadow mb-4">
                <div class="card-header">
                    <h6 class="card-title"><?= $subjudul ?></h6>
                    <button class="card-tools btn btn-default btn-sm mr-2 btn-toggle" data-toggle="modal"
                            data-target="#infoModal"><i class="fas fa-info-circle mr-1"></i> Info Error
                    </button>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-12 mb-3">
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text text-center">TOKEN</span>
                                </div>
                                <input id="token-input" class="form-control text-bold text-center" readonly="readonly"/>
                                <div class="input-group-append" id="kolom-kanan">
                                    <span id="interval" class="input-group-text text-xs d-none">-- : -- : --</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="table-responsive mb-4" id="table-hari-ini"></div>
                    <div id="table-all-jadwal"></div>
                </div>
                <div class="overlay d-none" id="loading">
                    <div class="spinner-grow"></div>
                </div>
            </div>
        </div>
    </section>
</div>

<div class="modal fade" id="infoModal" tabindex="-1" role="dialog" aria-labelledby="infoLabel" aria-hidden="true">
    <div class="modal-dialog modal-xs" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="infoLabel">Kode error siswa</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <table class="table w-100">
                    <tr>
                        <td class="text-bold">001</td>
                        <td>:</td>
                        <td>Token salah atau token belum digenerate</td>
                    </tr>
                    <tr>
                        <td class="text-bold">002</td>
                        <td>:</td>
                        <td>Harus reset izin</td>
                    </tr>
                    <tr>
                        <td class="text-bold">003</td>
                        <td>:</td>
                        <td>Harus reset waktu</td>
                    </tr>
                    <tr>
                        <td class="text-bold">004</td>
                        <td>:</td>
                        <td>Soal belum dibuat atau belum dipilih</td>
                    </tr>
                    <tr>
                        <td class="text-bold">005</td>
                        <td>:</td>
                        <td>Siswa menggunakan browser yang tidak mendukung</td>
                    </tr>
                    <tr>
                        <td class="text-bold">006</td>
                        <td>:</td>
                        <td>internet down atau error dari database/server</td>
                    </tr>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>

<script>
    const ruangs = JSON.parse('<?=json_encode($ruang)?>');
    const arrRuang = JSON.parse('<?=json_encode($ruangs)?>');

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

    $(document).ready(function () {
        ajaxcsrf();

        getToken(function (result) {
            getGlobalToken();
        });

        $('#refresh-token').click(function () {
            getToken(function (result) {
                getGlobalToken();
            });
        });

        function getGlobalToken() {
            if (globalToken != null) {
                const viewToken = $('#token-input');
                if (viewToken.length) viewToken.val(globalToken.token);
                if (globalToken.auto == '1' && adaJadwalUjian > 0) {
                    $('#refresh-token').removeClass('d-none')
                }
            }
        }

        $.ajax({
            type: "GET",
            url: base_url + "cbtstatus/gettgljadwalujian",
            cache: false,
            success: function (response) {
                populateTable(response)
            }
        });
    });

    function generateRowHtml(jadwal, ruangSesi, pengawas, guruId) {
        const gp = (pengawas?.id_guru || '').split(',');
        const isPengawas = gp.includes(guruId);
        const isPengampu = jadwal?.pengampu;

        // Jika bukan pengawas atau pengampu, jangan tampilkan baris ini
        if (!isPengawas && !isPengampu) return '';

        let role = isPengampu ? `<span class="badge badge-success">Pengampu</span>` : '';
        if (role !== '' && isPengawas) { role += '<br>'; }
        role += isPengawas ? `<span class="badge badge-primary">Pengawas</span>` : '';

        return `
        <tr>
            <td class="text-center align-middle">${ruangSesi.nama_ruang}</td>
            <td class="text-center align-middle">${ruangSesi.nama_sesi}</td>
            <td class="text-center align-middle">${pengawas?.jam_ke || '1'}</td>
            <td class="align-middle">
                ${jadwal.bank?.mapel?.nama_mapel}<br>( ${jadwal.bank?.bank_kode} )
            </td>
            <td class="text-center align-middle">${role}</td>
            <td class="text-center align-middle">
                <button class="btn btn-info btn-sm"
                    data-id="${jadwal.id_jadwal}"
                    data-ruang="${ruangSesi.ruang_id}"
                    data-sesi="${ruangSesi.sesi_id}"
                    onclick="detail(this)">Lihat Status</button>
            </td>
        </tr>`;
    }

    function populateTable(response) {
        const { guru, jadwals, hari_ini, ruangs_sesi, pengawas: listPengawas } = response;

        const ruangSesiSorted = [...ruangs_sesi].sort((a, b) => {
            const bandingRuang = a.nama_ruang.localeCompare(b.nama_ruang, undefined, { numeric: true });
            return bandingRuang !== 0 ? bandingRuang : a.nama_sesi.localeCompare(b.nama_sesi, undefined, { numeric: true });
        });

        const generateTableBody = (currentJadwals) => {
            let rows = '';
            const idGuru = guru.id_guru;

            // 1. Kumpulkan data yang valid
            let dataTampil = [];
            ruangSesiSorted.forEach(rs => {
                currentJadwals.forEach(jadwal => {
                    const p = listPengawas?.find(p =>
                        p.id_jadwal === jadwal.id_jadwal &&
                        p.id_ruang === rs.ruang_id &&
                        p.id_sesi === rs.sesi_id
                    );
                    const isPengawas = (p?.id_guru || '').split(',').includes(idGuru);
                    const isPengampu = jadwal.pengampu;

                    if (isPengawas || isPengampu) {
                        dataTampil.push({ rs, jadwal, p, isPengawas, isPengampu });
                    }
                });
            });

            // 2. Hitung Rowspan Ruang DAN Sesi
            const ruangCounts = {};
            const sesiCounts = {}; // format key: "namaRuang-namaSesi"

            dataTampil.forEach(item => {
                const rName = item.rs.nama_ruang;
                const sName = item.rs.nama_sesi;
                const comboKey = `${rName}-${sName}`;

                ruangCounts[rName] = (ruangCounts[rName] || 0) + 1;
                sesiCounts[comboKey] = (sesiCounts[comboKey] || 0) + 1;
            });

            const ruangSudahRender = {};
            const sesiSudahRender = {};
            let currentClass = '';

            dataTampil.forEach(item => {
                const { rs, jadwal, p, isPengawas, isPengampu } = item;
                const comboKey = `${rs.nama_ruang}-${rs.nama_sesi}`;

                // --- LOGIKA ROWSPAN RUANG ---
                let kolomRuang = '';
                if (!ruangSudahRender[rs.nama_ruang]) {
                    currentClass = (currentClass === '') ? 'bg-light' : ''; // Toggle warna per ruang
                    kolomRuang = `<td class="text-center align-middle" rowspan="${ruangCounts[rs.nama_ruang]}"><b>${rs.nama_ruang}</b></td>`;
                    ruangSudahRender[rs.nama_ruang] = true;
                }

                // --- LOGIKA ROWSPAN SESI ---
                let kolomSesi = '';
                if (!sesiSudahRender[comboKey]) {
                    kolomSesi = `<td class="text-center align-middle" rowspan="${sesiCounts[comboKey]}">${rs.nama_sesi}</td>`;
                    sesiSudahRender[comboKey] = true;
                }

                // Logika Role
                let role = isPengampu ? `<span class="badge badge-success">Pengampu</span>` : '';
                if (role !== '' && isPengawas) role += '<br>';
                role += isPengawas ? `<span class="badge badge-primary">Pengawas</span>` : '';

                rows += `
            <tr class="${currentClass}">
                ${kolomRuang}
                ${kolomSesi}
                <td class="text-center align-middle">${p?.jam_ke || '1'}</td>
                <td class="align-middle">
                    ${jadwal.bank?.mapel?.nama_mapel}<br>
                    <small class="text-muted">(${jadwal.bank?.bank_kode})</small>
                </td>
                <td class="text-center align-middle">${role}</td>
                <td class="text-center align-middle">
                    <button class="btn btn-info btn-sm" onclick="detail(this)"
                        data-id="${jadwal.id_jadwal}" data-ruang="${rs.ruang_id}" data-sesi="${rs.sesi_id}">
                        Lihat Status
                    </button>
                </td>
            </tr>`;
            });
            return rows;
        };
        // Hari Ini
        const bodyHariIni = generateTableBody(jadwals[hari_ini] || []);
        $('#table-hari-ini').html(bodyHariIni ? renderTableStructure(formatTanggal(hari_ini), () => bodyHariIni) : renderEmptyTable("Jadwal Hari Ini", "Tidak ada jadwal mengawas/mengampu"));
        // Sebelumnya
        const tglKeys = Object.keys(jadwals || {}).filter(k => k < hari_ini).sort().reverse();
        $('#table-all-jadwal').empty();
        tglKeys.forEach(tgl => {
            const body = generateTableBody(jadwals[tgl]);
            if (body) {
                $('#table-all-jadwal').append(`<div class="mb-4 table-responsive">${renderTableStructure(formatTanggal(tgl), () => body)}</div>`);
            }
        });
    }

    function renderTableStructure(title, rowCallback) {
        return `
        <table class="table table-bordered border-top m-0 table-sm">
            <thead>
                <tr><th colspan="6" class="bg-gray-light text-center">${title}</th></tr>
                <tr>
                    <th class="text-center align-middle">Ruang</th>
                    <th class="text-center align-middle">Sesi</th>
                    <th class="text-center align-middle">Jam Ke</th>
                    <th class="align-middle">Mapel/Bank Soal</th>
                    <th class="text-center align-middle">Role</th>
                    <th class="text-center align-middle">Aksi</th>
                </tr>
            </thead>
            <tbody>${rowCallback()}</tbody>
        </table>`;
    }

    function renderEmptyTable(title, message) {
        return `
        <table class="table table-bordered border-top m-0 table-sm">
            <thead><tr><th colspan="6" class="bg-gray-light text-center">${title}</th></tr></thead>
            <tbody><tr><td colspan="6" class="text-center">${message}</td></tr></tbody>
        </table>`;
    }

    function detail(e) {
        window.location.href = base_url + 'cbtstatus/pengawas?' +
            'ruang=' + $(e).data('ruang') +
            '&sesi=' + $(e).data('sesi') +
            '&jadwal=' + $(e).data('id');
    }

</script>
