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

<?php
/**
 * VIEW: schedule_timeslot/index.php
 * FASE 1 — Step 4: Setting Slot Waktu Harian
 *
 * Yang ditampilkan:
 * - Tab per hari (Senin–Sabtu)
 * - Slot KBM tampil berbeda dari non-KBM (istirahat/upacara/keagamaan)
 * - Ringkasan: berapa jam KBM per hari
 * - Form tambah slot dengan validasi informatif
 * - Copy slot dari hari lain
 * - Upacara khusus Senin — ada peringatan jika diletakkan di hari lain
 */

$dayNames = [1=>'Senin',2=>'Selasa',3=>'Rabu',4=>'Kamis',5=>'Jumat',6=>'Sabtu'];

// Hitung ringkasan per hari
$summary = [];
foreach ($dayNames as $d => $name) {
    $slots    = $grouped[$d] ?? [];
    $kbmCount = count(array_filter($slots, fn($s) => $s['slot_type'] === 'kbm'));
    $summary[$d] = [
        'total'    => count($slots),
        'kbm'      => $kbmCount,
        'nonkbm'   => count($slots) - $kbmCount,
        'slots'    => $slots,
    ];
}

// Cari window kontigu terpanjang per hari (untuk info engine)
function maxContiguousKbm(array $slots): int {
    $max = 0; $cur = 0;
    foreach ($slots as $s) {
        if ($s['slot_type'] === 'kbm' && $s['is_active']) { $cur++; $max = max($max, $cur); }
        elseif ($s['slot_type'] !== 'kbm') { $cur = 0; } // non-KBM memutus, tapi boleh dilompati
    }
    return $max;
}
// Versi "boleh lompat non-KBM" - hitung window KBM yang bisa disambung melewati non-KBM
function maxWindowWithNonKbm(array $slots): int {
    // Ambil hanya KBM aktif, hitung apakah bisa disambung (melewati non-KBM)
    $kbmSlots = array_values(array_filter($slots, fn($s) => $s['slot_type'] === 'kbm' && $s['is_active']));
    if (empty($kbmSlots)) return 0;
    // Window: dari KBM[i] ke KBM[j], tidak boleh ada KBM yang dilewati di antara
    // Artinya: kita cukup lihat urutan index — window max adalah jumlah KBM berurutan
    // yang slot_number-nya tidak diselang oleh KBM lain
    // Karena aturan: boleh melompati non-KBM, window = berapa KBM bisa disambung
    // selama tidak ada KBM lain di luar window di antara slot_number pertama dan terakhir
    // Sebenarnya: window terbesar = seluruh KBM dalam satu "grup" tanpa KBM di luar grup
    // Sederhananya: semua KBM bisa disambung jika tidak ada KBM lain di antara slot_number mereka
    // → window max = count($kbmSlots) (semua KBM selalu bisa disambung satu sama lain)
    // Pembatas sebenarnya adalah: apakah ada KBM yang berada di ANTARA 2 KBM window?
    // Karena tidak boleh ada KBM yang dilompati. Jadi window = KBM berurutan tanpa celah KBM
    // Implementasi sederhana: scan berurutan, non-KBM tidak memutus, KBM yang tidak dipilih memutus
    return count($kbmSlots); // semua KBM dalam satu hari bisa jadi satu window (boleh lompat non-KBM)
}
?>

<style>
/* === Layout === */
.{ width: 100%; }

