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

<?php
/**
 * VIEW: schedule_availability/edit.php
 * FASE 3 — Ketersediaan Guru
 * Tab 1: Batas Jam Mengajar per Hari
 * Tab 2: Grid Slot Tidak Tersedia
 */
$dayNames = [1=>'Senin',2=>'Selasa',3=>'Rabu',4=>'Kamis',5=>'Jumat',6=>'Sabtu'];

// Hitung jam KBM per hari dari grouped slots
$kbmPerDay = [];
foreach ($grouped as $day => $slots) {
    $kbmPerDay[$day] = count(array_filter($slots, fn($s) => $s['slot_type'] === 'kbm' && $s['is_active']));
}

// Effective max hours
$effectiveMax = $setting['max_hours_per_day'] ?? $defaultMax;
$isCustom     = $setting['max_hours_per_day'] !== null;

// Hitung total blocked
$totalBlocked = 0;
foreach ($blockedMap as $day => $slots) {
    $totalBlocked += count($slots);
}
?>

<style>
/* ── Tabs ── */
.tab-custom { display:flex; gap:4px; background:#f1f5f9; border-radius:12px; padding:4px; margin-bottom:18px; }
.tab-custom button { flex:1; padding:8px 16px; border:none; background:transparent; border-radius:8px; font-size:13px; font-weight:500; color:#64748b; cursor:pointer; transition:all .2s; }
.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; }

/* ── Grid ketersediaan ── */
.av-grid { width:100%; border-collapse:collapse; }
.av-grid th { padding:8px 6px; font-size:11px; font-weight:600; color:#6b7280; background:#f9fafb; border:1px solid #e5e7eb; text-align:center; }
.av-grid td { padding:4px; border:1px solid #f3f4f6; text-align:center; vertical-align:middle; }
.av-grid .day-head { background:#f9fafb; font-size:11px; font-weight:700; color:#374151; min-width:70px; }
.av-grid .day-kbm  { font-size:10px; color:#6b7280; font-weight:400; display:block; }

/* ── Slot cell ── */
.slot-cell {
    width: 36px; height: 36px;
    border-radius: 6px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-size: 11px;
    font-weight: 600;
    transition: all .15s;
    user-select: none;
    border: 1.5px solid transparent;
}
.slot-cell.kbm-free {
    background: #E1F5EE;
    color: #085041;
    border-color: #A7F3D0;
}
.slot-cell.kbm-free:hover { background:#22c55e; color:#fff; border-color:#16a34a; transform:scale(1.08); }
.slot-cell.kbm-blocked {
    background: #FBEAF0;
    color: #72243E;
    border-color: #FECDD3;
}
.slot-cell.kbm-blocked:hover { background:#dc2626; color:#fff; border-color:#b91c1c; transform:scale(1.08); }
.slot-cell.non-kbm {
    background: #f3f4f6;
    color: #d1d5db;
    cursor: not-allowed;
    font-size: 10px;
}
.slot-cell.non-kbm:hover { transform:none; }
.slot-cell.whole-day-blocked {
    background: #FEF2F2;
    color: #dc2626;
}

/* ── Hari penuh diblokir ── */
.day-row.all-blocked td { background: #fff5f5; }
.block-whole-day-btn {
    font-size: 10px; padding: 2px 7px;
    border-radius: 12px; border: 1px solid #e5e7eb;
    background: #fff; cursor: pointer; color: #6b7280;
    transition: all .15s;
}
.block-whole-day-btn:hover { background:#fee2e2; color:#dc2626; border-color:#fca5a5; }
.block-whole-day-btn.active { background:#fee2e2; color:#dc2626; border-color:#fca5a5; }

/* ── Stat pills ── */
.stat-pill { font-size:11px; padding:2px 9px; border-radius:20px; font-weight:600; }
.pill-ok    { background:#E1F5EE; color:#085041; }
.pill-warn  { background:#FFFBEB; color:#7B5800; }
.pill-block { background:#FBEAF0; color:#72243E; }

/* ── 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.ok    { background:#F0FDF4; color:#14532D; border:1px solid #BBF7D0; }

/* ── Legend ── */
.legend-item { display:inline-flex; align-items:center; gap:5px; font-size:11px; color:#6b7280; }
.legend-box  { width:16px; height:16px; border-radius:3px; display:inline-block; }
</style>

<!-- ── BREADCRUMB & HEADER ── -->
<div class="d-flex align-items-center gap-2 mb-1">
    <a href="/schedule-availability" class="btn btn-sm btn-outline-secondary py-0 px-2">
        <i class="bi bi-arrow-left"></i>
    </a>
    <div>
        <h5 class="mb-0 fw-semibold">
            <i class="bi bi-slash-circle me-2 text-primary"></i>Ketersediaan —
            <span class="text-primary"><?= esc($teacher['name']) ?></span>
        </h5>
        <small class="text-muted"><?= esc(teacher_id_display($teacher)) ?></small>
    </div>
</div>

<!-- Stat bar -->
<div class="d-flex gap-2 mb-3 flex-wrap">
    <span class="stat-pill pill-ok">
        <i class="bi bi-clock me-1"></i>Maks <?= $effectiveMax ?> jam/hari
        <?= $isCustom ? '(custom)' : '(default)' ?>
    </span>
    <?php if ($totalBlocked === 0): ?>
    <span class="stat-pill pill-ok"><i class="bi bi-check-circle me-1"></i>Bebas semua slot</span>
    <?php else: ?>
    <span class="stat-pill pill-block"><i class="bi bi-x-circle me-1"></i><?= $totalBlocked ?> slot diblokir</span>
    <?php endif; ?>
</div>

<!-- ── TABS ── -->
<div class="tab-custom">
    <button class="tab-btn active" data-tab="tab1">
        <i class="bi bi-hourglass-split me-1"></i>Batas Jam / Hari
    </button>
    <button class="tab-btn" data-tab="tab2">
        <i class="bi bi-grid me-1"></i>Slot Tidak Tersedia
    </button>
</div>

<!-- ══════════════════════════════
     TAB 1: BATAS JAM
══════════════════════════════ -->
<div class="tab-pane active" id="tab1">
    <div class="row justify-content-center">
        <div class="col-lg-6">
            <div class="card border-0 shadow-sm">
                <div class="card-body p-4">
                    <div class="ibox info mb-4">
                        <i class="bi bi-info-circle-fill flex-shrink-0 mt-1"></i>
                        <div>
                            Batas jam mengajar maksimal per hari untuk guru ini.
                            <strong>Default global: <?= $defaultMax ?> jam/hari.</strong>
                            Kosongkan untuk kembali ke default.
                            Engine generate tidak akan menempatkan lebih dari batas ini dalam satu hari.
                        </div>
                    </div>

                    <!-- Visual bar max jam -->
                    <div class="mb-4">
                        <div class="d-flex justify-content-between mb-1" style="font-size:12px">
                            <span class="text-muted">Batas saat ini</span>
                            <span class="fw-semibold" id="maxHoursDisplay"><?= $effectiveMax ?> jam / hari</span>
                        </div>
                        <div style="background:#e5e7eb;border-radius:6px;height:10px;overflow:hidden">
                            <div id="maxHoursBar"
                                 style="height:100%;border-radius:6px;background:#6366F1;transition:width .3s;width:<?= round($effectiveMax/12*100) ?>%"></div>
                        </div>
                        <div class="d-flex justify-content-between mt-1" style="font-size:10px;color:#9ca3af">
                            <span>1 jam</span><span>6 jam (default)</span><span>12 jam</span>
                        </div>
                    </div>

                    <form id="formSettings">
                        <div class="mb-3">
                            <label class="form-label fw-semibold" style="font-size:13px">
                                Maks Jam Mengajar / Hari
                            </label>
                            <div class="input-group">
                                <input type="number" id="maxHoursInput" class="form-control"
                                       value="<?= $isCustom ? $effectiveMax : '' ?>"
                                       min="1" max="12"
                                       placeholder="Kosong = gunakan default (<?= $defaultMax ?> jam)">
                                <span class="input-group-text">jam</span>
                            </div>
                            <div class="form-text">
                                Rentang: 1–12 jam. Default global saat ini: <strong><?= $defaultMax ?> jam</strong>.
                            </div>
                        </div>

                        <!-- Info feasibilitas -->
                        <div id="feasibilityInfo" class="ibox info mb-3" style="font-size:11px">
                            <i class="bi bi-calculator flex-shrink-0"></i>
                            <div id="feasibilityText">Isi batas jam untuk melihat analisis jadwal.</div>
                        </div>

                        <div class="mb-4">
                            <label class="form-label fw-semibold" style="font-size:13px">Catatan</label>
                            <textarea id="notesInput" class="form-control" rows="2"
                                      placeholder="Opsional..."><?= esc($setting['notes'] ?? '') ?></textarea>
                        </div>

                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary" id="btnSaveSettings">
                                <i class="bi bi-save me-1"></i>Simpan Pengaturan
                            </button>
                            <?php if ($isCustom): ?>
                            <button type="button" class="btn btn-outline-secondary" id="btnResetDefault">
                                <i class="bi bi-arrow-counterclockwise me-1"></i>Reset ke Default
                            </button>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ══════════════════════════════
     TAB 2: GRID SLOT
══════════════════════════════ -->
<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>
            Klik slot <span style="color:#085041;font-weight:600">hijau</span> untuk memblokir (guru tidak tersedia).
            Klik slot <span style="color:#72243E;font-weight:600">merah</span> untuk membuka kembali.
            Slot abu-abu (istirahat/upacara/keagamaan) tidak perlu diblokir — sudah otomatis tidak diisi engine.
            <strong>Klik "Simpan" setelah selesai mengatur.</strong>
        </div>
    </div>

    <!-- Legend -->
    <div class="d-flex gap-3 mb-3 flex-wrap">
        <span class="legend-item">
            <span class="legend-box" style="background:#E1F5EE;border:1.5px solid #A7F3D0"></span>Tersedia (KBM)
        </span>
        <span class="legend-item">
            <span class="legend-box" style="background:#FBEAF0;border:1.5px solid #FECDD3"></span>Diblokir
        </span>
        <span class="legend-item">
            <span class="legend-box" style="background:#f3f4f6;border:1px solid #e5e7eb"></span>Non-KBM (otomatis)
        </span>
    </div>

    <!-- Stat realtime -->
    <div class="d-flex gap-2 mb-3 align-items-center flex-wrap">
        <span class="stat-pill pill-block" id="blockedCount">
            <i class="bi bi-x-circle me-1"></i><span id="blockedNum"><?= $totalBlocked ?></span> slot diblokir
        </span>
        <span class="text-muted small" id="availableInfo"></span>
    </div>

    <div class="card border-0 shadow-sm mb-3">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="av-grid">
                    <thead>
                        <tr>
                            <th style="width:90px">Hari</th>
                            <?php
                            // Kumpulkan semua slot_number unik (urutan fisik)
                            $allSlotNums = [];
                            foreach ($grouped as $slots) {
                                foreach ($slots as $s) $allSlotNums[$s['slot_number']] = $s;
                            }
                            ksort($allSlotNums);
                            ?>
                            <?php foreach ($allSlotNums as $sNum => $sRef): ?>
                            <th title="<?= esc($sRef['label']) ?>">
                                <?= $sRef['slot_type'] === 'kbm' ? $sNum : '<i class="bi bi-dash"></i>' ?>
                                <div style="font-size:9px;font-weight:400;color:#9ca3af">
                                    <?= $sRef['slot_type'] !== 'kbm' ? esc(mb_substr($sRef['label'],0,6)) : esc($sRef['start_time'] ? substr($sRef['start_time'],0,5) : '') ?>
                                </div>
                            </th>
                            <?php endforeach; ?>
                            <th style="width:80px">Blokir Hari</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($dayNames as $day => $dayLabel): ?>
                    <?php
                        $daySlots   = $grouped[$day] ?? [];
                        $slotsByNum = [];
                        foreach ($daySlots as $s) $slotsByNum[$s['slot_number']] = $s;
                        $isWholeDayBlocked = isset($blockedMap[$day][0]);
                        $dayKbm = $kbmPerDay[$day] ?? 0;
                    ?>
                    <tr class="day-row <?= $isWholeDayBlocked ? 'all-blocked' : '' ?>"
                        id="day-row-<?= $day ?>">
                        <td class="day-head">
                            <div class="fw-semibold"><?= $dayLabel ?></div>
                            <div class="day-kbm"><?= $dayKbm ?> KBM</div>
                            <?php if ($day == 1): ?>
                            <div style="font-size:9px;color:#6366F1">Upacara hari ini</div>
                            <?php endif; ?>
                        </td>
                        <?php foreach ($allSlotNums as $sNum => $sRef): ?>
                        <?php
                            $slot    = $slotsByNum[$sNum] ?? null;
                            $isKbm   = $slot && $slot['slot_type'] === 'kbm' && $slot['is_active'];
                            $blocked = isset($blockedMap[$day][$sNum]) || $isWholeDayBlocked;
                            if (!$slot) {
                                // Hari ini tidak punya slot nomor ini
                                echo '<td><span class="slot-cell non-kbm">—</span></td>';
                                continue;
                            }
                            if (!$isKbm) {
                                // Non-KBM: tampilkan ikon tipe
                                $icons = ['istirahat'=>'bi-cup-hot','upacara'=>'bi-flag','keagamaan'=>'bi-moon-stars','lainnya'=>'bi-three-dots'];
                                $icon  = $icons[$slot['slot_type']] ?? 'bi-dot';
                                echo '<td><span class="slot-cell non-kbm" title="'.esc($slot['label']).'"><i class="bi '.$icon.'"></i></span></td>';
                                continue;
                            }
                            $cellClass = $blocked ? 'kbm-blocked' : 'kbm-free';
                            $icon      = $blocked ? 'bi-x-lg' : 'bi-check';
                        ?>
                        <td>
                            <span class="slot-cell <?= $cellClass ?>"
                                  id="cell-<?= $day ?>-<?= $sNum ?>"
                                  data-day="<?= $day ?>"
                                  data-slot="<?= $sNum ?>"
                                  data-blocked="<?= $blocked ? '1' : '0' ?>"
                                  onclick="toggleSlot(this)"
                                  title="<?= $dayLabel ?> - <?= esc($slot['label']) ?> (<?= substr($slot['start_time'],0,5) ?>)">
                                <i class="bi <?= $icon ?>"></i>
                            </span>
                        </td>
                        <?php endforeach; ?>
                        <!-- Tombol blokir seluruh hari -->
                        <td>
                            <button class="block-whole-day-btn <?= $isWholeDayBlocked ? 'active' : '' ?>"
                                    id="wholebtn-<?= $day ?>"
                                    onclick="toggleWholeDay(<?= $day ?>)">
                                <?= $isWholeDayBlocked ? '✓ Diblokir' : 'Blokir' ?>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Aksi -->
    <div class="d-flex gap-2">
        <button class="btn btn-primary" id="btnSaveGrid">
            <i class="bi bi-save me-1"></i>Simpan Ketersediaan
        </button>
        <button class="btn btn-outline-danger" id="btnResetGrid">
            <i class="bi bi-arrow-counterclockwise me-1"></i>Reset Semua
        </button>
        <a href="/schedule-availability" class="btn btn-outline-secondary ms-auto">
            <i class="bi bi-arrow-left me-1"></i>Kembali
        </a>
    </div>

</div><!-- /tab2 -->

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
'use strict';
const TEACHER_ID = <?= (int)$teacher['id'] ?>;
const CSRF       = '<?= csrf_hash() ?>';
const DEFAULT_MAX = <?= (int)$defaultMax ?>;

// ── 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');
    });
});

// ── TAB 1: BATAS JAM ────────────────────────
const maxInput  = document.getElementById('maxHoursInput');
const maxBar    = document.getElementById('maxHoursBar');
const maxDisplay= document.getElementById('maxHoursDisplay');
const feasText  = document.getElementById('feasibilityText');
const feasBox   = document.getElementById('feasibilityInfo');

// Total jam beban guru ini (perlu fetch atau bisa dari PHP)
// Kita hitung dari data yang sudah ada di halaman jika ada
// Untuk sekarang, ambil dari server jika tersedia

maxInput?.addEventListener('input', function() {
    const val = parseInt(this.value) || DEFAULT_MAX;
    const pct = Math.min(100, Math.round(val / 12 * 100));
    maxBar.style.width = pct + '%';
    maxBar.style.background = val > 8 ? '#f59e0b' : val > 10 ? '#dc2626' : '#6366F1';
    maxDisplay.textContent = (this.value ? val : DEFAULT_MAX) + ' jam / hari';
    updateFeasibility(val);
});

function updateFeasibility(maxPerDay) {
    // Hitung hari tersedia (bukan whole-day-blocked)
    let availDays = 0;
    document.querySelectorAll('[id^="wholebtn-"]').forEach(btn => {
        if (!btn.classList.contains('active')) availDays++;
    });
    if (availDays === 0) availDays = 5; // fallback

    const maxPossible = maxPerDay * availDays;
    // Kita tidak tahu total jam dari sini, tapi kita bisa tampilkan estimasi
    feasText.innerHTML = `Dengan maks <strong>${maxPerDay} jam/hari</strong> dan <strong>${availDays} hari tersedia</strong>,
        guru ini bisa mengajar maksimal <strong>${maxPossible} jam/minggu</strong>.`;

    if (maxPerDay <= 2) {
        feasBox.className = 'ibox warn mb-3';
        feasText.innerHTML = '⚠ ' + feasText.innerHTML + ' Batas sangat ketat — mungkin sulit menyelesaikan beban mengajar.';
    } else {
        feasBox.className = 'ibox ok mb-3';
    }
}

// Init feasibility
if (maxInput?.value) updateFeasibility(parseInt(maxInput.value));

// Submit settings
document.getElementById('formSettings')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const btn  = document.getElementById('btnSaveSettings');
    const orig = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Menyimpan...';

    const payload = {
        max_hours_per_day: maxInput.value ? parseInt(maxInput.value) : null,
        notes: document.getElementById('notesInput').value,
    };

    try {
        const res  = await fetch('/schedule-availability/save-settings/' + TEACHER_ID, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': CSRF },
            body: JSON.stringify(payload)
        });
        const data = await res.json();
        btn.disabled = false; btn.innerHTML = orig;
        if (data.success) {
            Swal.fire({ icon:'success', title:'Tersimpan!', text: data.message, timer:1800, showConfirmButton:false })
                .then(() => location.reload());
        } else {
            Swal.fire({ icon:'error', title:'Gagal!', text: data.message });
        }
    } catch(err) {
        btn.disabled = false; btn.innerHTML = orig;
        Swal.fire({ icon:'error', title:'Error!', text: err.message });
    }
});

// Reset ke default
document.getElementById('btnResetDefault')?.addEventListener('click', async function() {
    const result = await Swal.fire({
        title: 'Reset ke Default?',
        text: `Batas jam akan dikembalikan ke default global (${DEFAULT_MAX} jam/hari).`,
        icon: 'question', showCancelButton: true,
        confirmButtonText: 'Ya, Reset', cancelButtonText: 'Batal'
    });
    if (!result.isConfirmed) return;
    maxInput.value = '';
    maxDisplay.textContent = DEFAULT_MAX + ' jam / hari (default)';
    maxBar.style.width = Math.round(DEFAULT_MAX/12*100) + '%';
    document.getElementById('formSettings').dispatchEvent(new Event('submit'));
});

// ── TAB 2: GRID SLOT ────────────────────────

// State: blocked[day][slot] = true/false
// Baca dari DOM
const blocked = {};
document.querySelectorAll('.slot-cell[data-day]').forEach(cell => {
    const d = cell.dataset.day, s = cell.dataset.slot;
    if (!blocked[d]) blocked[d] = {};
    blocked[d][s] = cell.dataset.blocked === '1';
});
// Whole day blocked
const wholeDay = {};
<?php foreach ($dayNames as $d => $label): ?>
wholeDay[<?= $d ?>] = <?= isset($blockedMap[$d][0]) ? 'true' : 'false' ?>;
<?php endforeach; ?>

function toggleSlot(cell) {
    if (cell.classList.contains('non-kbm')) return;
    const d  = cell.dataset.day;
    const s  = cell.dataset.slot;
    const now = cell.dataset.blocked === '1';
    const next = !now;

    cell.dataset.blocked = next ? '1' : '0';
    cell.className = 'slot-cell ' + (next ? 'kbm-blocked' : 'kbm-free');
    cell.innerHTML = `<i class="bi ${next ? 'bi-x-lg' : 'bi-check'}"></i>`;

    if (!blocked[d]) blocked[d] = {};
    blocked[d][s] = next;
    updateBlockedCount();
}

function toggleWholeDay(day) {
    const btn  = document.getElementById('wholebtn-' + day);
    const row  = document.getElementById('day-row-' + day);
    const isBlocked = wholeDay[day];
    wholeDay[day] = !isBlocked;

    if (!isBlocked) {
        // Blokir semua KBM di hari ini
        row.querySelectorAll('.slot-cell:not(.non-kbm)').forEach(cell => {
            cell.dataset.blocked = '1';
            cell.className = 'slot-cell kbm-blocked';
            cell.innerHTML = '<i class="bi bi-x-lg"></i>';
            if (!blocked[day]) blocked[day] = {};
            blocked[day][cell.dataset.slot] = true;
        });
        row.classList.add('all-blocked');
        btn.classList.add('active');
        btn.textContent = '✓ Diblokir';
    } else {
        // Buka semua
        row.querySelectorAll('.slot-cell:not(.non-kbm)').forEach(cell => {
            cell.dataset.blocked = '0';
            cell.className = 'slot-cell kbm-free';
            cell.innerHTML = '<i class="bi bi-check"></i>';
            if (blocked[day]) blocked[day][cell.dataset.slot] = false;
        });
        row.classList.remove('all-blocked');
        btn.classList.remove('active');
        btn.textContent = 'Blokir';
    }
    updateBlockedCount();
}

function updateBlockedCount() {
    let count = 0;
    document.querySelectorAll('.slot-cell[data-day]').forEach(cell => {
        if (cell.dataset.blocked === '1') count++;
    });
    // Tambah whole-day entries
    Object.values(wholeDay).forEach(v => { if (v) count++; }); // slot 0

    document.getElementById('blockedNum').textContent = count;

    // Update stat pill style
    const pill = document.getElementById('blockedCount');
    if (count === 0) {
        pill.className = 'stat-pill pill-ok';
        pill.innerHTML = '<i class="bi bi-check-circle me-1"></i><span id="blockedNum">0</span> slot diblokir';
    } else {
        pill.className = 'stat-pill pill-block';
        pill.innerHTML = `<i class="bi bi-x-circle me-1"></i><span id="blockedNum">${count}</span> slot diblokir`;
    }
}

// Simpan grid
document.getElementById('btnSaveGrid')?.addEventListener('click', async function() {
    const btn  = this;
    const orig = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Menyimpan...';

    // Kumpulkan semua blocked
    const blockedArr = [];

    // Whole-day blocked (slot_number = 0)
    Object.entries(wholeDay).forEach(([day, isBlocked]) => {
        if (isBlocked) blockedArr.push({ day: parseInt(day), slot_number: 0, reason: null });
    });

    // Slot individual
    document.querySelectorAll('.slot-cell[data-day]').forEach(cell => {
        if (cell.dataset.blocked === '1') {
            // Jangan duplikat dengan whole-day
            const d = parseInt(cell.dataset.day);
            if (!wholeDay[d]) {
                blockedArr.push({ day: d, slot_number: parseInt(cell.dataset.slot), reason: null });
            }
        }
    });

    try {
        const res  = await fetch('/schedule-availability/save/' + TEACHER_ID, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': CSRF },
            body: JSON.stringify({ blocked: blockedArr })
        });
        const data = await res.json();
        btn.disabled = false; btn.innerHTML = orig;
        if (data.success) {
            Swal.fire({
                icon:'success', title:'Tersimpan!',
                text: `${data.total} slot berhasil disimpan.`,
                timer: 1800, showConfirmButton: false
            });
        } else {
            Swal.fire({ icon:'error', title:'Gagal!', text: data.message });
        }
    } catch(err) {
        btn.disabled = false; btn.innerHTML = orig;
        Swal.fire({ icon:'error', title:'Error!', text: err.message });
    }
});

// Reset grid
document.getElementById('btnResetGrid')?.addEventListener('click', async function() {
    const result = await Swal.fire({
        title: 'Reset Semua Blokir?',
        text: 'Semua slot yang diblokir akan dibuka kembali.',
        icon: 'warning', showCancelButton: true,
        confirmButtonColor: '#dc3545', confirmButtonText: 'Ya, Reset',
        cancelButtonText: 'Batal'
    });
    if (!result.isConfirmed) return;

    const res  = await fetch('/schedule-availability/reset/' + TEACHER_ID, {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': CSRF },
        body: new FormData()
    });
    const data = await res.json();
    if (data.success) {
        Swal.fire({ icon:'success', title:'Direset!', timer:1500, showConfirmButton:false })
            .then(() => location.reload());
    }
});
</script>
<?= $this->endSection() ?>