<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="container-fluid py-3">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-0 text-gray-800 fw-bold"><?= esc($schedule['name']) ?></h1>
            <p class="text-muted small mb-0">
                <span class="badge bg-secondary me-1">T.A. <?= esc($schedule['year_name']) ?> — <?= esc($schedule['period_name']) ?></span>
                Status: 
                <?php if ($schedule['status'] === 'published') : ?>
                    <span class="badge bg-success-subtle text-success border border-success-subtle"><i class="bi bi-check2-circle me-1"></i> Terbit (Aktif)</span>
                <?php else : ?>
                    <span class="badge bg-secondary-subtle text-secondary border border-secondary-subtle">Draf</span>
                <?php endif; ?>
            </p>
        </div>
        <div class="d-flex gap-2">
            <a href="/manual-schedule" class="btn btn-outline-secondary btn-sm d-flex align-items-center gap-1">
                <i class="bi bi-arrow-left"></i> Kembali
            </a>
            <div class="dropdown">
                <button class="btn btn-outline-primary btn-sm dropdown-toggle d-flex align-items-center gap-1" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="bi bi-printer"></i> Lihat & Cetak
                </button>
                <ul class="dropdown-menu dropdown-menu-end">
                    <li><a class="dropdown-item" href="/manual-schedule/by-class/<?= $schedule['id'] ?>?classroom_id=<?= $selectedClassroomId ?>"><i class="bi bi-door-open me-2"></i>Jadwal Per Kelas</a></li>
                    <li><a class="dropdown-item" href="/manual-schedule/by-teacher/<?= $schedule['id'] ?>"><i class="bi bi-person-badge me-2"></i>Jadwal Per Guru</a></li>
                </ul>
            </div>
            <?php if ($schedule['status'] !== 'published') : ?>
                <a href="/manual-schedule/publish/<?= $schedule['id'] ?>" class="btn btn-success btn-sm d-flex align-items-center gap-1" onclick="return confirm('Aktifkan jadwal ini secara global?');">
                    <i class="bi bi-check-lg"></i> Publikasikan
                </a>
            <?php endif; ?>
        </div>
    </div>

    <!-- Alerts -->
    <?php if (session()->getFlashdata('success')) : ?>
        <div class="alert alert-success alert-dismissible fade show border-0 shadow-sm mb-4" role="alert">
            <div class="d-flex align-items-center gap-2">
                <i class="bi bi-check-circle-fill fs-5"></i>
                <div><?= session()->getFlashdata('success') ?></div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if (session()->getFlashdata('warning')) : ?>
        <div class="alert alert-warning alert-dismissible fade show border-0 shadow-sm mb-4" role="alert">
            <div class="d-flex align-items-center gap-2">
                <i class="bi bi-exclamation-triangle-fill fs-5"></i>
                <div><?= session()->getFlashdata('warning') ?></div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if (session()->getFlashdata('error')) : ?>
        <div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm mb-4" role="alert">
            <div class="d-flex align-items-center gap-2">
                <i class="bi bi-x-circle-fill fs-5"></i>
                <div><?= session()->getFlashdata('error') ?></div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <!-- Workspace Layout -->
    <div class="row">
        <!-- Panel Kiri: Daftar Kelas -->
        <div class="col-lg-3 mb-4">
            <div class="card shadow-sm border-0 rounded-3 h-100">
                <div class="card-header bg-light py-3 border-bottom-0">
                    <h6 class="fw-bold text-dark mb-0"><i class="bi bi-door-open me-1"></i> Pilih Kelas</h6>
                </div>
                <div class="card-body p-2" style="max-height: 600px; overflow-y: auto;">
                    <div class="accordion accordion-flush" id="classroomAccordion">
                        <?php 
                        $idx = 0;
                        foreach ($groupedClassrooms as $gradeName => $clsList) : 
                            $idx++;
                            $collapseId = 'collapseGrade_' . $idx;
                            // Cek apakah ada kelas terpilih di grup ini untuk auto-expand
                            $hasActiveChild = false;
                            foreach ($clsList as $c) {
                                if ($c['id'] == $selectedClassroomId) {
                                    $hasActiveChild = true;
                                    break;
                                }
                            }
                        ?>
                            <div class="accordion-item border-0">
                                <h2 class="accordion-header" id="headingGrade_<?= $idx ?>">
                                    <button class="accordion-button py-2 px-3 fw-bold text-dark <?= $hasActiveChild ? '' : 'collapsed' ?>" type="button" data-bs-toggle="collapse" data-bs-target="#<?= $collapseId ?>" aria-expanded="<?= $hasActiveChild ? 'true' : 'false' ?>">
                                        <?= esc($gradeName) ?>
                                    </button>
                                </h2>
                                <div id="<?= $collapseId ?>" class="accordion-collapse collapse <?= $hasActiveChild ? 'show' : '' ?>" data-bs-parent="#classroomAccordion">
                                    <div class="accordion-body p-1">
                                        <div class="list-group list-group-flush">
                                            <?php foreach ($clsList as $c) : 
                                                $active = ($c['id'] == $selectedClassroomId) ? 'active bg-primary border-primary rounded-3 text-white' : 'text-dark';
                                            ?>
                                                <a href="/manual-schedule/edit/<?= $schedule['id'] ?>?classroom_id=<?= $c['id'] ?>" class="list-group-item list-group-item-action border-0 py-2 px-3 rounded-2 mb-1 small fw-semibold d-flex justify-content-between align-items-center <?= $active ?>">
                                                    <span><?= esc($c['name']) ?></span>
                                                    <?php 
                                                    $cnt = isset($gridByClassroom[$c['id']]) ? count($gridByClassroom[$c['id']], COUNT_RECURSIVE) - count($gridByClassroom[$c['id']]) : 0;
                                                    if ($cnt > 0) :
                                                    ?>
                                                        <span class="badge rounded-pill <?= ($c['id'] == $selectedClassroomId) ? 'bg-light text-primary' : 'bg-secondary-subtle text-secondary' ?>"><?= $cnt ?> JP</span>
                                                    <?php endif; ?>
                                                </a>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Panel Kanan: Workspace Grid -->
        <div class="col-lg-9 mb-4">
            <div class="card shadow-sm border-0 rounded-3">
                <div class="card-header bg-light py-3 border-bottom-0 d-flex justify-content-between align-items-center">
                    <?php 
                    $selectedClassroomName = '';
                    foreach ($groupedClassrooms as $gradeName => $clsList) {
                        foreach ($clsList as $c) {
                            if ($c['id'] == $selectedClassroomId) {
                                $selectedClassroomName = $c['name'];
                                break 2;
                            }
                        }
                    }
                    ?>
                    <h5 class="fw-bold text-dark mb-0 d-flex align-items-center gap-2">
                        <i class="bi bi-grid-3x3 text-primary"></i> 
                        Jadwal Kelas: <span class="text-primary"><?= esc($selectedClassroomName ?: 'Pilih Kelas') ?></span>
                    </h5>
                    <?php if ($selectedClassroomId) : ?>
                        <?php 
                        $totalJp = 0;
                        if (isset($gridByClassroom[$selectedClassroomId])) {
                            foreach ($gridByClassroom[$selectedClassroomId] as $day => $slots) {
                                $totalJp += count($slots);
                            }
                        }
                        ?>
                        <span class="badge bg-primary-subtle text-primary border border-primary-subtle px-3 py-2 fw-bold" style="font-size: 0.8rem;">
                            Total Beban: <?= $totalJp ?> Jam Pelajaran (JP)
                        </span>
                    <?php endif; ?>
                </div>

                <div class="card-body p-3">
                    <?php if (!$selectedClassroomId) : ?>
                        <div class="text-center py-5 text-muted">
                            <i class="bi bi-door-open fs-1 opacity-25 d-block mb-3"></i>
                            <span class="fw-semibold">Silakan pilih kelas di panel kiri untuk memulai input jadwal.</span>
                        </div>
                    <?php else : ?>
                        <div class="table-responsive">
                            <table class="table table-bordered align-middle grid-table text-center mb-0">
                                <thead>
                                    <tr class="table-light">
                                        <th class="col-time py-3 text-muted fw-bold">Jam</th>
                                        <?php foreach ($activeDays as $dayNum) : ?>
                                            <th class="py-3 text-dark fw-bold" style="min-width: 140px; width: 16%;">
                                                <?= esc($dayNames[$dayNum]) ?>
                                            </th>
                                        <?php endforeach; ?>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    for ($slotNum = 1; $slotNum <= $maxSlotNumber; $slotNum++) : 
                                    ?>
                                        <tr>
                                            <!-- Row Header: Jam ke-X -->
                                            <td class="col-time align-middle py-3">
                                                <div class="fw-bold text-dark text-center">Jam <?= $slotNum ?></div>
                                            </td>

                                            <!-- Data Columns (Days) -->
                                            <?php foreach ($activeDays as $dayNum) : ?>
                                                <?php 
                                                $isKbmSlot = isset($groupedTimeslots[$dayNum][$slotNum]);
                                                ?>
                                                <td class="align-middle p-2 <?= !$isKbmSlot ? 'bg-light text-muted' : '' ?>" style="height: 90px; vertical-align: top;">
                                                    <?php if (!$isKbmSlot) : ?>
                                                        <span class="text-muted opacity-50 small">-</span>
                                                    <?php else : ?>
                                                        <?php 
                                                        $entry = null;
                                                        if (isset($gridByClassroom[$selectedClassroomId][$dayNum][$slotNum])) {
                                                            $entryList = $gridByClassroom[$selectedClassroomId][$dayNum][$slotNum];
                                                            $entry = $entryList[0] ?? null; // Single assignment per slot
                                                        }
                                                        ?>

                                                        <?php if ($entry) : ?>
                                                            <!-- Assigned Card -->
                                                            <div class="card border-0 rounded-3 text-start p-2 h-100 position-relative assign-card shadow-sm transition-all" style="background-color: #f0fdf4; border-left: 4px solid #22c55e !important;">
                                                                <div class="pe-3">
                                                                    <div class="fw-bold text-dark mb-1 fs-7" title="<?= esc($entry['subject_name']) ?>" style="line-height: 1.2;">
                                                                        <?= esc($entry['subject_name']) ?>
                                                                    </div>
                                                                    <div class="text-secondary fs-8" title="<?= esc($entry['teacher_name']) ?>" style="line-height: 1.2;">
                                                                        <i class="bi bi-person me-1"></i><?= esc($entry['teacher_name']) ?>
                                                                    </div>
                                                                </div>
                                                                <button type="button" class="btn btn-link text-danger p-0 position-absolute btn-delete" style="top: 8px; right: 8px;" onclick="deleteSlot(<?= $dayNum ?>, <?= $slotNum ?>)">
                                                                    <i class="bi bi-x-circle-fill"></i>
                                                                </button>
                                                            </div>
                                                        <?php else : ?>
                                                            <!-- Empty Button Slot -->
                                                            <button type="button" class="btn btn-dashed w-100 h-100 d-flex flex-column align-items-center justify-content-center text-muted" onclick="openAssignModal(<?= $dayNum ?>, <?= $slotNum ?>, '<?= esc($dayNames[$dayNum]) ?>')">
                                                                <i class="bi bi-plus-lg fs-5 mb-1 opacity-50"></i>
                                                                <span class="fs-8">Tambah</span>
                                                            </button>
                                                        <?php endif; ?>
                                                    <?php endif; ?>
                                                </td>
                                            <?php endforeach; ?>
                                        </tr>
                                    <?php endfor; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal Dialog Assign Jadwal -->
