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

<?php
function getInitials(string $name): string {
    $words = explode(' ', trim($name));
    $init  = '';
    foreach (array_slice($words, 0, 2) as $w)
        $init .= mb_strtoupper(mb_substr($w, 0, 1));
    return $init;
}
// Siapkan data subjectTargets sebagai JSON untuk JS
$subjectTargetsJson = json_encode($subjectTargets ?? []);
?>

<style>
/* ── Layout tabel guru ── */
.bm-table { width:100%; border-collapse:collapse; font-size:13px; }
.bm-table thead th { padding:9px 12px; font-size:11px; font-weight:600; color:#6b7280; background:#f9fafb; border-bottom:1px solid #e5e7eb; white-space:nowrap; }
.guru-row { border-bottom:1px solid #f3f4f6; transition:background .1s; }
.guru-row:hover { background:#f9fafb; }
.guru-row.open { background:#EBF5FF; }
.guru-row td { padding:9px 12px; vertical-align:middle; }
.guru-avatar { width:32px; height:32px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:11px; font-weight:700; flex-shrink:0; }
.bm-pill { font-size:11px; padding:2px 9px; border-radius:20px; font-weight:600; white-space:nowrap; }
.pill-jam   { background:#EBF5FF; color:#0C447C; }
.pill-kelas { background:#EAF3DE; color:#27500A; }
.pill-none  { background:#f3f4f6; color:#9ca3af; border:1px solid #e5e7eb; }

/* ── Detail row ── */
.detail-row td { padding:0; }
.detail-inner { padding:10px 12px 14px 56px; background:#f0f7ff; border-bottom:2px solid #185FA5; }
.detail-tbl { width:100%; font-size:12px; border-collapse:collapse; }
.detail-tbl td { padding:6px 10px; border-bottom:1px solid #e0edf9; vertical-align:middle; }
.icon-btn { width:28px; height:28px; border:1px solid #e5e7eb; border-radius:5px; display:inline-flex; align-items:center; justify-content:center; cursor:pointer; background:#fff; transition:all .1s; font-size:12px; }
.icon-btn:hover { background:#f9fafb; }
.icon-btn.danger { color:#dc2626; }
.icon-btn.danger:hover { background:#fef2f2; border-color:#fca5a5; }
.btn-tambah-inline { margin-top:8px; font-size:11px; padding:4px 12px; border:1px solid #185FA5; border-radius:6px; color:#185FA5; background:transparent; cursor:pointer; }
.btn-tambah-inline:hover { background:#EBF5FF; }
.split-preview { font-size:11px; color:#6b7280; margin-left:4px; }

/* ── Kelas checkbox grid ── */
.grade-group { margin-bottom:10px; border:1px solid #e5e7eb; border-radius:8px; overflow:hidden; }
.grade-header { background:#f8fafc; padding:8px 12px; border-bottom:1px solid #e5e7eb; display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
.classroom-list { padding:8px 12px; display:grid; grid-template-columns:repeat(2,1fr); gap:5px; }
@media (min-width:576px) { .classroom-list { grid-template-columns:repeat(3,1fr); } }
@media (min-width:992px) { .classroom-list { grid-template-columns:repeat(4,1fr); } }

/* ── Tabs ── */
.tab-custom { display:flex; gap:4px; background:#f1f5f9; border-radius:12px; padding:4px; margin-bottom:18px; }
.tab-custom button { flex:1; padding:8px 14px; border:none; background:transparent; border-radius:8px; font-size:13px; font-weight:500; color:#64748b; cursor:pointer; transition:all .2s; white-space:nowrap; }
.tab-custom button.active { background:#fff; color:#1d4ed8; box-shadow:0 1px 3px rgba(0,0,0,.1); }
.tab-pane { display:none; }
.tab-pane.active { display:block; }

/* ── Target table ── */
.target-input { width:65px; text-align:center; border:1px solid #e2e8f0; border-radius:6px; padding:4px 6px; font-size:13px; }
.target-input:focus { outline:2px solid #6366F1; border-color:#6366F1; }

/* ── Block preview ── */
.block-preview { display:inline-flex; gap:3px; align-items:center; flex-wrap:wrap; }
.block-box { display:inline-flex; align-items:center; justify-content:center; border-radius:4px; font-size:11px; font-weight:700; padding:2px 8px; color:#fff; }
.block-box.s1 { background:#6366F1; }
.block-box.s2 { background:#0891B2; }
.block-box.s3 { background:#059669; }
.block-sep { color:#9ca3af; font-size:10px; margin:0 1px; }

/* ── Info box ── */
.ibox { border-radius:8px; padding:9px 13px; font-size:12px; display:flex; align-items:flex-start; gap:8px; }
.ibox.info  { background:#EBF5FF; color:#0C447C; border:1px solid #BFDBFE; }
.ibox.warn  { background:#FFFBEB; color:#7B5800; border:1px solid #FDE68A; }
.ibox.error { background:#FFF1F2; color:#881337; border:1px solid #FECDD3; }
.ibox.ok    { background:#F0FDF4; color:#14532D; border:1px solid #BBF7D0; }

/* ── Target status di modal ── */
.grade-target-row { border-radius:8px; padding:8px 12px; margin-bottom:6px; border:1px solid #e5e7eb; transition:all .2s; }
.grade-target-row.status-ok   { background:#F0FDF4; border-color:#86EFAC; }
.grade-target-row.status-warn { background:#FFFBEB; border-color:#FDE68A; }
.grade-target-row.status-full { background:#FFF3CD; border-color:#FCD34D; }
.grade-target-row.status-over { background:#FFF1F2; border-color:#FECDD3; }
.grade-target-row.status-none { background:#f9fafb; border-color:#e5e7eb; }
.target-bar { height:6px; border-radius:3px; background:#e5e7eb; overflow:hidden; margin-top:4px; }
.target-bar-fill { height:100%; border-radius:3px; transition:width .3s; }
</style>

<!-- ── HEADER ── -->
<div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
    <div>
        <h5 class="mb-0 fw-semibold">
            <i class="bi bi-person-lines-fill me-2 text-primary"></i>Beban Mengajar
        </h5>
        <small class="text-muted">
            <?php if ($year && $period): ?>
                <?= esc($year['name']) ?> — Semester <?= esc($period['semester']) ?>
                &nbsp;·&nbsp; <?= count($teachers) ?> guru terdaftar
            <?php else: ?>
                <span class="text-danger">Belum ada tahun ajaran / periode aktif</span>
            <?php endif; ?>
        </small>
    </div>
    <?php if ($year && $period): ?>
    <button class="btn btn-outline-danger btn-sm" id="btnDeleteAll">
        <i class="bi bi-trash3-fill me-1"></i>Hapus Semua Beban
    </button>
    <?php endif; ?>
</div>

<?php if (!$year || !$period): ?>
<div class="alert alert-warning">
    <i class="bi bi-exclamation-triangle me-2"></i>
    Silakan aktifkan <strong>Tahun Ajaran</strong> dan <strong>Periode Akademik</strong> terlebih dahulu.
</div>
<?php else: ?>

<!-- ── TABS ── -->
<div class="tab-custom">
    <button class="tab-btn active" data-tab="tab1">
        <i class="bi bi-person-plus me-1"></i>Input Beban Mengajar
    </button>
    <button class="tab-btn" data-tab="tab2">
        <i class="bi bi-trophy me-1"></i>Target JTM / Mapel
    </button>
    <button class="tab-btn" data-tab="tab3">
        <i class="bi bi-clipboard-data me-1"></i>Rekap & Validasi
    </button>
</div>

<!-- ══════════════════════════════
     TAB 1: INPUT BEBAN MENGAJAR
══════════════════════════════ -->
<div class="tab-pane active" id="tab1">
    <div class="ibox info mb-3">
        <i class="bi bi-info-circle-fill flex-shrink-0 mt-1"></i>
        <div>Klik nama guru untuk melihat atau menambah beban mengajar.
        Validasi target JTM otomatis tampil saat memilih mapel — guru tidak bisa melebihi target yang sudah ditentukan di tab <strong>Target JTM</strong>.</div>
    </div>

    <div class="d-flex gap-2 mb-3 flex-wrap align-items-center">
        <input type="text" id="searchGuru" class="form-control form-control-sm"
               placeholder="Cari nama / NIP / PEG ID..." style="max-width:240px">
        <select id="filterStatus" class="form-select form-select-sm" style="max-width:160px">
            <option value="all">Semua guru</option>
            <option value="has">Sudah ada beban</option>
            <option value="empty">Belum ada beban</option>
        </select>
        <span id="filterCount" class="text-muted small"></span>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="bm-table">
                    <thead>
                        <tr>
                            <th style="width:42px"></th>
                            <th>Nama Guru</th>
                            <th>NIP / PEG ID</th>
                            <th class="text-center">Total Jam</th>
                            <th class="text-center">Total Kelas</th>
                            <th class="text-center" style="width:50px"></th>
                        </tr>
                    </thead>
                    <tbody id="tbodyGuru">
                    <?php foreach ($teachers as $idx => $teacher): ?>
                    <?php
                        $loads    = $loadsByTeacher[$teacher['id']] ?? [];
                        $totalJam = array_sum(array_column($loads, 'hours_per_week'));
                        $hasLoad  = !empty($loads);
                        $av       = $avatarColors[$idx % count($avatarColors)];
                        $initials = getInitials($teacher['name']);
                        $rowId    = 'detail-' . $teacher['id'];
                    ?>
                    <tr class="guru-row"
                        data-name="<?= strtolower(esc($teacher['name'])) ?>"
                        data-nip="<?= esc($teacher['nip'] ?? '') ?>"
                        data-pegid="<?= esc($teacher['peg_id'] ?? '') ?>"
                        data-status="<?= $hasLoad ? 'has' : 'empty' ?>">
                        <td onclick="toggleRow('<?= $rowId ?>', '<?= $teacher['id'] ?>')">
                            <div class="guru-avatar" style="background:<?= $av['bg'] ?>;color:<?= $av['color'] ?>">
                                <?= $initials ?>
                            </div>
                        </td>
                        <td onclick="toggleRow('<?= $rowId ?>', '<?= $teacher['id'] ?>')" class="fw-semibold" style="cursor:pointer">
                            <?= esc($teacher['name']) ?>
                        </td>
                        <td onclick="toggleRow('<?= $rowId ?>', '<?= $teacher['id'] ?>')" class="text-muted" style="font-size:12px;cursor:pointer">
                            <?= esc(teacher_id_display($teacher)) ?>
                        </td>
                        <td class="text-center" onclick="toggleRow('<?= $rowId ?>', '<?= $teacher['id'] ?>')" style="cursor:pointer">
                            <?php if ($hasLoad): ?>
                            <span class="bm-pill pill-jam"><?= $totalJam ?> jam</span>
                            <?php else: ?>
                            <span class="bm-pill pill-none">—</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-center" onclick="toggleRow('<?= $rowId ?>', '<?= $teacher['id'] ?>')" style="cursor:pointer">
                            <?php if ($hasLoad): ?>
                            <span class="bm-pill pill-kelas"><?= count($loads) ?> kelas</span>
                            <?php else: ?>
                            <span class="bm-pill pill-none">—</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-center" onclick="toggleRow('<?= $rowId ?>', '<?= $teacher['id'] ?>')" style="cursor:pointer">
                            <i class="bi bi-chevron-down" id="chev-<?= $teacher['id'] ?>"></i>
                        </td>
                    </tr>

                    <!-- DETAIL ROW -->
                    <tr class="detail-row" id="<?= $rowId ?>" style="display:none">
                        <td colspan="6">
                            <div class="detail-inner">
                                <?php if (!$hasLoad): ?>
                                <div class="text-muted small mb-2">Belum ada beban mengajar untuk guru ini.</div>
                                <?php else: ?>
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="small fw-semibold text-muted">Beban mengajar:</span>
                                    <button class="btn btn-sm btn-outline-danger py-0 px-2"
                                            style="font-size:11px"
                                            onclick="hapusSemuaGuru(<?= $teacher['id'] ?>, '<?= esc($teacher['name'], 'js') ?>')">
                                        <i class="bi bi-trash3 me-1"></i>Hapus Semua
                                    </button>
                                </div>
                                <table class="detail-tbl">
                                    <tbody>
                                    <?php foreach ($loads as $load): ?>
                                    <tr id="load-row-<?= $load['id'] ?>">
                                        <td style="width:32%">
                                            <strong><?= esc($load['subject_name']) ?></strong>
                                            <?php if ($load['subject_code']): ?>
                                            <small class="text-muted">[<?= esc($load['subject_code']) ?>]</small>
                                            <?php endif; ?>
                                        </td>
                                        <td style="width:22%"><?= esc($load['classroom_name']) ?></td>
                                        <td>
                                            <span class="bm-pill pill-jam" style="font-size:10px"><?= $load['hours_per_week'] ?> jam</span>
                                            <?php if (!empty($load['split_config']) && $load['split_config'] != $load['hours_per_week']): ?>
                                            <span class="split-preview">(<?= esc($load['split_config']) ?>)</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end" style="white-space:nowrap">
                                            <button class="icon-btn" title="Edit"
                                                    onclick="editLoad(<?= htmlspecialchars(json_encode($load), ENT_QUOTES) ?>)">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            <button class="icon-btn danger" title="Hapus"
                                                    onclick="hapusSatu(<?= $load['id'] ?>, '<?= esc($load['subject_name'].' · '.$load['classroom_name'], 'js') ?>')">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    </tbody>
                                </table>
                                <?php endif; ?>

                                <button class="btn-tambah-inline"
                                        onclick="openTambah(<?= $teacher['id'] ?>, '<?= esc($teacher['name'], 'js') ?>')">
                                    <i class="bi bi-plus-lg me-1"></i>Tambah mapel / kelas
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div><!-- /tab1 -->

<!-- ══════════════════════════════
     TAB 2: TARGET JTM
══════════════════════════════ -->
<div class="tab-pane" id="tab2">
    <div class="ibox info mb-3">
        <i class="bi bi-info-circle-fill flex-shrink-0 mt-1"></i>
        <div>
            Target jam tatap muka (JTM) per mapel per tingkat digunakan untuk validasi input beban mengajar.
            Contoh: Al-Qur'an Hadis tingkat VII = 2 jam/minggu, artinya total jam mapel tersebut
            untuk <strong>semua kelas tingkat VII</strong> tidak boleh melebihi 2 jam (karena 1 guru 1 kelas = 2 jam).
            <strong>Tekan tombol <i class="bi bi-save"></i> untuk menyimpan tiap baris.</strong>
        </div>
    </div>
    <div class="card border-0 shadow-sm">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-bordered mb-0" style="font-size:13px">
                    <thead>
                        <tr>
                            <th style="width:36px" class="bg-light">No</th>
                            <th class="bg-light">Mata Pelajaran</th>
                            <?php
                            $allGrades   = [];
                            $gradeNames  = [];
                            foreach ($subjectTargets as $gradeMap)
                                foreach ($gradeMap as $gid => $v) $allGrades[$gid] = $gid;
                            ksort($allGrades);
                            if (empty($allGrades)) $allGrades = [1=>1,2=>2,3=>3];
                            // Ambil nama grade dari DB (fallback default MTs)
                            $gradeLabels = [1=>'VII',2=>'VIII',3=>'IX'];
                            ?>
                            <?php foreach ($allGrades as $gid): ?>
                            <th class="text-center bg-light" style="width:110px">
                                <?= $gradeLabels[$gid] ?? 'Tingkat '.$gid ?>
                                <div style="font-size:10px;font-weight:400;color:#6b7280">jam/minggu</div>
                            </th>
                            <?php endforeach; ?>
                            <th class="text-center bg-light" style="width:70px">Total</th>
                            <th class="text-center bg-light" style="width:64px">Simpan</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($subjects as $i => $subject): ?>
                    <?php
                        $rowTotal = 0;
                        foreach ($allGrades as $gid)
                            $rowTotal += ($subjectTargets[$subject['id']][$gid] ?? 0);
                    ?>
                    <tr id="target-row-<?= $subject['id'] ?>">
                        <td class="text-muted"><?= $i + 1 ?></td>
                        <td>
                            <span class="fw-semibold"><?= esc($subject['name']) ?></span>
                            <?php if ($subject['code']): ?>
                            <small class="text-muted ms-1">[<?= esc($subject['code']) ?>]</small>
                            <?php endif; ?>
                        </td>
                        <?php foreach ($allGrades as $gid): ?>
                        <td class="text-center">
                            <input type="number" class="target-input target-grade"
                                   data-subject-id="<?= $subject['id'] ?>"
                                   data-grade-id="<?= $gid ?>"
                                   value="<?= $subjectTargets[$subject['id']][$gid] ?? 0 ?>"
                                   min="0" max="20"
                                   onchange="recalcTotal(<?= $subject['id'] ?>)">
                        </td>
                        <?php endforeach; ?>
                        <td class="text-center fw-bold" id="total-<?= $subject['id'] ?>"><?= $rowTotal ?></td>
                        <td class="text-center">
                            <button class="btn btn-sm btn-primary py-0 px-2 btn-save-target"
                                    data-subject-id="<?= $subject['id'] ?>" title="Simpan target">
                                <i class="bi bi-save"></i>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div><!-- /tab2 -->

<!-- ══════════════════════════════
     TAB 3: REKAP & VALIDASI
══════════════════════════════ -->
<div class="tab-pane" id="tab3">
    <div id="rekapContent">
        <div class="text-center py-5 text-muted">
            <i class="bi bi-arrow-clockwise fs-2 d-block mb-2 opacity-25"></i>
            Memuat data rekap...
        </div>
    </div>
</div>

<?php endif; ?>

<!-- ══════════════════════════════
     MODAL: TAMBAH BEBAN
══════════════════════════════ -->
<div class="modal fade" id="modalTambah" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <form id="formTambah">
                <?= csrf_field() ?>
                <input type="hidden" name="teacher_id" id="inputTeacherId">
                <div class="modal-header border-bottom pb-2">
                    <div>
                        <h6 class="modal-title fw-bold mb-0">
                            <i class="bi bi-plus-circle text-primary me-2"></i>Tambah Beban Mengajar
                        </h6>
                        <small class="text-muted" id="modalGuruLabel">—</small>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row g-3">

                        <!-- Mapel -->
                        <div class="col-12">
                            <label class="form-label fw-semibold small">Mata Pelajaran <span class="text-danger">*</span></label>
                            <select name="school_subject_id" id="selectSubject" class="form-select form-select-sm" required>
                                <option value="">— Pilih Mapel —</option>
                                <?php foreach ($subjects as $s): ?>
                                <option value="<?= $s['id'] ?>">
                                    <?= esc($s['name']) ?><?= $s['code'] ? ' ['.esc($s['code']).']' : '' ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- STATUS TARGET PER TINGKAT — tampil setelah pilih mapel -->
                        <div class="col-12" id="targetStatusArea" style="display:none">
                            <div class="small fw-semibold mb-2 text-muted">
                                <i class="bi bi-trophy me-1"></i>Status Target JTM per Tingkat:
                            </div>
                            <div id="targetGradeCards"></div>
                        </div>

                        <!-- Kelas -->
                        <div class="col-12">
                            <label class="form-label fw-semibold small">
                                Kelas <span class="text-danger">*</span>
                                <span class="fw-normal text-muted">(bisa pilih lebih dari satu)</span>
                            </label>
                            <div class="border rounded-3 p-2" style="max-height:260px;overflow-y:auto" id="classroomBox">
                                <?php foreach ($groupedClassrooms as $grade): ?>
                                <div class="grade-group">
                                    <div class="grade-header">
                                        <div class="form-check mb-0">
                                            <input class="form-check-input check-all-grade" type="checkbox"
                                                   id="chkGrade<?= $grade['grade_id'] ?>"
                                                   data-grade-id="<?= $grade['grade_id'] ?>">
                                            <label class="form-check-label fw-semibold small" for="chkGrade<?= $grade['grade_id'] ?>">
                                                <?= esc($grade['grade_name']) ?>
                                            </label>
                                        </div>
                                        <!-- Badge status target tingkat ini -->
                                        <span class="ms-auto grade-badge" data-grade-id="<?= $grade['grade_id'] ?>" style="display:none;font-size:10px"></span>
                                    </div>
                                    <div class="classroom-list" data-grade-id="<?= $grade['grade_id'] ?>">
                                        <?php foreach ($grade['classrooms'] as $class): ?>
                                        <div class="form-check">
                                            <input class="form-check-input chk-kelas" type="checkbox"
                                                   name="classroom_ids[]"
                                                   id="kelas<?= $class['id'] ?>"
                                                   value="<?= $class['id'] ?>"
                                                   data-grade-id="<?= $grade['grade_id'] ?>">
                                            <label class="form-check-label small" for="kelas<?= $class['id'] ?>">
                                                <?= esc($class['name']) ?>
                                            </label>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <div class="d-flex gap-3 mt-1">
                                <a href="#" id="btnPilihSemua" class="small">Pilih semua</a>
                                <a href="#" id="btnHapusSemua" class="small text-danger">Hapus semua</a>
                            </div>
                        </div>

                        <!-- Jam & Split -->
                        <div class="col-md-4">
                            <label class="form-label fw-semibold small">Jam / Minggu <span class="text-danger">*</span></label>
                            <input type="number" name="hours_per_week" id="hoursPerWeek"
                                   class="form-control form-control-sm" value="2" min="1" max="18" required>
                        </div>
                        <div class="col-md-8">
                            <label class="form-label fw-semibold small">
                                Pembagian Blok
                                <span class="fw-normal text-muted">(tiap blok = hari berbeda)</span>
                            </label>
                            <div class="input-group input-group-sm">
                                <input type="text" name="split_config" id="splitConfig"
                                       class="form-control" placeholder="cth: 2,2 atau 3,2">
                                <button type="button" class="btn btn-outline-secondary" id="btnSuggest">
                                    <i class="bi bi-magic me-1"></i>Saran
                                </button>
                            </div>
                            <div class="mt-1 d-flex align-items-center gap-2 flex-wrap">
                                <div class="block-preview" id="blockPreview"></div>
                                <span id="splitInfo" class="text-muted" style="font-size:11px">Kosong = 1 blok</span>
                            </div>
                        </div>

                        <!-- Catatan -->
                        <div class="col-12">
                            <label class="form-label fw-semibold small">Catatan</label>
                            <input type="text" name="notes" id="addNotes" class="form-control form-control-sm"
                                   placeholder="Opsional..." maxlength="200">
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-top py-2">
                    <button type="button" class="btn btn-light btn-sm" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary btn-sm" id="btnSubmitTambah">
                        <i class="bi bi-save me-1"></i>Simpan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ══════════════════════════════
     MODAL: EDIT BEBAN
══════════════════════════════ -->
<div class="modal fade" id="modalEdit" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form id="formEdit">
                <?= csrf_field() ?>
                <input type="hidden" name="id" id="editId">
                <div class="modal-header border-bottom pb-2">
                    <h6 class="modal-title fw-bold mb-0">
                        <i class="bi bi-pencil-square text-primary me-2"></i>Edit Beban Mengajar
                    </h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="ibox info mb-3" style="font-size:11px">
                        <i class="bi bi-info-circle-fill flex-shrink-0"></i>
                        <span>Guru, mapel, dan kelas tidak dapat diubah. Hapus lalu tambah ulang jika perlu ganti.</span>
                    </div>
                    <div class="row g-2">
                        <div class="col-12">
                            <label class="form-label fw-semibold small">Guru</label>
                            <input type="text" id="editTeacherName" class="form-control form-control-sm" disabled>
                        </div>
                        <div class="col-6">
                            <label class="form-label fw-semibold small">Mata Pelajaran</label>
                            <input type="text" id="editSubjectName" class="form-control form-control-sm" disabled>
                        </div>
                        <div class="col-6">
                            <label class="form-label fw-semibold small">Kelas</label>
                            <input type="text" id="editClassroomName" class="form-control form-control-sm" disabled>
                        </div>
                        <div class="col-4">
                            <label class="form-label fw-semibold small">Jam/Minggu *</label>
                            <input type="number" name="hours_per_week" id="editHours"
                                   class="form-control form-control-sm" min="1" max="18" required>
                        </div>
                        <div class="col-8">
                            <label class="form-label fw-semibold small">Pembagian Blok</label>
                            <div class="input-group input-group-sm">
                                <input type="text" name="split_config" id="editSplitConfig"
                                       class="form-control" placeholder="cth: 2,2">
                                <button type="button" class="btn btn-outline-secondary" id="btnEditSuggest">
                                    <i class="bi bi-magic"></i>
                                </button>
                            </div>
                            <div class="block-preview mt-1" id="editBlockPreview"></div>
                        </div>
                        <div class="col-12">
                            <label class="form-label fw-semibold small">Catatan</label>
                            <input type="text" name="notes" id="editNotes"
                                   class="form-control form-control-sm" maxlength="200">
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-top py-2">
                    <button type="button" class="btn btn-light btn-sm" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary btn-sm">
                        <i class="bi bi-save me-1"></i>Update
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
'use strict';
const CSRF = '<?= csrf_hash() ?>';
// Data target dari PHP — dipakai untuk validasi JS tanpa fetch
const subjectTargets = <?= $subjectTargetsJson ?>;

// ─────────────────────────────────────────
// SEARCH & FILTER
// ─────────────────────────────────────────
const allRows = [];
document.querySelectorAll('#tbodyGuru .guru-row').forEach(row => {
    allRows.push({ guru: row, detail: row.nextElementSibling });
});
function doSearch() {
    const q  = (document.getElementById('searchGuru').value || '').toLowerCase();
    const st = document.getElementById('filterStatus').value;
    let n = 0;
    allRows.forEach(p => {
        const show = (p.guru.dataset.name.includes(q) || p.guru.dataset.nip.includes(q) || p.guru.dataset.pegid && p.guru.dataset.pegid.includes(q))
                  && (st === 'all' || p.guru.dataset.status === st);
        p.guru.style.display   = show ? '' : 'none';
        p.detail.style.display = show && p.guru.classList.contains('open') ? '' : 'none';
        if (show) n++;
    });
    document.getElementById('filterCount').textContent = n + ' guru';
}
document.getElementById('searchGuru')?.addEventListener('input', doSearch);
document.getElementById('filterStatus')?.addEventListener('change', doSearch);
doSearch();

// ─────────────────────────────────────────
// TOGGLE ROW — tidak pakai event bubbling
// ─────────────────────────────────────────
function toggleRow(detailId, teacherId) {
    const detail  = document.getElementById(detailId);
    const guruRow = document.querySelector(`[data-name]#tbodyGuru .guru-row`) || detail.previousElementSibling;
    const isOpen  = detail.style.display === 'table-row';
    detail.style.display = isOpen ? 'none' : 'table-row';
    // Cari guru-row yang benar
    const allGuruRows = document.querySelectorAll('.guru-row');
    allGuruRows.forEach(r => {
        if (r.nextElementSibling && r.nextElementSibling.id === detailId) {
            r.classList.toggle('open', !isOpen);
        }
    });
    const chev = document.getElementById('chev-' + teacherId);
    if (chev) {
        chev.classList.toggle('bi-chevron-down', isOpen);
        chev.classList.toggle('bi-chevron-up',   !isOpen);
    }
}

// ─────────────────────────────────────────
// HAPUS SATU — dipanggil langsung dari onclick
// ─────────────────────────────────────────
function hapusSatu(id, label) {
    Swal.fire({
        title: 'Hapus Beban Ini?',
        html: `<strong>${label}</strong> akan dihapus permanen.`,
        icon: 'warning', showCancelButton: true,
        confirmButtonColor: '#dc3545', confirmButtonText: 'Hapus',
        cancelButtonText: 'Batal'
    }).then(async result => {
        if (!result.isConfirmed) return;
        Swal.fire({ title: 'Menghapus...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
        const res  = await fetch('/schedule-load/delete-ajax/' + id, {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body: new FormData()
        });
        const data = await res.json();
        if (data.success) {
            Swal.fire({ icon: 'success', title: 'Dihapus!', timer: 1200, showConfirmButton: false })
                .then(() => location.reload());
        } else {
            Swal.fire({ icon: 'error', title: 'Gagal!', text: data.message });
        }
    });
}

// ─────────────────────────────────────────
// HAPUS SEMUA PER GURU — dipanggil langsung dari onclick
// ─────────────────────────────────────────
function hapusSemuaGuru(teacherId, teacherName) {
    Swal.fire({
        title: 'Hapus Semua Beban?',
        html: `Semua beban mengajar <strong>${teacherName}</strong> akan dihapus.<br>
               <span class="text-danger small">Aksi ini tidak dapat dibatalkan!</span>`,
        icon: 'warning', showCancelButton: true,
        confirmButtonColor: '#dc3545', confirmButtonText: 'Ya, Hapus Semua',
        cancelButtonText: 'Batal'
    }).then(async result => {
        if (!result.isConfirmed) return;
        Swal.fire({ title: 'Menghapus...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
        const fd = new FormData();
        fd.append('<?= csrf_token() ?>', CSRF);
        const res  = await fetch('/schedule-load/delete-all-by-teacher/' + teacherId, {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body: fd
        });
        const data = await res.json();
        if (data.success) {
            Swal.fire({ icon: 'success', title: 'Dihapus!', text: data.message, timer: 1500, showConfirmButton: false })
                .then(() => location.reload());
        } else {
            Swal.fire({ icon: 'error', title: 'Gagal!', text: data.message });
        }
    });
}

// ─────────────────────────────────────────
// HAPUS SEMUA GLOBAL
// ─────────────────────────────────────────
document.getElementById('btnDeleteAll')?.addEventListener('click', () => {
    Swal.fire({
        title: 'Hapus SEMUA Beban Mengajar?',
        text: 'Semua data beban mengajar periode aktif akan dihapus permanen.',
        icon: 'warning', showCancelButton: true,
        confirmButtonColor: '#dc3545', confirmButtonText: 'Ya, Hapus Semua',
        cancelButtonText: 'Batal'
    }).then(r => { if (r.isConfirmed) window.location.href = '/schedule-load/delete-all'; });
});

// ─────────────────────────────────────────
// OPEN TAMBAH MODAL
// ─────────────────────────────────────────
function openTambah(teacherId, teacherName) {
    document.getElementById('inputTeacherId').value = teacherId;
    document.getElementById('modalGuruLabel').textContent = teacherName;
    document.getElementById('selectSubject').value  = '';
    document.getElementById('hoursPerWeek').value   = '2';
    document.getElementById('splitConfig').value    = '';
    document.getElementById('addNotes').value       = '';
    document.getElementById('blockPreview').innerHTML = '';
    document.getElementById('splitInfo').textContent = 'Kosong = 1 blok';
    document.getElementById('targetStatusArea').style.display = 'none';
    document.querySelectorAll('.chk-kelas').forEach(c => c.checked = false);
    document.querySelectorAll('.check-all-grade').forEach(c => c.checked = false);
    document.querySelectorAll('.grade-badge').forEach(b => { b.style.display = 'none'; b.textContent = ''; });
    new bootstrap.Modal(document.getElementById('modalTambah')).show();
}

// ─────────────────────────────────────────
// EDIT LOAD
// ─────────────────────────────────────────
function editLoad(load) {
    document.getElementById('editId').value            = load.id;
    document.getElementById('editTeacherName').value   = load.teacher_name;
    document.getElementById('editSubjectName').value   = load.subject_name;
    document.getElementById('editClassroomName').value = load.classroom_name;
    document.getElementById('editHours').value         = load.hours_per_week;
    document.getElementById('editSplitConfig').value   = load.split_config || '';
    document.getElementById('editNotes').value         = load.notes || '';
    renderBlocks('editBlockPreview', parseInt(load.hours_per_week), load.split_config || '');
    new bootstrap.Modal(document.getElementById('modalEdit')).show();
}

// ─────────────────────────────────────────
// RENDER BLOCK PREVIEW
// ─────────────────────────────────────────
function renderBlocks(containerId, total, splitStr) {
    const el = document.getElementById(containerId);
    if (!el) return;
    const str = (splitStr || '').trim();
    let blocks = str ? str.split(',').map(b => parseInt(b)).filter(b => b > 0) : (total > 0 ? [total] : []);
    if (!blocks.length) { el.innerHTML = ''; return; }
    const sum   = blocks.reduce((a,b) => a+b, 0);
    const valid = sum === total && blocks.length <= 3 && blocks.every(b => b >= 1 && b <= 3);
    let html = blocks.map((s, i) =>
        `${i > 0 ? '<span class="block-sep">+</span>' : ''}<span class="block-box s${Math.min(s,3)}" style="opacity:${valid?1:.4}">${s}j</span>`
    ).join('');
    if (!valid) {
        const err = sum !== total ? `${sum}≠${total}` : blocks.length > 3 ? 'maks 3 blok' : 'tiap blok 1-3j';
        html += `<span style="font-size:10px;color:#dc2626;margin-left:4px">⚠ ${err}</span>`;
    } else if (blocks.length > 1) {
        html += `<span style="font-size:10px;color:#6b7280;margin-left:4px">→ ${blocks.length} hari</span>`;
    }
    el.innerHTML = html;
}

// ─────────────────────────────────────────
// SPLIT CONFIG — event listeners
// ─────────────────────────────────────────
function updateSplit() {
    const total = parseInt(document.getElementById('hoursPerWeek').value) || 0;
    const split = document.getElementById('splitConfig').value;
    renderBlocks('blockPreview', total, split);
    const info = document.getElementById('splitInfo');
    const str = split.trim();
    if (!str) {
        info.textContent = `Kosong = 1 blok (${total} jam dalam 1 hari)`;
        info.style.color = '#6b7280';
        return;
    }
    const blocks = str.split(',').map(b => parseInt(b)).filter(b => b > 0);
    const sum = blocks.reduce((a,b) => a+b, 0);
    if (sum === total && blocks.length <= 3 && blocks.every(b => b >= 1 && b <= 3)) {
        info.innerHTML = `<span style="color:#085041"><i class="bi bi-check-circle"></i> Valid: ${blocks.length} blok, tiap blok di hari berbeda</span>`;
    } else {
        const err = sum !== total ? `Total ${sum} ≠ ${total} jam` : blocks.length > 3 ? 'Maks 3 blok' : 'Tiap blok 1–3 jam';
        info.innerHTML = `<span style="color:#dc2626"><i class="bi bi-exclamation-triangle"></i> ${err}</span>`;
    }
    // Update target warning setelah jam berubah
    updateTargetWarning();
}
document.getElementById('splitConfig')?.addEventListener('input', updateSplit);
document.getElementById('hoursPerWeek')?.addEventListener('input', updateSplit);

async function suggestSplit(hoursId, splitId, previewId) {
    const total = document.getElementById(hoursId)?.value;
    if (!total || total < 1) return;
    const res  = await fetch('/schedule-load/get-suggest-split?total_jam=' + total, {
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    });
    const data = await res.json();
    if (data.success) {
        document.getElementById(splitId).value = data.split;
        if (splitId === 'splitConfig') updateSplit();
        else renderBlocks(previewId, parseInt(total), data.split);
    }
}
document.getElementById('btnSuggest')?.addEventListener('click', () => suggestSplit('hoursPerWeek', 'splitConfig', 'blockPreview'));
document.getElementById('btnEditSuggest')?.addEventListener('click', () => suggestSplit('editHours', 'editSplitConfig', 'editBlockPreview'));
document.getElementById('editSplitConfig')?.addEventListener('input', function() {
    renderBlocks('editBlockPreview', parseInt(document.getElementById('editHours').value)||0, this.value);
});
document.getElementById('editHours')?.addEventListener('input', function() {
    renderBlocks('editBlockPreview', parseInt(this.value)||0, document.getElementById('editSplitConfig').value);
});

// ─────────────────────────────────────────
// TARGET STATUS — saat pilih mapel
// Data target sudah ada di JS variable `subjectTargets`
// Fetch hanya untuk data "yang sudah terisi" dari DB
// ─────────────────────────────────────────
let targetFilled = {}; // { gradeId: { filled, existing_teachers } }

document.getElementById('selectSubject')?.addEventListener('change', async function() {
    const sid = this.value;
    targetFilled = {};
    document.getElementById('targetStatusArea').style.display = 'none';
    document.querySelectorAll('.grade-badge').forEach(b => { b.style.display = 'none'; b.textContent = ''; });
    if (!sid) return;

    // Ambil data yang sudah terisi dari server
    try {
        const res  = await fetch('/schedule-load/get-target-info/' + sid, {
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        });
        const data = await res.json();
        if (data.success) {
            // Simpan data filled per grade
            // Endpoint perlu return: filled_1, filled_2, filled_3 dan existing_teachers
            targetFilled = data.filled_by_grade || {};
        }
    } catch(e) {}

    updateTargetWarning();
});

function updateTargetWarning() {
    const sid   = document.getElementById('selectSubject')?.value;
    const hours = parseInt(document.getElementById('hoursPerWeek')?.value) || 0;
    if (!sid) return;

    const targets = subjectTargets[sid] || {};
    const gradeCards = document.getElementById('targetGradeCards');
    let html = '';
    let hasAny = false;

    // Loop semua grade yang ada targetnya
    const gradeLabels = {1:'VII', 2:'VIII', 3:'IX'};
    for (const [gidStr, target] of Object.entries(targets)) {
        if (target === 0) continue;
        hasAny = true;
        const gid    = parseInt(gidStr);
        const filled = targetFilled[gid] ? parseInt(targetFilled[gid].filled) : 0;
        const left   = target - filled;
        const afterAdd = left - hours; // sisa setelah menambah jam ini

        let statusCls, statusText, barPct, barColor;
        if (filled > target) {
            statusCls = 'status-over'; statusText = '❌ MELEBIHI TARGET';
            barPct = 100; barColor = '#dc2626';
        } else if (left === 0) {
            statusCls = 'status-full'; statusText = '⚠ SUDAH PENUH';
            barPct = 100; barColor = '#f59e0b';
        } else if (hours > 0 && afterAdd < 0) {
            statusCls = 'status-warn'; statusText = `⚠ Akan melebihi (sisa ${left}, ditambah ${hours})`;
            barPct = Math.round(filled / target * 100); barColor = '#f59e0b';
        } else if (left <= 2) {
            statusCls = 'status-warn'; statusText = `Sisa ${left} jam dari target ${target}`;
            barPct = Math.round(filled / target * 100); barColor = '#f59e0b';
        } else {
            statusCls = 'status-ok'; statusText = `${filled}/${target} jam terisi, sisa ${left}`;
            barPct = Math.round(filled / target * 100); barColor = '#22c55e';
        }

        // Guru yang sudah mengajar
        let teacherNote = '';
        if (targetFilled[gid] && targetFilled[gid].teachers && targetFilled[gid].teachers.length > 0) {
            teacherNote = `<div style="font-size:10px;color:#6b7280;margin-top:3px">
                <i class="bi bi-person-check me-1"></i>Sudah ada: <strong>${targetFilled[gid].teachers.join(', ')}</strong>
            </div>`;
        }

        html += `<div class="grade-target-row ${statusCls}">
            <div class="d-flex justify-content-between align-items-center">
                <span class="fw-semibold" style="font-size:12px">Tingkat ${gradeLabels[gid] || gid}</span>
                <span style="font-size:11px">${statusText}</span>
            </div>
            <div class="target-bar mt-1">
                <div class="target-bar-fill" style="width:${barPct}%;background:${barColor}"></div>
            </div>
            ${teacherNote}
        </div>`;

        // Update badge di header grade
        const badge = document.querySelector(`.grade-badge[data-grade-id="${gid}"]`);
        if (badge) {
            badge.style.display = '';
            if (left <= 0)
                badge.innerHTML = `<span class="bm-pill" style="background:#FFF3CD;color:#7B5800;font-size:10px">PENUH</span>`;
            else if (hours > 0 && afterAdd < 0)
                badge.innerHTML = `<span class="bm-pill" style="background:#FFF1F2;color:#881337;font-size:10px">Akan melebihi</span>`;
            else
                badge.innerHTML = `<span class="bm-pill" style="background:#E1F5EE;color:#085041;font-size:10px">Sisa ${left} jam</span>`;
        }
    }

    if (hasAny) {
        gradeCards.innerHTML = html;
        document.getElementById('targetStatusArea').style.display = '';
    }
}

// ─────────────────────────────────────────
// CHECK ALL PER GRADE
// ─────────────────────────────────────────
document.querySelectorAll('.check-all-grade').forEach(chk => {
    chk.addEventListener('change', function() {
        document.querySelectorAll(`.chk-kelas[data-grade-id="${this.dataset.gradeId}"]`)
            .forEach(cb => cb.checked = this.checked);
    });
});
document.getElementById('btnPilihSemua')?.addEventListener('click', e => {
    e.preventDefault();
    document.querySelectorAll('.chk-kelas').forEach(c => c.checked = true);
    document.querySelectorAll('.check-all-grade').forEach(c => c.checked = true);
});
document.getElementById('btnHapusSemua')?.addEventListener('click', e => {
    e.preventDefault();
    document.querySelectorAll('.chk-kelas').forEach(c => c.checked = false);
    document.querySelectorAll('.check-all-grade').forEach(c => c.checked = false);
});

// ─────────────────────────────────────────
// FORM TAMBAH — submit
// ─────────────────────────────────────────
document.getElementById('formTambah')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const sid    = document.getElementById('selectSubject').value;
    const hours  = parseInt(document.getElementById('hoursPerWeek').value);
    const kelasIds = Array.from(document.querySelectorAll('.chk-kelas:checked')).map(cb => cb.value);

    if (!sid)              { Swal.fire('Error', 'Pilih mata pelajaran terlebih dahulu', 'error'); return; }
    if (!kelasIds.length)  { Swal.fire('Error', 'Pilih minimal 1 kelas', 'error'); return; }
    if (!hours || hours < 1) { Swal.fire('Error', 'Jam/minggu tidak valid', 'error'); return; }

    // Cek apakah ada grade yang PENUH atau melebihi
    const gradeMap = {};
    kelasIds.forEach(cid => {
        const gid = document.querySelector(`#kelas${cid}`)?.dataset.gradeId;
        if (gid) gradeMap[gid] = (gradeMap[gid] || 0) + 1;
    });

    let warningMsg = '';
    for (const [gid, cnt] of Object.entries(gradeMap)) {
        const target = (subjectTargets[sid] || {})[gid] || 0;
        if (!target) continue;
        const filled = targetFilled[gid] ? parseInt(targetFilled[gid].filled) : 0;
        const willAdd = hours * cnt;
        if (filled + willAdd > target) {
            const gradeLabels = {1:'VII',2:'VIII',3:'IX'};
            warningMsg += `Tingkat ${gradeLabels[gid]||gid}: target ${target} jam, sudah ${filled} jam, akan ditambah ${willAdd} jam (total ${filled+willAdd})<br>`;
        }
    }

    if (warningMsg) {
        const result = await Swal.fire({
            icon: 'warning',
            title: 'Melebihi Target JTM',
            html: warningMsg + '<br><small>Apakah tetap ingin menyimpan?</small>',
            showCancelButton: true,
            confirmButtonText: 'Tetap Simpan',
            cancelButtonText: 'Batal',
            confirmButtonColor: '#f59e0b',
        });
        if (!result.isConfirmed) return;
    }

    // Submit
    const btn  = document.getElementById('btnSubmitTambah');
    const orig = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Menyimpan...';
    try {
        const fd = new FormData(this);
        const res  = await fetch('/schedule-load/store', {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body: fd
        });
        const data = await res.json();
        btn.disabled = false; btn.innerHTML = orig;
        if (data.success) {
            Swal.fire({ icon: 'success', title: 'Berhasil!', text: data.message, timer: 2000, showConfirmButton: false })
                .then(() => location.reload());
        } else {
            Swal.fire({ icon: 'error', title: 'Gagal!', html: data.message });
        }
    } catch(err) {
        btn.disabled = false; btn.innerHTML = orig;
        Swal.fire({ icon: 'error', title: 'Error!', text: err.message });
    }
});

// ─────────────────────────────────────────
// FORM EDIT — submit
// ─────────────────────────────────────────
document.getElementById('formEdit')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const id = document.getElementById('editId').value;
    const res  = await fetch('/schedule-load/update/' + id, {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: new FormData(this)
    });
    const data = await res.json();
    if (data.success) {
        Swal.fire({ icon: 'success', title: 'Berhasil!', text: data.message, timer: 1500, showConfirmButton: false })
            .then(() => location.reload());
    } else {
        Swal.fire({ icon: 'error', title: 'Gagal!', html: data.message });
    }
});

// ─────────────────────────────────────────
// TAB SWITCH
// ─────────────────────────────────────────
document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
        document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active'));
        this.classList.add('active');
        document.getElementById(this.dataset.tab).classList.add('active');
        if (this.dataset.tab === 'tab3') loadRekap();
    });
});

// ─────────────────────────────────────────
// TAB 2 — simpan target
// ─────────────────────────────────────────
function recalcTotal(sid) {
    let t = 0;
    document.querySelectorAll(`.target-grade[data-subject-id="${sid}"]`).forEach(i => t += parseInt(i.value)||0);
    const el = document.getElementById('total-' + sid);
    if (el) el.textContent = t;
}

document.querySelectorAll('.btn-save-target').forEach(btn => {
    btn.addEventListener('click', async function() {
        const sid     = this.dataset.subjectId;
        const payload = { subject_id: sid, vii: 0, viii: 0, ix: 0 };
        document.querySelectorAll(`.target-grade[data-subject-id="${sid}"]`).forEach(inp => {
            const gid = inp.dataset.gradeId;
            payload['grade_' + gid] = parseInt(inp.value) || 0;
            if (gid == 1) payload.vii  = payload['grade_' + gid];
            if (gid == 2) payload.viii = payload['grade_' + gid];
            if (gid == 3) payload.ix   = payload['grade_' + gid];
        });
        const res  = await fetch('/schedule-load/save-target', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': CSRF },
            body: JSON.stringify(payload)
        });
        const data = await res.json();
        if (data.success) {
            const orig = this.innerHTML;
            this.innerHTML = '<i class="bi bi-check-circle text-white"></i>';
            this.classList.replace('btn-primary', 'btn-success');
            setTimeout(() => { this.innerHTML = orig; this.classList.replace('btn-success','btn-primary'); }, 1500);
            // Update local JS variable
            if (!subjectTargets[sid]) subjectTargets[sid] = {};
            document.querySelectorAll(`.target-grade[data-subject-id="${sid}"]`).forEach(inp => {
                subjectTargets[sid][inp.dataset.gradeId] = parseInt(inp.value) || 0;
            });
        } else {
            Swal.fire({ icon: 'error', title: 'Gagal!', text: data.message });
        }
    });
});

// ─────────────────────────────────────────
// TAB 3 — REKAP DETAIL
// ─────────────────────────────────────────
let rekapDone = false;
let rekapData = null;

async function loadRekap() {
    if (rekapDone) return;
    const el = document.getElementById('rekapContent');
    el.innerHTML = `<div class="text-center py-4"><div class="spinner-border text-primary"></div></div>`;
    try {
        const res  = await fetch('/schedule-load/get-rekap', { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
        const data = await res.json();
        if (!data.success) { el.innerHTML = `<div class="alert alert-danger">${data.message}</div>`; return; }
        rekapData = data;
        renderRekap(data);
        rekapDone = true;
    } catch(e) {
        el.innerHTML = `<div class="alert alert-danger">Gagal memuat: ${e.message}</div>`;
    }
}

function renderRekap(data) {
    const kap = data.capacity_per_class || 0;
    const ov  = (data.classrooms||[]).filter(c => c.total_hours >  kap).length;
    const ok  = (data.classrooms||[]).filter(c => c.total_hours === kap).length;
    const krg = (data.classrooms||[]).filter(c => c.total_hours <  kap).length;

    let html = `
    <div class="row g-2 mb-3">
        <div class="col-4"><div class="card border-0 text-center py-2" style="background:#F0FDF4">
            <div style="font-size:24px;font-weight:800;color:#22c55e">${ok}</div>
            <div style="font-size:11px;color:#14532d">Penuh</div>
        </div></div>
        <div class="col-4"><div class="card border-0 text-center py-2" style="background:#FFFBEB">
            <div style="font-size:24px;font-weight:800;color:#f59e0b">${krg}</div>
            <div style="font-size:11px;color:#7B5800">Ada Sisa</div>
        </div></div>
        <div class="col-4"><div class="card border-0 text-center py-2" style="background:#FFF1F2">
            <div style="font-size:24px;font-weight:800;color:#dc2626">${ov}</div>
            <div style="font-size:11px;color:#881337">Overload</div>
        </div></div>
    </div>
    <div class="row g-3">

    <!-- Tabel ringkasan — klik baris untuk lihat detail -->
    <div class="col-lg-5">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white py-2 d-flex justify-content-between align-items-center">
                <span class="fw-semibold"><i class="bi bi-door-open me-2 text-primary"></i>Ringkasan per Kelas</span>
                <small class="text-muted">${kap} slot/minggu</small>
            </div>
            <div class="card-body p-0">
            <div class="table-responsive" style="max-height:400px;overflow-y:auto">
            <table class="table table-sm mb-0" style="font-size:12px">
            <thead class="table-light" style="position:sticky;top:0;z-index:1">
                <tr><th>Kelas</th><th class="text-center">Terisi</th><th class="text-center">Sisa</th><th>Status</th></tr>
            </thead><tbody id="rekapKelasBody">`;

    (data.classrooms||[]).forEach(cls => {
        const sisa = kap - cls.total_hours;
        let badge;
        if      (sisa < 0)   badge = `<span class="bm-pill" style="background:#FFF1F2;color:#881337;font-size:10px">❌+${-sisa}</span>`;
        else if (sisa === 0)  badge = `<span class="bm-pill" style="background:#E1F5EE;color:#085041;font-size:10px">✓</span>`;
        else if (sisa <= 3)   badge = `<span class="bm-pill" style="background:#FFF3CD;color:#7B5800;font-size:10px">⚠${sisa}</span>`;
        else                  badge = `<span class="bm-pill" style="background:#f3f4f6;color:#6b7280;font-size:10px">${sisa}</span>`;
        html += `<tr class="rekap-kelas-row" style="cursor:pointer"
                    data-id="${cls.id}" onclick="showClassDetail(this, ${cls.id}, '${(cls.name||'').replace(/'/g,"\\'")}')">
            <td class="fw-semibold">${cls.name} <i class="bi bi-chevron-right" style="font-size:10px;color:#9ca3af"></i></td>
            <td class="text-center">${cls.total_hours}</td>
            <td class="text-center">${sisa}</td>
            <td>${badge}</td>
        </tr>`;
    });

    html += `</tbody></table></div></div></div></div>

    <!-- Panel detail kelas -->
    <div class="col-lg-7">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white py-2">
                <span class="fw-semibold">
                    <i class="bi bi-table me-2 text-primary"></i>
                    Detail — <span id="classDetailName" class="text-primary">pilih kelas di sebelah kiri</span>
                </span>
            </div>
            <div class="card-body p-0" id="classDetailBody">
                <div class="text-center py-5 text-muted">
                    <i class="bi bi-hand-index-thumb fs-2 d-block mb-2 opacity-25"></i>
                    Klik nama kelas untuk melihat detail beban mengajar.
                </div>
            </div>
        </div>
    </div>

    <!-- Target belum terpenuhi -->
    <div class="col-12">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white py-2">
                <span class="fw-semibold">
                    <i class="bi bi-exclamation-triangle me-2 text-warning"></i>Target JTM Belum Terpenuhi
                </span>
            </div>
            <div class="card-body p-0">`;

    if (!data.warnings || !data.warnings.length) {
        html += `<div class="text-center py-3 text-success">
            <i class="bi bi-check-circle-fill fs-2 d-block mb-1"></i>Semua target terpenuhi!</div>`;
    } else {
        html += `<div class="table-responsive">
            <table class="table table-sm mb-0" style="font-size:12px">
            <thead class="table-light"><tr>
                <th>Mapel</th><th>Tingkat</th>
                <th class="text-center">Target</th><th class="text-center">Terisi</th>
                <th class="text-center text-danger">Kurang</th>
            </tr></thead><tbody>`;
        data.warnings.forEach(w => {
            html += `<tr>
                <td>${w.subject}</td><td>${w.grade}</td>
                <td class="text-center">${w.target}</td>
                <td class="text-center">${w.filled}</td>
                <td class="text-center text-danger fw-bold">${w.target - w.filled}</td>
            </tr>`;
        });
        html += `</tbody></table></div>`;
    }
    html += `</div></div></div></div>`;

    document.getElementById('rekapContent').innerHTML = html;
}

function showClassDetail(rowEl, classId, className) {
    // Highlight baris
    document.querySelectorAll('.rekap-kelas-row').forEach(r => r.style.background = '');
    rowEl.style.background = '#EBF5FF';

    document.getElementById('classDetailName').textContent = className;

    if (!rekapData || !rekapData.detail_by_classroom) {
        document.getElementById('classDetailBody').innerHTML =
            `<div class="text-center py-4 text-muted">Data detail tidak tersedia.</div>`;
        return;
    }

    const rows = rekapData.detail_by_classroom.filter(r => String(r.classroom_id) === String(classId));

    if (!rows.length) {
        document.getElementById('classDetailBody').innerHTML =
            `<div class="text-center py-4 text-muted">Belum ada beban mengajar untuk kelas ini.</div>`;
        return;
    }

    const totalJam = rows.reduce((s, r) => s + parseInt(r.hours_per_week||0), 0);
    let html = `<div class="table-responsive">
        <table class="table table-sm mb-0" style="font-size:12px">
        <thead class="table-light"><tr>
            <th>#</th><th>Mata Pelajaran</th><th>Guru</th>
            <th class="text-center">Jam</th><th class="text-center">Split Blok</th>
        </tr></thead><tbody>`;
    rows.forEach((r, i) => {
        html += `<tr>
            <td class="text-muted">${i+1}</td>
            <td class="fw-semibold">${r.subject_name}</td>
            <td>${r.teacher_name}</td>
            <td class="text-center">
                <span class="bm-pill pill-jam" style="font-size:10px">${r.hours_per_week}j</span>
            </td>
            <td class="text-center" style="font-size:11px;color:#6b7280">
                ${r.split_config ? r.split_config : '<span class="text-muted">—</span>'}
            </td>
        </tr>`;
    });
    html += `</tbody>
        <tfoot class="table-light">
            <tr>
                <td colspan="3" class="fw-semibold text-end">Total jam</td>
                <td class="text-center fw-bold text-primary">${totalJam}j</td>
                <td></td>
            </tr>
        </tfoot>
    </table></div>`;

    document.getElementById('classDetailBody').innerHTML = html;
}
</script>
<?= $this->endSection() ?>