<?= $this->extend('layout/admin') ?>
<?= $this->section('content') ?>

<style>
    .schedule-table th,
    .schedule-table td {
        text-align: center;
        vertical-align: middle;
        min-width: 130px;
        font-size: 14px;
    }

    .schedule-table th {
        background: #2c3e50;
        color: #fff;
        font-weight: 600;
    }

    .schedule-table td {
        height: 90px;
        background: #f9fafb;
        cursor: pointer;
        transition: background .2s ease;
    }

    .schedule-table td:hover {
        background: #eef3f8;
    }

    .schedule-slot {
        min-height: 70px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .schedule-item {
        background: linear-gradient(135deg, #1f4fd8, #1741b5);
        color: #fff;
        padding: 6px 10px;
        border-radius: 8px;
        font-size: 13px;
        width: 100%;
        text-align: left;
        box-shadow: 0 4px 10px rgba(0, 0, 0, .08);
    }

    .schedule-item strong {
        display: block;
        font-weight: 600;
    }

    .schedule-item small {
        display: block;
        font-size: 11px;
        opacity: .9;
    }

    .schedule-empty {
        color: #adb5bd;
        font-size: 12px;
        font-style: italic;
    }

    .bg-gradient-primary {
        background: linear-gradient(135deg, #4e73df, #224abe);
    }

    .modal-content {
        border-radius: 14px;
        animation: fadeUp .25s ease;
    }

    .form-control-lg {
        border-radius: 10px;
    }

    .modal-header {
        border-bottom: none;
    }

    @keyframes fadeUp {
        from {
            opacity: 0;
            transform: translateY(15px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
</style>


<div class="card shadow-sm">

    <!-- HEADER -->
    <div class="card-header bg-primary text-white">
        <b><i class="fas fa-calendar-alt me-1"></i> Jadwal Pelajaran</b>
        <div class="small opacity-75">Manajemen Akademik</div>
    </div>

    <!-- FILTER -->
    <div class="card-body border-bottom">
        <div class="row g-2">
            <div class="col-md-3">
                <label class="fw-bold">Tahun Ajaran</label>
                <select class="form-select" id="filterTahun">
                    <option value="2024/2025">2024 / 2025</option>
                    <option value="2025/2026">2025 / 2026</option>
                </select>
            </div>

            <div class="col-md-3">
                <label class="fw-bold">Semester</label>
                <select class="form-select" id="filterSemester">
                    <option value="Ganjil">Ganjil</option>
                    <option value="Genap">Genap</option>
                </select>
            </div>

            <div class="col-md-3">
                <label class="fw-bold">Kelas</label>
                <select class="form-select" id="filterKelas">
                    <option value="1">VII A</option>
                    <option value="2">VII B</option>
                    <option value="3">VIII A</option>
                </select>
            </div>

            <div class="col-md-3 d-flex align-items-end">
                <button class="btn btn-primary w-100" id="btnTampilkan">
                    <i class="fas fa-search me-1"></i> Tampilkan
                </button>
            </div>
        </div>
    </div>

    <!-- GRID -->
    <div class="card-body table-responsive">
        <table class="table table-bordered schedule-table">
            <thead class="table-dark">
                <tr>
                    <th width="120">Jam</th>
                    <th>Senin</th>
                    <th>Selasa</th>
                    <th>Rabu</th>
                    <th>Kamis</th>
                    <th>Jumat</th>
                </tr>
            </thead>
            <tbody>
                <?php for ($jam = 1; $jam <= 8; $jam++): ?>
                    <tr>
                        <th class="table-secondary">Jam <?= $jam ?></th>
                        <?php foreach (['senin', 'selasa', 'rabu', 'kamis', 'jumat'] as $hari): ?>
                            <td>
                                <div class="schedule-slot" data-hari="<?= $hari ?>" data-jam="<?= $jam ?>"></div>
                            </td>
                        <?php endforeach ?>
                    </tr>
                <?php endfor ?>
            </tbody>
        </table>
    </div>
</div>

<!-- ================= MODAL ================= -->
<div class="modal fade" id="modalJadwal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <form class="modal-content border-0 shadow-lg rounded-lg" id="formJadwal">

            <!-- hidden -->
            <input type="hidden" name="hari" id="modalHari">
            <input type="hidden" name="jam_ke" id="modalJam">
            <input type="hidden" name="tahun_ajaran" value="2024/2025">
            <input type="hidden" name="semester" value="Ganjil">
            <input type="hidden" name="kelas_id" value="1">

            <!-- HEADER -->
            <div class="modal-header bg-gradient-primary text-white">
                <h5 class="modal-title font-weight-bold">
                    <i class="fas fa-calendar-check mr-2"></i> Atur Jadwal Pelajaran
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>

            <!-- BODY -->
            <div class="modal-body px-4 py-3">

                <div class="form-group">
                    <label class="small text-muted font-weight-bold">
                        Mata Pelajaran
                    </label>
                    <select class="form-control form-control-lg" name="subject_id" required>
                        <option value="">Pilih Mata Pelajaran</option>
                        <?php foreach ($subjects as $s): ?>
                            <option value="<?= $s['id'] ?>">
                                <?= $s['nama_mapel'] ?>
                            </option>
                        <?php endforeach ?>
                    </select>
                </div>

                <div class="form-group">
                    <label class="small text-muted font-weight-bold">
                        Guru Pengajar
                    </label>
                    <select class="form-control form-control-lg" name="guru_id" required>
                        <option value="">Pilih Guru</option>
                        <?php foreach ($gurus as $g): ?>
                            <option value="<?= $g['id'] ?>">
                                <?= $g['nama_guru'] ?>     <?= $g['gelar'] ?>
                            </option>
                        <?php endforeach ?>
                    </select>
                </div>

                <div class="form-group mb-0">
                    <label class="small text-muted font-weight-bold">
                        Ruang Kelas
                    </label>
                    <select class="form-control form-control-lg" name="ruang">
                        <option value="R101">Ruang 101</option>
                        <option value="LAB">Laboratorium IPA</option>
                    </select>
                </div>

            </div>

            <!-- FOOTER -->
            <div class="modal-footer border-0 px-4 pb-4">
                <button type="button" class="btn btn-light px-4" data-dismiss="modal">
                    Batal
                </button>
                <button type="button" class="btn btn-primary px-4" id="btnSaveJadwal">
                    <i class="fas fa-save mr-1"></i> Simpan Jadwal
                </button>
            </div>

        </form>
    </div>
</div>

<script>
    /* ================= CLEAR GRID ================= */
    function clearGrid() {
        document.querySelectorAll('.schedule-slot')
            .forEach(slot => slot.innerHTML = '');
    }

    /* ================= LOAD JADWAL ================= */
    function loadJadwal() {

        clearGrid();

        let tahun = document.getElementById('filterTahun').value;
        let semester = document.getElementById('filterSemester').value;
        let kelas = document.getElementById('filterKelas').value;

        fetch(`<?= site_url('master/jadwal/data') ?>?tahun_ajaran=${tahun}&semester=${semester}&kelas_id=${kelas}`)
            .then(res => res.json())
            .then(data => {

                console.log('DATA JADWAL:', data); // 🔥 DEBUG

                if (!Array.isArray(data)) return;

                data.forEach(row => {
                    let slot = document.querySelector(
                        `.schedule-slot[data-hari="${row.hari}"][data-jam="${row.jam_ke}"]`
                    );

                    if (slot) {
                        slot.innerHTML = `
                        <div class="schedule-item">
                            ${row.nama_subject ?? '-'}
                            <small>${row.nama_guru ?? '-'}</small>
                            <small>${row.ruang ?? '-'}</small>
                        </div>
                    `;
                    }
                });
            });
    }

    function clearGrid() {
        document.querySelectorAll('.schedule-slot')
            .forEach(slot => {
                slot.innerHTML = `<span class="schedule-empty">Belum diatur</span>`;
            });
    }

    /* ================= EVENT ================= */
    document.getElementById('btnTampilkan')
        .addEventListener('click', loadJadwal);

    document.querySelectorAll('.schedule-slot').forEach(slot => {
        slot.addEventListener('click', function (e) {

            if (e.target.closest('.schedule-item')) return;

            document.getElementById('modalHari').value = this.dataset.hari;
            document.getElementById('modalJam').value = this.dataset.jam;

            $('#modalJadwal').modal('show');
        });
    });

    document.getElementById('btnSaveJadwal')
        .addEventListener('click', function () {

            let formData = new FormData(
                document.getElementById('formJadwal')
            );

            fetch("<?= site_url('master/jadwal/store') ?>", {
                method: 'POST',
                body: formData
            })
                .then(res => res.json())
                .then(res => {

                    // 🚫 JIKA BENTROK
                    if (!res.status) {
                        alert(res.msg); // 🔥 tampilkan pesan bentrok guru
                        return;
                    }

                    // ✅ JIKA AMAN
                    $('#modalJadwal').modal('hide');
                    loadJadwal();
                });
        });

    /* ================= AUTO LOAD ================= */
    document.addEventListener('DOMContentLoaded', loadJadwal);
</script>
<?= $this->endSection() ?>