<?php if ($selectedClassroomId) : ?>
<div class="modal fade" id="modalAssignEntry" tabindex="-1" aria-labelledby="modalAssignEntryLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-header bg-primary text-white py-3">
                <h5 class="modal-title fw-bold" id="modalAssignEntryLabel">Assign Pelajaran</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <div class="alert alert-danger d-none" id="modalAlert" role="alert"></div>

                <form id="formAssignSlot">
                    <!-- Hidden params -->
                    <input type="hidden" name="schedule_id" value="<?= $schedule['id'] ?>">
                    <input type="hidden" name="classroom_id" value="<?= $selectedClassroomId ?>">
                    <input type="hidden" name="day" id="inputDay">
                    <input type="hidden" name="slot_number" id="inputSlot">

                    <!-- Info Box -->
                    <div class="p-3 bg-light rounded-3 mb-3 border">
                        <div class="row">
                            <div class="col-6 mb-1 text-muted small">Kelas:</div>
                            <div class="col-6 mb-1 fw-bold text-dark text-end"><?= esc($selectedClassroomName) ?></div>
                            <div class="col-6 text-muted small">Waktu:</div>
                            <div class="col-6 fw-bold text-dark text-end"><span id="infoDayText">Senin</span> — Jam Ke-<span id="infoSlotText">1</span></div>
                        </div>
                    </div>

                    <!-- Dropdown Guru -->
                    <div class="mb-3">
                        <label for="selectTeacher" class="form-label fw-bold text-dark small">Pilih Guru Pengampu <span class="text-danger">*</span></label>
                        <select name="teacher_id" id="selectTeacher" class="form-select select2-modal" style="width: 100%;" required>
                            <option value="">-- Pilih Guru --</option>
                            <?php foreach ($teachers as $t) : ?>
                                <option value="<?= $t['id'] ?>"><?= esc($t['name']) ?> (<?= esc($t['short_code'] ?: 'No Code') ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- Dropdown Mapel -->
                    <div class="mb-3">
                        <label for="selectSubject" class="form-label fw-bold text-dark small">Pilih Mata Pelajaran <span class="text-danger">*</span></label>
                        <select name="school_subject_id" id="selectSubject" class="form-select select2-modal" style="width: 100%;" required>
                            <option value="">-- Pilih Mata Pelajaran --</option>
                            <?php foreach ($subjects as $ss) : ?>
                                <option value="<?= $ss['id'] ?>">[<?= esc($ss['code'] ?: '-') ?>] <?= esc($ss['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- Dropdown Durasi (JP) -->
                    <div class="mb-3">
                        <label for="selectDuration" class="form-label fw-bold text-dark small">Durasi Pelajaran (JP) <span class="text-danger">*</span></label>
                        <select name="duration" id="selectDuration" class="form-select" required>
                            <option value="1">1 JP (Jam Pelajaran)</option>
                            <option value="2">2 JP</option>
                            <option value="3">3 JP</option>
                            <option value="4">4 JP</option>
                            <option value="5">5 JP</option>
                        </select>
                        <div class="form-text text-muted" style="font-size: 0.72rem;">Mengisi slot otomatis secara berurutan mulai dari Jam ini.</div>
                    </div>

                    <div class="d-flex justify-content-end gap-2 pt-3 border-top mt-4">
                        <button type="button" class="btn btn-light px-4" data-bs-dismiss="modal">Batal</button>
                        <button type="button" class="btn btn-primary px-4 fw-bold shadow-sm" id="btnSaveSlot" onclick="saveSlot()">Simpan Jadwal</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
// Membuka modal penginputan
function openAssignModal(day, slot, dayName) {
    const modal = new bootstrap.Modal(document.getElementById('modalAssignEntry'));
    
    // Set hidden fields
    document.getElementById('inputDay').value = day;
    document.getElementById('inputSlot').value = slot;
    
    // Set text labels
    document.getElementById('infoDayText').innerText = dayName;
    document.getElementById('infoSlotText').innerText = slot;
    
    // Reset fields & alerts
    document.getElementById('selectTeacher').value = '';
    document.getElementById('selectSubject').value = '';
    document.getElementById('selectDuration').value = '1';
    document.getElementById('modalAlert').classList.add('d-none');
    document.getElementById('modalAlert').innerHTML = '';

    modal.show();
}

// Simpan data KBM via AJAX
function saveSlot() {
    const alertBox = document.getElementById('modalAlert');
    alertBox.classList.add('d-none');
    
    const data = {
        schedule_id: parseInt(document.querySelector('input[name="schedule_id"]').value),
        classroom_id: parseInt(document.querySelector('input[name="classroom_id"]').value),
        day: parseInt(document.getElementById('inputDay').value),
        slot_number: parseInt(document.getElementById('inputSlot').value),
        teacher_id: parseInt(document.getElementById('selectTeacher').value),
        school_subject_id: parseInt(document.getElementById('selectSubject').value),
        duration: parseInt(document.getElementById('selectDuration').value || 1)
    };

    if (!data.teacher_id || !data.school_subject_id) {
        alertBox.innerHTML = 'Silakan pilih Guru dan Mata Pelajaran terlebih dahulu.';
        alertBox.classList.remove('d-none');
        return;
    }

    // Ubah status button
    const btn = document.getElementById('btnSaveSlot');
    btn.disabled = true;
    btn.innerText = 'Menyimpan...';

    fetch('/manual-schedule/save-entry', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(res => {
        btn.disabled = false;
        btn.innerText = 'Simpan Jadwal';
        if (res.success) {
            window.location.reload();
        } else {
            alertBox.innerHTML = res.message;
            alertBox.classList.remove('d-none');
        }
    })
    .catch(err => {
        btn.disabled = false;
        btn.innerText = 'Simpan Jadwal';
        alertBox.innerHTML = 'Terjadi kesalahan sistem, silakan coba lagi.';
        alertBox.classList.remove('d-none');
        console.error(err);
    });
}

// Hapus slot pelajaran via AJAX
function deleteSlot(day, slot) {
    if (!confirm('Hapus jadwal pelajaran pada jam ini?')) {
        return;
    }

    const data = {
        schedule_id: parseInt(document.querySelector('input[name="schedule_id"]').value),
        classroom_id: parseInt(document.querySelector('input[name="classroom_id"]').value),
        day: day,
        slot_number: slot
    };

    fetch('/manual-schedule/delete-entry', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(res => {
        if (res.success) {
            window.location.reload();
        } else {
            alert(res.message || 'Gagal menghapus entri jadwal.');
        }
    })
    .catch(err => {
        alert('Terjadi kesalahan sistem saat menghapus.');
        console.error(err);
    });
}
</script>

<style>
.accordion-button:not(.collapsed) {
    background-color: rgba(13, 110, 253, 0.05) !important;
    color: var(--bs-primary) !important;
}
.list-group-item-action:hover {
    background-color: #f1f5f9;
}
.grid-table {
    border-collapse: separate;
    border-spacing: 0;
    font-size: 0.85rem;
}
.grid-table th {
    font-size: 0.8rem;
    background-color: #f8f9fa;
    border-bottom: 2px solid #dee2e6;
}
.grid-table td.col-time {
    background-color: #fcfcfc;
    font-size: 0.8rem;
    min-width: 100px;
}
.btn-dashed {
    background: transparent;
    border: 2px dashed #cbd5e1;
    transition: all 0.2s ease-in-out;
}
.btn-dashed:hover {
    border-color: var(--bs-primary);
    background-color: rgba(13, 110, 253, 0.03);
    color: var(--bs-primary) !important;
}
.assign-card {
    transition: all 0.2s ease-in-out;
}
.assign-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.08) !important;
}
.btn-delete {
    opacity: 0.4;
    transition: opacity 0.15s ease-in-out;
}
.assign-card:hover .btn-delete {
    opacity: 1;
}
.fs-7 {
    font-size: 0.8rem;
}
.fs-8 {
    font-size: 0.72rem;
}
.accordion-button::after {
    font-size: 0.8rem;
    width: 1rem;
    height: 1rem;
    background-size: 1rem;
}
</style>

<?= $this->endSection() ?>