/* === Day tabs === */
.day-tabs { display:flex; gap:6px; flex-wrap:wrap; margin-bottom:16px; }
.day-tab {
    padding: 7px 18px;
    border-radius: 8px;
    border: 1.5px solid #e5e7eb;
    background: #fff;
    font-size: 12px;
    font-weight: 600;
    cursor: pointer;
    transition: all .15s;
    position: relative;
}
.day-tab:hover { border-color: #6366F1; color: #6366F1; }
.day-tab.active { background: #6366F1; color: #fff; border-color: #6366F1; }
.day-tab .kbm-count {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 18px; height: 18px;
    border-radius: 50%;
    font-size: 10px;
    margin-left: 6px;
    background: rgba(255,255,255,0.25);
}
.day-tab:not(.active) .kbm-count { background: #E1F5EE; color: #085041; }
.day-tab.active .kbm-count { background: rgba(255,255,255,0.3); color: #fff; }

/* === Slot table === */
.slot-tbl { width:100%; border-collapse:collapse; font-size:13px; }
.slot-tbl thead th {
    padding: 8px 12px;
    font-size: 11px;
    font-weight: 600;
    color: #6b7280;
    background: #f9fafb;
    border-bottom: 1px solid #e5e7eb;
}
.slot-tbl tbody tr { transition: background .1s; }
.slot-tbl tbody tr:hover { background: #f9fafb; }
.slot-tbl td { padding: 8px 12px; vertical-align: middle; border-bottom: 1px solid #f3f4f6; }

/* === Slot type styling === */
.slot-row-kbm { }
.slot-row-nonkbm { background: #fafafa; }
.slot-row-nonkbm td { color: #9ca3af; }

.slot-number-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 26px; height: 26px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 700;
}
.badge-kbm    { background: #E1F5EE; color: #085041; }
.badge-istirahat  { background: #FFF3CD; color: #7B5800; }
.badge-upacara    { background: #FBEAF0; color: #72243E; }
.badge-keagamaan  { background: #EEF2FF; color: #3730A3; }
.badge-lainnya    { background: #f3f4f6; color: #6b7280; }

.slot-type-pill {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    font-size: 11px;
    padding: 2px 9px;
    border-radius: 20px;
    font-weight: 600;
}
.pill-kbm       { background: #E1F5EE; color: #085041; }
.pill-istirahat { background: #FFF3CD; color: #7B5800; }
.pill-upacara   { background: #FBEAF0; color: #72243E; }
.pill-keagamaan { background: #EEF2FF; color: #3730A3; }
.pill-lainnya   { background: #f3f4f6; color: #6b7280; }

.non-kbm-note {
    font-size: 10px;
    color: #9ca3af;
    font-style: italic;
}

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

/* === Empty state === */
.empty-day {
    text-align: center;
    padding: 48px 20px;
    color: #9ca3af;
}
.empty-day i { font-size: 2.5rem; display: block; margin-bottom: 12px; opacity: .3; }

/* === Day panel === */
.day-panel { display: none; }
.day-panel.active { display: block; }

/* === Capacity summary === */
.cap-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: 8px;
    margin-bottom: 16px;
}
.cap-card {
    border-radius: 8px;
    padding: 10px 12px;
    border: 1.5px solid #e5e7eb;
    font-size: 12px;
    cursor: pointer;
    transition: all .15s;
}
.cap-card:hover { border-color: #6366F1; }
.cap-card.active { border-color: #6366F1; background: #EEF2FF; }
.cap-card .day-label { font-weight: 700; color: #111827; font-size: 13px; }
.cap-card .kbm-num { font-size: 22px; font-weight: 800; color: #6366F1; line-height: 1; }
.cap-card .kbm-label { font-size: 10px; color: #6b7280; }
.cap-card .window-label { font-size: 10px; color: #9ca3af; margin-top: 2px; }

/* === Modal form === */
.form-select, .form-control { font-size: 13px; }

/* Upacara warning */
.upacara-warning {
    display: none;
    font-size: 11px;
    color: #72243E;
    background: #FBEAF0;
    border-radius: 6px;
    padding: 6px 10px;
    margin-top: 6px;
}
</style>

<!-- ===== PAGE HEADER ===== -->
<div class="d-flex flex-wrap align-items-start justify-content-between gap-2 mb-4">
    <div>
        <h5 class="mb-0 fw-semibold">
            <i class="bi bi-clock me-2 text-primary"></i>Pengaturan Slot Waktu
        </h5>
        <small class="text-muted">
            Atur jam KBM, istirahat, upacara, dan keagamaan per hari.<br>
            <strong>Hanya slot bertipe KBM yang bisa diisi pelajaran oleh engine generate.</strong>
        </small>
    </div>
    <div class="d-flex gap-2">
        <button class="btn btn-sm btn-outline-danger" onclick="confirmClearDay()">
            <i class="bi bi-trash me-1"></i>Kosongkan Hari Ini
        </button>
        <button class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#modalCopyDay">
            <i class="bi bi-copy me-1"></i>Salin dari Hari Lain
        </button>
        <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#modalAddSlot">
            <i class="bi bi-plus-lg me-1"></i>Tambah Slot
        </button>
    </div>
</div>

<form id="formClearDay" action="/schedule-timeslot/delete-day" method="post" style="display:none;">
    <?= csrf_field() ?>
    <input type="hidden" name="day" id="clearDayInput" value="">
</form>

<?php if (session()->getFlashdata('success')): ?>
<div class="alert alert-success alert-dismissible fade show py-2 mb-3" role="alert">
    <i class="bi bi-check-circle me-2"></i><?= session()->getFlashdata('success') ?>
    <button type="button" class="btn-close btn-sm" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<?php if (session()->getFlashdata('error')): ?>
<div class="alert alert-danger alert-dismissible fade show py-2 mb-3" role="alert">
    <i class="bi bi-exclamation-circle me-2"></i><?= session()->getFlashdata('error') ?>
    <button type="button" class="btn-close btn-sm" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- ===== RINGKASAN KAPASITAS (klik untuk pindah tab) ===== -->
<div class="cap-grid" id="capGrid">
<?php foreach ($dayNames as $d => $name): ?>
<?php
    $s   = $summary[$d];
    $kbm = $s['kbm'];
    $win = maxWindowWithNonKbm($s['slots']);
?>
<div class="cap-card <?= $selectedDay == $d ? 'active' : '' ?>" onclick="switchDay(<?= $d ?>)" id="cap-<?= $d ?>">
    <div class="day-label"><?= $name ?></div>
    <div class="kbm-num"><?= $kbm ?></div>
    <div class="kbm-label">jam KBM / minggu</div>
    <div class="window-label">
        <?php if ($kbm === 0): ?>
        <span class="text-danger">⚠ Belum ada slot KBM</span>
        <?php else: ?>
        <?= $s['total'] ?> slot total · <?= $s['nonkbm'] ?> non-KBM
        <?php endif; ?>
    </div>
</div>
<?php endforeach; ?>
</div>

<!-- Info kapasitas total -->
<?php
$totalKbm = array_sum(array_column($summary, 'kbm'));
?>
<div class="info-box info mb-3">
    <i class="bi bi-info-circle-fill flex-shrink-0 mt-1"></i>
    <div>
        <strong>Total kapasitas KBM: <?= $totalKbm ?> jam/kelas/minggu</strong>
        <?php if ($totalKbm === 0): ?>
        &nbsp;—&nbsp;<span class="text-danger fw-semibold">Belum ada slot KBM! Engine generate tidak bisa berjalan.</span>
        <?php else: ?>
        &nbsp;—&nbsp;Dengan <?php
            $classCount = \Config\Database::connect()->table('classrooms')->where('deleted_at', null)->countAllResults();
        ?><strong><?= $classCount ?> kelas</strong>, kapasitas total = <strong><?= $totalKbm * $classCount ?> slot</strong>/minggu.
        Engine generate hanya akan mengisi slot bertipe <span class="fw-semibold" style="color:#085041">KBM</span>.
        <?php endif; ?>
    </div>
</div>

<!-- ===== TAB PER HARI ===== -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white border-bottom py-2 px-3">
        <div class="day-tabs" id="dayTabs">
            <?php foreach ($dayNames as $d => $name): ?>
            <button class="day-tab <?= $selectedDay == $d ? 'active' : '' ?>"
                    onclick="switchDay(<?= $d ?>)" id="tab-<?= $d ?>">
                <?= $name ?>
                <span class="kbm-count"><?= $summary[$d]['kbm'] ?></span>
            </button>
            <?php endforeach; ?>
        </div>
    </div>

    <div class="card-body p-0">
        <?php foreach ($dayNames as $d => $name): ?>
        <div class="day-panel <?= $selectedDay == $d ? 'active' : '' ?>" id="panel-<?= $d ?>">
            <?php
            $slots = $summary[$d]['slots'];
            $kbmCount = $summary[$d]['kbm'];
            ?>

            <?php if ($d == 1): ?>
            <!-- Peringatan khusus Senin: upacara -->
            <div class="info-box warn m-3 mb-0">
                <i class="bi bi-flag-fill flex-shrink-0 mt-1"></i>
                <div>
                    <strong>Hari Senin:</strong> Upacara biasanya menempati slot pertama.
                    Pastikan Slot 1 bertipe <strong>Upacara</strong> agar engine tidak menempatkan pelajaran di slot tersebut.
                    Guru yang tidak ikut upacara bisa mengajar mulai jam KBM pertama.
                </div>
            </div>
            <?php endif; ?>

            <?php if (empty($slots)): ?>
            <div class="empty-day">
                <i class="bi bi-clock-history"></i>
                <p class="mb-3">Belum ada slot waktu untuk hari <?= $name ?>.</p>
                <button class="btn btn-primary btn-sm" onclick="openAddModal(<?= $d ?>)">
                    <i class="bi bi-plus-lg me-1"></i>Tambah Slot Pertama
                </button>
            </div>

            <?php else: ?>

            <!-- Info ringkasan hari ini -->
            <div class="d-flex align-items-center gap-3 px-3 py-2 border-bottom bg-light" style="font-size:12px">
                <span>
                    <i class="bi bi-book text-success me-1"></i>
                    <strong><?= $kbmCount ?></strong> jam KBM
                </span>
                <?php if ($summary[$d]['nonkbm'] > 0): ?>
                <span class="text-muted">
                    <i class="bi bi-dash-circle me-1"></i>
                    <?= $summary[$d]['nonkbm'] ?> slot non-KBM (tidak bisa diisi mapel)
                </span>
                <?php endif; ?>
                <?php if ($kbmCount === 0): ?>
                <span class="text-danger fw-semibold">
                    <i class="bi bi-exclamation-triangle me-1"></i>
                    Tidak ada slot KBM! Engine tidak akan menjadwalkan hari ini.
                </span>
                <?php endif; ?>
                <div class="ms-auto">
                    <button class="btn btn-outline-primary btn-sm py-0 px-2" onclick="openAddModal(<?= $d ?>)">
                        <i class="bi bi-plus me-1"></i>Tambah
                    </button>
                </div>
            </div>

            <div class="table-responsive">
                <table class="slot-tbl">
                    <thead>
                        <tr>
                            <th style="width:50px">No.</th>
                            <th style="width:80px">Tipe</th>
                            <th>Label</th>
                            <th>Mulai</th>
                            <th>Selesai</th>
                            <th class="text-center" style="width:70px">Aktif</th>
                            <th class="text-center" style="width:120px">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($slots as $slot): ?>
                    <?php
                        $isKbm    = $slot['slot_type'] === 'kbm';
                        $typeInfo = $slotTypes[$slot['slot_type']] ?? ['label'=>$slot['slot_type'],'icon'=>'bi-dot'];
                        $rowClass = $isKbm ? 'slot-row-kbm' : 'slot-row-nonkbm';
                        $badgeCls = 'badge-' . $slot['slot_type'];
                        $pillCls  = 'pill-'  . $slot['slot_type'];
                    ?>
                    <tr class="<?= $rowClass ?>">
                        <td>
                            <span class="slot-number-badge <?= $badgeCls ?>">
                                <?= $slot['slot_number'] ?>
                            </span>
                        </td>
                        <td>
                            <span class="slot-type-pill <?= $pillCls ?>">
                                <i class="bi <?= $typeInfo['icon'] ?>"></i>
                                <?= $typeInfo['label'] ?>
                            </span>
                            <?php if (!$isKbm): ?>
                            <div class="non-kbm-note mt-1">tidak bisa diisi mapel</div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="fw-semibold <?= !$isKbm ? 'text-muted' : '' ?>">
                                <?= esc($slot['label']) ?>
                            </span>
                        </td>
                        <td><?= esc($slot['start_time']) ?></td>
                        <td><?= esc($slot['end_time']) ?></td>
                        <td class="text-center">
                            <?php if ($slot['is_active']): ?>
                            <span class="badge bg-success-subtle text-success" style="font-size:10px">Aktif</span>
                            <?php else: ?>
                            <span class="badge bg-secondary-subtle text-secondary" style="font-size:10px">Nonaktif</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-center">
                            <div class="d-flex gap-1 justify-content-center">
                                <!-- Toggle aktif -->
                                <a href="/schedule-timeslot/toggle-active/<?= $slot['id'] ?>"
                                   class="btn btn-sm btn-outline-secondary py-0 px-2"
                                   title="<?= $slot['is_active'] ? 'Nonaktifkan' : 'Aktifkan' ?>"
                                   onclick="return confirm('Ubah status slot ini?')">
                                    <i class="bi <?= $slot['is_active'] ? 'bi-eye-slash' : 'bi-eye' ?>"></i>
                                </a>
                                <!-- Edit -->
                                <button class="btn btn-sm btn-outline-primary py-0 px-2"
                                        onclick="openEditModal(<?= htmlspecialchars(json_encode($slot)) ?>)"
                                        title="Edit">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <!-- Hapus -->
                                <a href="/schedule-timeslot/delete/<?= $slot['id'] ?>"
                                   class="btn btn-sm btn-outline-danger py-0 px-2"
                                   title="Hapus"
                                   onclick="return confirmDelete(<?= $slot['id'] ?>, '<?= esc($slot['label']) ?>')">
                                    <i class="bi bi-trash"></i>
                                </a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($kbmCount >= 3): ?>
            <!-- Info blok: apakah blok 3 jam bisa masuk? -->
            <div class="px-3 py-2 border-top" style="font-size:11px;color:#6b7280;background:#fafafa">
                <i class="bi bi-lightning-charge text-warning me-1"></i>
                <strong>Info engine:</strong>
                Blok 3 jam bisa ditempatkan di hari ini (ada <?= $kbmCount ?> slot KBM, melewati non-KBM diperbolehkan).
                <?php if ($kbmCount < 3): ?>
                <span class="text-danger fw-semibold">Blok 3 jam tidak bisa masuk — hanya ada <?= $kbmCount ?> jam KBM.</span>
                <?php endif; ?>
            </div>
            <?php elseif ($kbmCount > 0 && $kbmCount < 3): ?>
            <div class="info-box warn m-3 mt-2">
                <i class="bi bi-exclamation-triangle-fill flex-shrink-0"></i>
                <div>
                    Hanya ada <strong><?= $kbmCount ?> jam KBM</strong> di hari <?= $name ?>.
                    <strong>Blok 3 jam tidak bisa ditempatkan di hari ini.</strong>
                    Jika ada mapel dengan split blok 3 jam, engine akan melewati hari ini untuk blok tersebut.
                </div>
            </div>
            <?php endif; ?>

            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- ================================================================
     MODAL: TAMBAH SLOT
     ================================================================ -->
<div class="modal fade" id="modalAddSlot" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header border-bottom py-2 px-3">
                <h6 class="modal-title fw-semibold mb-0">
                    <i class="bi bi-plus-circle me-2 text-primary"></i>Tambah Slot Waktu
                </h6>
                <button type="button" class="btn-close btn-sm" data-bs-dismiss="modal"></button>
            </div>
            <form action="/schedule-timeslot/store" method="post">
                <?= csrf_field() ?>
                <div class="modal-body p-3">

                    <!-- Pilih hari -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold" style="font-size:13px">Hari <span class="text-danger">*</span></label>
                        <select name="day" id="addDay" class="form-select" required onchange="checkUpacaraWarning()">
                            <?php foreach ($dayNames as $d => $name): ?>
                            <option value="<?= $d ?>" <?= $selectedDay == $d ? 'selected' : '' ?>><?= $name ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- Tipe slot -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold" style="font-size:13px">Tipe Slot <span class="text-danger">*</span></label>
                        <select name="slot_type" id="addSlotType" class="form-select" required onchange="onSlotTypeChange()">
                            <?php foreach ($slotTypes as $key => $info): ?>
                            <option value="<?= $key ?>"><?= $info['label'] ?></option>
                            <?php endforeach; ?>
                        </select>

                        <!-- Penjelasan per tipe -->
                        <div id="typeDesc" class="mt-2 px-2 py-1 rounded" style="font-size:11px;background:#f9fafb;color:#6b7280">
                            Slot <strong>KBM</strong>: Dapat diisi mata pelajaran oleh engine generate.
                        </div>

                        <!-- Warning upacara di hari bukan Senin -->
                        <div class="upacara-warning" id="upacaraWarning">
                            <i class="bi bi-exclamation-triangle-fill me-1"></i>
                            <strong>Perhatian:</strong> Upacara biasanya hanya ada di hari Senin.
                            Apakah Anda yakin ingin menambah slot Upacara di hari ini?
                        </div>
                    </div>

                    <div class="row g-2 mb-3">
                        <!-- Nomor urut -->
                        <div class="col-4">
                            <label class="form-label fw-semibold" style="font-size:13px">Urutan <span class="text-danger">*</span></label>
                            <input type="number" name="slot_number" id="addSlotNumber" class="form-control"
                                   min="1" max="20" required placeholder="1">
                            <div class="form-text" style="font-size:10px">Urutan fisik dari atas</div>
                        </div>
                        <!-- Label -->
                        <div class="col-8">
                            <label class="form-label fw-semibold" style="font-size:13px">Label <span class="text-danger">*</span></label>
                            <input type="text" name="label" id="addLabel" class="form-control"
                                   maxlength="30" required placeholder="cth: Jam 1, Istirahat">
                        </div>
                    </div>

                    <div class="row g-2 mb-3">
                        <div class="col-6">
                            <label class="form-label fw-semibold" style="font-size:13px">Mulai <span class="text-danger">*</span></label>
                            <input type="time" name="start_time" class="form-control" required>
                        </div>
                        <div class="col-6">
                            <label class="form-label fw-semibold" style="font-size:13px">Selesai <span class="text-danger">*</span></label>
                            <input type="time" name="end_time" class="form-control" required>
                        </div>
                    </div>

                    <!-- Info visual blok -->
                    <div id="kbmBlockInfo" class="info-box info" style="font-size:11px">
                        <i class="bi bi-info-circle-fill flex-shrink-0"></i>
                        <div>
                            Slot KBM akan dapat diisi pelajaran. Pastikan slot disusun berurutan
                            agar engine bisa menempatkan blok 2–3 jam secara kontigu.
                        </div>
                    </div>
                    <div id="nonKbmBlockInfo" class="info-box warn" style="font-size:11px;display:none">
                        <i class="bi bi-dash-circle-fill flex-shrink-0"></i>
                        <div>
                            Slot <strong>non-KBM</strong> tidak bisa diisi pelajaran.
                            Engine generate akan melompatinya, tapi blok yang melewatinya masih dianggap kontigu.
                        </div>
                    </div>

                </div>
                <div class="modal-footer border-top py-2 px-3">
                    <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-sm btn-primary">
                        <i class="bi bi-plus-lg me-1"></i>Tambah Slot
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ================================================================
     MODAL: EDIT SLOT
     ================================================================ -->
<div class="modal fade" id="modalEditSlot" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header border-bottom py-2 px-3">
                <h6 class="modal-title fw-semibold mb-0">
                    <i class="bi bi-pencil me-2 text-primary"></i>Edit Slot Waktu
                </h6>
                <button type="button" class="btn-close btn-sm" data-bs-dismiss="modal"></button>
            </div>
            <form id="editForm" method="post">
                <?= csrf_field() ?>
                <div class="modal-body p-3">

                    <!-- Info tidak bisa ubah hari/urutan -->
                    <div class="info-box info mb-3" style="font-size:11px">
                        <i class="bi bi-info-circle-fill flex-shrink-0"></i>
                        <div>Hari dan nomor urut tidak bisa diubah. Jika perlu mengubah urutan, hapus dan buat ulang.</div>
                    </div>

                    <div class="mb-2 d-flex gap-3" style="font-size:13px">
                        <span><strong>Hari:</strong> <span id="editDayLabel"></span></span>
                        <span><strong>Urutan:</strong> <span id="editSlotNumLabel"></span></span>
                    </div>

                    <!-- Tipe slot -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold" style="font-size:13px">Tipe Slot <span class="text-danger">*</span></label>
                        <select name="slot_type" id="editSlotType" class="form-select" required onchange="onEditSlotTypeChange()">
                            <?php foreach ($slotTypes as $key => $info): ?>
                            <option value="<?= $key ?>"><?= $info['label'] ?></option>
                            <?php endforeach; ?>
                        </select>
                        <div id="editTypeChange" class="info-box warn mt-2" style="font-size:11px;display:none">
                            <i class="bi bi-exclamation-triangle-fill flex-shrink-0"></i>
                            <div>
                                Mengubah tipe dari/ke KBM akan mempengaruhi kapasitas generate.
                                <strong>Jika jadwal sudah di-generate, lakukan reset dan generate ulang.</strong>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold" style="font-size:13px">Label <span class="text-danger">*</span></label>
                        <input type="text" name="label" id="editLabel" class="form-control" maxlength="30" required>
                    </div>

                    <div class="row g-2">
                        <div class="col-6">
                            <label class="form-label fw-semibold" style="font-size:13px">Mulai <span class="text-danger">*</span></label>
                            <input type="time" name="start_time" id="editStartTime" class="form-control" required>
                        </div>
                        <div class="col-6">
                            <label class="form-label fw-semibold" style="font-size:13px">Selesai <span class="text-danger">*</span></label>
                            <input type="time" name="end_time" id="editEndTime" class="form-control" required>
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-top py-2 px-3">
                    <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-sm btn-primary">
                        <i class="bi bi-check-lg me-1"></i>Simpan Perubahan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ================================================================
     MODAL: COPY DAY
     ================================================================ -->
<div class="modal fade" id="modalCopyDay" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header border-bottom py-2 px-3">
                <h6 class="modal-title fw-semibold mb-0">
                    <i class="bi bi-copy me-2 text-primary"></i>Salin Slot dari Hari Lain
                </h6>
                <button type="button" class="btn-close btn-sm" data-bs-dismiss="modal"></button>
            </div>
            <form action="/schedule-timeslot/copy-day" method="post">
                <?= csrf_field() ?>
                <div class="modal-body p-3">
                    <div class="info-box info mb-3" style="font-size:11px">
                        <i class="bi bi-info-circle-fill flex-shrink-0"></i>
                        <div>
                            Salin semua slot dari hari sumber ke hari tujuan.
                            Slot yang sudah ada di hari tujuan tidak akan ditimpa (dilewati).
                            <strong>Tip: Setup Senin dulu (dengan Upacara), lalu salin ke hari lain, kemudian ubah Upacara → KBM di hari lain.</strong>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold" style="font-size:13px">Salin dari Hari <span class="text-danger">*</span></label>
                        <select name="from_day" class="form-select" required>
                            <?php foreach ($dayNames as $d => $name): ?>
                            <option value="<?= $d ?>" <?= $selectedDay == $d ? 'selected' : '' ?>>
                                <?= $name ?> (<?= $summary[$d]['total'] ?> slot)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold d-block mb-2" style="font-size:13px">
                            Salin ke Hari <span class="text-danger">*</span>
                        </label>
                        <div class="d-flex flex-wrap gap-2">
                            <?php foreach ($dayNames as $d => $name): ?>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox"
                                       name="to_days[]" value="<?= $d ?>"
                                       id="copyTo<?= $d ?>">
                                <label class="form-check-label" for="copyTo<?= $d ?>" style="font-size:13px">
                                    <?= $name ?>
                                    <small class="text-muted">(<?= $summary[$d]['total'] ?>)</small>
                                </label>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-top py-2 px-3">
                    <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-sm btn-primary">
                        <i class="bi bi-copy me-1"></i>Salin Slot
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ================================================================
     MODAL: KONFIRMASI HAPUS
     ================================================================ -->
<div class="modal fade" id="modalDeleteConfirm" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content">
            <div class="modal-body p-4 text-center">
                <i class="bi bi-trash fs-1 text-danger opacity-50 d-block mb-3"></i>
                <p class="mb-1 fw-semibold" id="deleteLabel">Hapus slot ini?</p>
                <p class="text-muted mb-3" style="font-size:12px">
                    Jika slot ini sudah ada dalam jadwal yang di-generate,
                    <strong>lakukan reset jadwal terlebih dahulu</strong> sebelum menghapus.
                </p>
                <div class="d-flex gap-2 justify-content-center">
                    <button class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Batal</button>
                    <a id="deleteLink" href="#" class="btn btn-sm btn-danger">
                        <i class="bi bi-trash me-1"></i>Hapus
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
const dayNames = {1:'Senin',2:'Selasa',3:'Rabu',4:'Kamis',5:'Jumat',6:'Sabtu'};

// ── Switch tab hari ──────────────────────────────────────────────
function switchDay(day) {
    document.querySelectorAll('.day-panel').forEach(p => p.classList.remove('active'));
    document.querySelectorAll('.day-tab').forEach(t => t.classList.remove('active'));
    document.querySelectorAll('.cap-card').forEach(c => c.classList.remove('active'));

    document.getElementById('panel-' + day).classList.add('active');
    document.getElementById('tab-'   + day).classList.add('active');
    document.getElementById('cap-'   + day).classList.add('active');

    // Update URL tanpa reload
    history.replaceState(null, '', '?day=' + day);

    // Update form tambah
    document.getElementById('addDay').value = day;
    autoFillSlotNumber(day);
    checkUpacaraWarning();
}

// ── Auto-isi nomor urut berikutnya ──────────────────────────────
const slotCounts = <?= json_encode(array_map(fn($s) => $s['total'], $summary)) ?>;
function autoFillSlotNumber(day) {
    const count = slotCounts[day] ?? 0;
    document.getElementById('addSlotNumber').value = count + 1;
    document.getElementById('addLabel').value = '';

    // Saran label berdasarkan tipe
    const type = document.getElementById('addSlotType').value;
    suggestLabel(type, count + 1);
}

// ── Saran label otomatis ─────────────────────────────────────────
const kbmCount = <?= json_encode(array_map(fn($s) => $s['kbm'], $summary)) ?>;
function suggestLabel(type, slotNum) {
    const day = parseInt(document.getElementById('addDay').value);
    const currentKbm = kbmCount[day] ?? 0;
    const labelEl = document.getElementById('addLabel');
    if (labelEl.value !== '') return; // jangan timpa kalau sudah diisi

    if (type === 'kbm')       labelEl.value = 'Jam ' + (currentKbm + 1);
    else if (type === 'istirahat')  labelEl.value = 'Istirahat';
    else if (type === 'upacara')    labelEl.value = 'Upacara';
    else if (type === 'keagamaan')  labelEl.value = 'Kegiatan Keagamaan';
    else labelEl.value = '';
}

// ── Deskripsi tipe slot ──────────────────────────────────────────
const typeDescs = {
    kbm:       { text: 'Slot <strong>KBM</strong>: Dapat diisi mata pelajaran oleh engine generate.', cls: '#f0fdf4', color: '#14532d' },
    istirahat: { text: 'Slot <strong>Istirahat</strong>: Tidak bisa diisi pelajaran. Engine akan melompatinya, tapi blok yang melewatinya tetap dianggap kontigu.', cls: '#fffbeb', color: '#7B5800' },
    upacara:   { text: 'Slot <strong>Upacara</strong>: Tidak bisa diisi pelajaran. Sebaiknya hanya di hari Senin.', cls: '#fff1f2', color: '#881337' },
    keagamaan: { text: 'Slot <strong>Kegiatan Keagamaan</strong>: Tidak bisa diisi pelajaran. Engine akan melompatinya.', cls: '#eef2ff', color: '#3730A3' },
    lainnya:   { text: 'Slot <strong>Lainnya</strong>: Tidak bisa diisi pelajaran.', cls: '#f9fafb', color: '#6b7280' },
};

function onSlotTypeChange() {
    const type = document.getElementById('addSlotType').value;
    const desc = typeDescs[type];
    const el   = document.getElementById('typeDesc');
    el.innerHTML = desc.text;
    el.style.background = desc.cls;
    el.style.color = desc.color;

    // Show/hide info blok
    const isKbm = type === 'kbm';
    document.getElementById('kbmBlockInfo').style.display    = isKbm ? '' : 'none';
    document.getElementById('nonKbmBlockInfo').style.display = isKbm ? 'none' : '';

    // Saran label
    document.getElementById('addLabel').value = '';
    const slotNum = parseInt(document.getElementById('addSlotNumber').value);
    suggestLabel(type, slotNum);

    checkUpacaraWarning();
}

function checkUpacaraWarning() {
    const type = document.getElementById('addSlotType').value;
    const day  = parseInt(document.getElementById('addDay').value);
    const warn = document.getElementById('upacaraWarning');
    warn.style.display = (type === 'upacara' && day !== 1) ? 'block' : 'none';
}

// ── Edit modal ────────────────────────────────────────────────────
function openEditModal(slot) {
    const form = document.getElementById('editForm');
    form.action = '/schedule-timeslot/update/' + slot.id;

    document.getElementById('editDayLabel').textContent    = dayNames[slot.day] || slot.day;
    document.getElementById('editSlotNumLabel').textContent = slot.slot_number;
    document.getElementById('editSlotType').value           = slot.slot_type;
    document.getElementById('editLabel').value              = slot.label;
    document.getElementById('editStartTime').value          = slot.start_time;
    document.getElementById('editEndTime').value            = slot.end_time;

    document.getElementById('editTypeChange').style.display = 'none';
    const origType = slot.slot_type;
    document.getElementById('editSlotType').dataset.orig = origType;

    new bootstrap.Modal(document.getElementById('modalEditSlot')).show();
}

function onEditSlotTypeChange() {
    const el    = document.getElementById('editSlotType');
    const orig  = el.dataset.orig;
    const now   = el.value;
    const warn  = document.getElementById('editTypeChange');
    // Tampilkan warning jika tipe berubah dari/ke KBM
    warn.style.display = (orig !== now && (orig === 'kbm' || now === 'kbm')) ? '' : 'none';
}

// ── Add modal shortcut ────────────────────────────────────────────
function openAddModal(day) {
    document.getElementById('addDay').value = day;
    autoFillSlotNumber(day);
    onSlotTypeChange();
    new bootstrap.Modal(document.getElementById('modalAddSlot')).show();
}

// ── Hapus dengan konfirmasi ──────────────────────────────────────
function confirmDelete(id, label) {
    document.getElementById('deleteLabel').textContent = 'Hapus slot "' + label + '"?';
    document.getElementById('deleteLink').href = '/schedule-timeslot/delete/' + id;
    new bootstrap.Modal(document.getElementById('modalDeleteConfirm')).show();
    return false; // stop default link
}

// ── Kosongkan Hari Ini ───────────────────────────────────────────
function confirmClearDay() {
    const day = parseInt(document.getElementById('addDay').value);
    const dayName = dayNames[day] || 'hari ini';
    if (confirm('Apakah Anda yakin ingin menghapus SEMUA slot waktu pada hari ' + dayName + '?\n\nTindakan ini tidak dapat dibatalkan.')) {
        document.getElementById('clearDayInput').value = day;
        document.getElementById('formClearDay').submit();
    }
}

// ── Init ──────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', function() {
    onSlotTypeChange();
    autoFillSlotNumber(<?= $selectedDay ?>);
});
</script>
<?= $this->endSection() ?>