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

<!-- TAB HEADER -->
<ul class="nav nav-tabs mb-0" id="teacherTab" role="tablist">
    <li class="nav-item">
        <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-aktif" type="button">
            <i class="bi bi-person-check me-1"></i>Guru Aktif
            <span class="badge bg-primary ms-1"><?= count($teachers) ?></span>
        </button>
    </li>
    <li class="nav-item">
        <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-nonaktif" type="button">
            <i class="bi bi-person-dash me-1"></i>Non-Aktif
            <?php if (count($teachers_inactive) > 0): ?>
            <span class="badge bg-secondary ms-1"><?= count($teachers_inactive) ?></span>
            <?php endif; ?>
        </button>
    </li>
</ul>

<div class="tab-content border border-top-0 rounded-bottom bg-body shadow-sm">

<!-- ════════════════════════════════════════════════════════ -->
<!-- TAB: GURU AKTIF -->
<!-- ════════════════════════════════════════════════════════ -->
<div class="tab-pane fade show active" id="tab-aktif">
<div class="d-flex flex-column" style="min-height:calc(100vh - 260px)">

    <!-- Header -->
    <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 p-3 border-bottom">
        <small class="text-muted">Guru yang aktif bertugas di madrasah</small>
        <div class="d-flex gap-2 flex-wrap">
            <button class="btn btn-warning btn-sm" id="btnBulkAccount" disabled>
                <i class="bi bi-key me-1"></i>Buat Akun Terpilih
            </button>
            <a href="/teacher/import" class="btn btn-success btn-sm">
                <i class="bi bi-file-earmark-excel me-1"></i>Import Excel
            </a>
            <a href="/teacher/export" class="btn btn-outline-success btn-sm">
                <i class="bi bi-download me-1"></i>Export Excel
            </a>
            <a href="/teacher/create" class="btn btn-primary btn-sm">
                <i class="bi bi-plus-circle me-1"></i>Tambah Guru
            </a>
        </div>
    </div>

    <!-- Search & Filter -->
    <div class="px-3 pt-2 pb-2 border-bottom">
        <div class="row g-2 align-items-end">
            <div class="col-sm-4">
                <input type="text" id="searchInput" class="form-control form-control-sm"
                    placeholder="Cari nama / NIP / PEG ID / email / kode..." oninput="applyFilter()">
            </div>
            <div class="col-sm-3">
                <select id="filterStatus" class="form-select form-select-sm" onchange="applyFilter()">
                    <option value="">Semua Status Akun</option>
                    <option value="punya">Sudah Punya Akun</option>
                    <option value="belum">Belum Punya Akun</option>
                </select>
            </div>
            <div class="col-sm-5 d-flex align-items-center justify-content-between gap-2">
                <div>
                    <input type="checkbox" id="checkAll" class="form-check-input me-1" onchange="toggleAll(this)">
                    <label for="checkAll" class="form-check-label small text-muted">Pilih semua (belum punya akun)</label>
                </div>
                <span class="text-muted small" id="infoCount"></span>
            </div>
        </div>
    </div>

    <!-- Tabel Guru Aktif -->
    <div class="flex-grow-1 overflow-auto" style="min-height:0">
        <table class="table table-hover table-sm mb-0">
            <thead class="table-light sticky-top">
                <tr>
                    <th style="width:36px"></th>
                    <th style="width:40px" class="text-center">#</th>
                    <th>Nama Guru</th>
                    <th>NIP / PEG ID</th>
                    <th>Pangkat/Gol</th>
                    <th>Jabatan</th>
                    <th>Status</th>
                    <th>Sertif.</th>
                    <th style="width:70px">Kode</th>
                    <th style="width:50px">JK</th>
                    <th>No. HP</th>
                    <th>Email</th>
                    <th style="width:130px">Status Akun</th>
                    <th style="width:130px">Aksi</th>
                </tr>
            </thead>
            <tbody id="teacherBody">
                <?php if (empty($teachers)): ?>
                <tr>
                    <td colspan="14" class="text-center text-muted py-5">
                        <i class="bi bi-inbox fs-2 d-block mb-2 opacity-25"></i>
                        <small>Belum ada data guru aktif</small>
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($teachers as $i => $t): ?>
                <tr class="teacher-row"
                    data-name="<?= strtolower(esc($t['name'])) ?>"
                    data-nip="<?= strtolower(esc($t['nip'] ?? '')) ?>"
                    data-pegid="<?= strtolower(esc($t['peg_id'] ?? '')) ?>"
                    data-email="<?= strtolower(esc($t['email'] ?? '')) ?>"
                    data-shortcode="<?= strtolower(esc($t['short_code'] ?? '')) ?>"
                    data-has-account="<?= $t['user_id'] ? '1' : '0' ?>">
                    <td class="align-middle">
                        <?php if (!$t['user_id']): ?>
                        <input type="checkbox" class="form-check-input teacher-check"
                            value="<?= $t['id'] ?>" onchange="onCheckChange()">
                        <?php endif; ?>
                    </td>
                    <td class="text-center text-muted small align-middle"><?= $i + 1 ?></td>
                    <td class="align-middle">
                        <div class="fw-semibold small"><?= esc($t['name']) ?></div>
                    </td>
                    <td class="small text-muted align-middle"><?= teacher_id_display($t) ?></td>
                    <td class="small align-middle"><?= esc($t['golongan'] ?? '—') ?></td>
                    <td class="small align-middle"><?= esc($t['jabatan'] ?? '—') ?></td>
                    <td class="small align-middle">
                        <?php if (($t['status_kepegawaian'] ?? '') === 'PNS'): ?>
                            <span class="badge bg-primary" style="font-size:.7rem">PNS</span>
                        <?php elseif (($t['status_kepegawaian'] ?? '') === 'PPPK'): ?>
                            <span class="badge bg-info text-dark" style="font-size:.7rem">PPPK</span>
                        <?php elseif (!empty($t['status_kepegawaian'])): ?>
                            <span class="badge bg-secondary" style="font-size:.7rem"><?= esc($t['status_kepegawaian']) ?></span>
                        <?php else: ?>
                            —
                        <?php endif; ?>
                    </td>
                    <td class="small align-middle">
                        <?php if ($t['is_sertifikasi'] ?? 0): ?>
                            <span class="badge bg-success" style="font-size:.7rem">Sudah</span>
                        <?php else: ?>
                            <span class="badge bg-light text-muted border" style="font-size:.7rem">Belum</span>
                        <?php endif; ?>
                    </td>
                    <td class="small align-middle"><?= esc($t['short_code'] ?? '—') ?></td>
                    <td class="align-middle">
                        <span class="badge" style="font-size:.7rem;background:<?= $t['gender'] == 'L' ? '#0d6efd' : '#e91e8c' ?>">
                            <?= $t['gender'] ?>
                        </span>
                    </td>
                    <td class="small align-middle"><?= esc($t['phone'] ?? '—') ?></td>
                    <td class="small align-middle"><?= esc($t['email'] ?? '—') ?></td>
                    <td class="align-middle">
                        <?php if ($t['user_id']): ?>
                            <?php if ($t['user_active']): ?>
                            <span class="badge bg-success" style="font-size:.7rem">
                                <i class="bi bi-check-circle me-1"></i>Akun Aktif
                            </span>
                            <?php else: ?>
                            <span class="badge bg-warning text-dark" style="font-size:.7rem">
                                <i class="bi bi-pause-circle me-1"></i>Akun Nonaktif
                            </span>
                            <?php endif; ?>
                        <?php else: ?>
                        <span class="badge bg-secondary" style="font-size:.7rem">
                            <i class="bi bi-x-circle me-1"></i>Belum Punya
                        </span>
                        <?php endif; ?>
                    </td>
                    <td class="align-middle">
                        <div class="d-flex gap-1 flex-wrap">
                            <a href="/teacher/edit/<?= $t['id'] ?>"
                                class="btn btn-sm btn-outline-primary py-0 px-2" title="Edit">
                                <i class="bi bi-pencil"></i>
                            </a>
                            <?php if (!$t['user_id']): ?>
                            <button class="btn btn-sm btn-outline-warning py-0 px-2" title="Buat Akun Login"
                                onclick="openCreateAccount(<?= $t['id'] ?>, '<?= esc($t['name'], 'js') ?>', '<?= esc($t['email'] ?? '', 'js') ?>', '<?php $id = teacher_login_identifier($t); echo esc($id ?? '', 'js'); ?>')">
                                <i class="bi bi-key"></i>
                            </button>
                            <?php else: ?>
                            <button class="btn btn-sm btn-outline-info py-0 px-2" title="Reset Password"
                                onclick="resetPassword(<?= $t['id'] ?>, '<?= esc($t['name'], 'js') ?>')">
                                <i class="bi bi-arrow-repeat"></i>
                            </button>
                            <?php endif; ?>
                            <a href="/teacher/delete/<?= $t['id'] ?>"
                                class="btn btn-sm btn-outline-danger py-0 px-2" title="Nonaktifkan (pindah ke Non-Aktif)"
                                onclick="return confirm('Nonaktifkan guru <?= esc($t['name'], 'js') ?>?\nGuru akan dipindah ke tab Non-Aktif.\nAkun login akan dinonaktifkan.')">
                                <i class="bi bi-person-dash"></i>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
</div><!-- end tab-aktif -->

<!-- ════════════════════════════════════════════════════════ -->
<!-- TAB: GURU NON-AKTIF -->
<!-- ════════════════════════════════════════════════════════ -->
<div class="tab-pane fade" id="tab-nonaktif">
<div class="d-flex flex-column" style="min-height:calc(100vh - 260px)">

    <div class="d-flex align-items-center justify-content-between p-3 border-bottom">
        <small class="text-muted">
            <i class="bi bi-info-circle me-1"></i>
            Guru yang sudah dinonaktifkan. Bisa diaktifkan kembali atau dihapus permanen.
        </small>
        <span class="text-muted small" id="infoCountInactive"></span>
    </div>

    <!-- Search Non-Aktif -->
    <div class="px-3 pt-2 pb-2 border-bottom">
        <input type="text" id="searchInactive" class="form-control form-control-sm" style="max-width:300px"
            placeholder="Cari nama / NIP / PEG ID..." oninput="applyFilterInactive()">
    </div>

    <div class="flex-grow-1 overflow-auto" style="min-height:0">
        <table class="table table-hover table-sm mb-0">
            <thead class="table-light sticky-top">
                <tr>
                    <th style="width:40px" class="text-center">#</th>
                    <th>Nama Guru</th>
                    <th>NIP / PEG ID</th>
                    <th>Pangkat/Gol</th>
                    <th>Jabatan</th>
                    <th>Status</th>
                    <th>Sertif.</th>
                    <th style="width:70px">Kode</th>
                    <th style="width:50px">JK</th>
                    <th>Email</th>
                    <th style="width:130px">Status Akun</th>
                    <th style="width:160px">Aksi</th>
                </tr>
            </thead>
            <tbody id="inactiveBody">
                <?php if (empty($teachers_inactive)): ?>
                <tr>
                    <td colspan="12" class="text-center text-muted py-5">
                        <i class="bi bi-check-circle fs-2 d-block mb-2 opacity-25 text-success"></i>
                        <small>Tidak ada guru non-aktif</small>
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($teachers_inactive as $i => $t): ?>
                <tr class="inactive-row"
                    data-name="<?= strtolower(esc($t['name'])) ?>"
                    data-nip="<?= strtolower(esc($t['nip'] ?? '')) ?>"
                    data-pegid="<?= strtolower(esc($t['peg_id'] ?? '')) ?>">
                    <td class="text-center text-muted small align-middle"><?= $i + 1 ?></td>
                    <td class="align-middle">
                        <div class="fw-semibold small text-muted"><?= esc($t['name']) ?></div>
                    </td>
                    <td class="small text-muted align-middle"><?= teacher_id_display($t) ?></td>
                    <td class="small align-middle"><?= esc($t['golongan'] ?? '—') ?></td>
                    <td class="small align-middle"><?= esc($t['jabatan'] ?? '—') ?></td>
                    <td class="small align-middle">
                        <?php if (($t['status_kepegawaian'] ?? '') === 'PNS'): ?>
                            <span class="badge bg-primary" style="font-size:.7rem">PNS</span>
                        <?php elseif (($t['status_kepegawaian'] ?? '') === 'PPPK'): ?>
                            <span class="badge bg-info text-dark" style="font-size:.7rem">PPPK</span>
                        <?php elseif (!empty($t['status_kepegawaian'])): ?>
                            <span class="badge bg-secondary" style="font-size:.7rem"><?= esc($t['status_kepegawaian']) ?></span>
                        <?php else: ?>
                            —
                        <?php endif; ?>
                    </td>
                    <td class="small align-middle">
                        <?php if ($t['is_sertifikasi'] ?? 0): ?>
                            <span class="badge bg-success" style="font-size:.7rem">Sudah</span>
                        <?php else: ?>
                            <span class="badge bg-light text-muted border" style="font-size:.7rem">Belum</span>
                        <?php endif; ?>
                    </td>
                    <td class="small align-middle"><?= esc($t['short_code'] ?? '—') ?></td>
                    <td class="align-middle">
                        <span class="badge bg-secondary" style="font-size:.7rem"><?= $t['gender'] ?></span>
                    </td>
                    <td class="small align-middle text-muted"><?= esc($t['email'] ?? '—') ?></td>
                    <td class="align-middle">
                        <?php if ($t['user_id']): ?>
                        <span class="badge bg-warning text-dark" style="font-size:.7rem">
                            <i class="bi bi-pause-circle me-1"></i>Akun Nonaktif
                        </span>
                        <?php else: ?>
                        <span class="badge bg-light text-muted border" style="font-size:.7rem">
                            Tidak Punya Akun
                        </span>
                        <?php endif; ?>
                    </td>
                    <td class="align-middle">
                        <div class="d-flex gap-1">
                            <a href="/teacher/restore/<?= $t['id'] ?>"
                                class="btn btn-sm btn-outline-success py-0 px-2"
                                title="Aktifkan Kembali"
                                onclick="return confirm('Aktifkan kembali guru <?= esc($t['name'], 'js') ?>?')">
                                <i class="bi bi-person-check me-1"></i>Aktifkan
                            </a>
                            <a href="/teacher/force-delete/<?= $t['id'] ?>"
                                class="btn btn-sm btn-danger py-0 px-2"
                                title="Hapus Permanen"
                                onclick="return confirm('HAPUS PERMANEN data guru <?= esc($t['name'], 'js') ?>?\n\nTindakan ini tidak bisa dibatalkan!\nData akun login juga akan dihapus.')">
                                <i class="bi bi-trash3"></i>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
</div><!-- end tab-nonaktif -->

</div><!-- end tab-content -->

<!-- ════ MODAL: BUAT AKUN PER BARIS ════ -->
<div class="modal fade" id="modalCreateAccount" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title fw-semibold">
                    <i class="bi bi-key me-2 text-warning"></i>Buat Akun Login
                </h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p class="small text-muted mb-3">Guru: <strong id="accountName"></strong></p>
                <div class="mb-3">
                    <label class="form-label small">Username (NIP / PEG ID) <span class="text-danger">*</span></label>
                    <input type="text" id="accountUsername" class="form-control form-control-sm" readonly>
                    <div id="usernameWarning" class="text-danger small mt-1" style="display:none">
                        <i class="bi bi-exclamation-triangle"></i> NIP / PEG ID wajib diisi! Edit data guru dulu.
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label small">Email (Opsional)</label>
                    <input type="email" id="accountEmail" class="form-control form-control-sm" placeholder="email@sekolah.id">
                </div>
                <div class="mb-2">
                    <label class="form-label small">Password</label>
                    <input type="text" id="accountPassword" class="form-control form-control-sm" placeholder="Kosongkan = NIP / guru123">
                    <div class="form-text" id="passwordHint"></div></div>
                     <div class="form-text small text-muted">Password default = username</div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Batal</button>
                <button type="button" class="btn btn-warning btn-sm" id="btnCreateAccountConfirm">
                    <span id="createAccountLabel"><i class="bi bi-key me-1"></i>Buat Akun</span>
                    <span id="createAccountLoading" style="display:none"><span class="spinner-border spinner-border-sm"></span></span>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- ════ MODAL: BUAT AKUN MASSAL ════ -->
<div class="modal fade" id="modalBulkAccount" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title fw-semibold">
                    <i class="bi bi-key me-2 text-warning"></i>Buat Akun Massal
                </h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info py-2 small">
                    <i class="bi bi-info-circle me-1"></i>
                    Password default = <strong>NIP / PEG ID</strong> masing-masing guru.
                </div>
                <p class="small mb-1">Guru yang dipilih: <strong id="bulkCount">0</strong></p>
                <div id="bulkList" class="small text-muted" style="max-height:200px;overflow-y:auto"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Batal</button>
                <button type="button" class="btn btn-warning btn-sm" id="btnBulkConfirm">
                    <span id="bulkLabel"><i class="bi bi-check-circle me-1"></i>Buat Semua Akun</span>
                    <span id="bulkLoading" style="display:none"><span class="spinner-border spinner-border-sm"></span></span>
                </button>
            </div>
        </div>
    </div>
</div>

<style>
.overflow-auto thead.sticky-top th { top:0; z-index:2; background:#f8f9fa; }
[data-bs-theme="dark"] .overflow-auto thead.sticky-top th { background:#2a3447; }
.nav-tabs .nav-link { font-size:.875rem; }
</style>

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
let currentTeacherId = null;
let currentNip = null;

// ── FILTER TAB AKTIF ─────────────────────────────────────────
function applyFilter() {
    const q      = document.getElementById('searchInput').value.toLowerCase();
    const status = document.getElementById('filterStatus').value;
    const rows   = document.querySelectorAll('.teacher-row');
    let visible  = 0;

    rows.forEach(row => {
        const matchQ = !q ||
            row.dataset.name.includes(q) ||
            row.dataset.nip.includes(q) ||
            row.dataset.pegid && row.dataset.pegid.includes(q) ||
            row.dataset.email.includes(q) ||
            (row.dataset.shortcode && row.dataset.shortcode.includes(q));
        const hasAcc = row.dataset.hasAccount === '1';
        const matchS = !status ||
            (status === 'punya' && hasAcc) ||
            (status === 'belum' && !hasAcc);
        if (matchQ && matchS) { row.style.display = ''; visible++; }
        else                  { row.style.display = 'none'; }
    });

    document.getElementById('infoCount').textContent = `${visible} guru`;
}

// ── FILTER TAB NON-AKTIF ──────────────────────────────────────
function applyFilterInactive() {
    const q    = document.getElementById('searchInactive').value.toLowerCase();
    const rows = document.querySelectorAll('.inactive-row');
    let vis    = 0;
    rows.forEach(row => {
        const match = !q || row.dataset.name.includes(q) || row.dataset.nip.includes(q) || (row.dataset.pegid && row.dataset.pegid.includes(q));
        row.style.display = match ? '' : 'none';
        if (match) vis++;
    });
    document.getElementById('infoCountInactive').textContent = `${vis} guru`;
}

// ── CHECKBOX ─────────────────────────────────────────────────
function toggleAll(cb) {
    document.querySelectorAll('.teacher-check').forEach(c => {
        const row = c.closest('tr');
        if (row.style.display !== 'none') c.checked = cb.checked;
    });
    onCheckChange();
}

function onCheckChange() {
    const checked = document.querySelectorAll('.teacher-check:checked');
    document.getElementById('btnBulkAccount').disabled = checked.length === 0;
}

// ── BUAT AKUN PER BARIS ──────────────────────────────────────
function openCreateAccount(id, name, email, username) {
    currentTeacherId = id;
    currentNip = username;
    document.getElementById('accountName').textContent     = name;
    document.getElementById('accountUsername').value       = username || '(NIP/PEG ID kosong)';
    document.getElementById('accountEmail').value          = email;
    document.getElementById('accountPassword').value       = '';
    document.getElementById('passwordHint').textContent    = username ? 'Default: username (' + username + ')' : 'Default: guru123';
    document.getElementById('usernameWarning').style.display = username ? 'none' : 'block';
    new bootstrap.Modal(document.getElementById('modalCreateAccount')).show();
}

document.getElementById('btnCreateAccountConfirm').addEventListener('click', function() {
    if (!currentTeacherId || !currentNip) {
        showToast('NIP wajib diisi untuk membuat akun!', 'danger');
        bootstrap.Modal.getInstance(document.getElementById('modalCreateAccount')).hide();
        return;
    }
    document.getElementById('createAccountLabel').style.display = 'none';
    document.getElementById('createAccountLoading').style.display = '';
    this.disabled = true;

    const fd = new FormData();
    fd.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');
    fd.append('email',    document.getElementById('accountEmail').value);
    fd.append('password', document.getElementById('accountPassword').value);

    fetch(`/teacher/create-account/${currentTeacherId}`, {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: fd
    })
    .then(r => r.json())
    .then(data => {
        bootstrap.Modal.getInstance(document.getElementById('modalCreateAccount')).hide();
        showToast(data.message, data.success ? 'success' : 'danger');
        if (data.success) setTimeout(() => location.reload(), 1500);
        document.getElementById('createAccountLabel').style.display = '';
        document.getElementById('createAccountLoading').style.display = 'none';
        document.getElementById('btnCreateAccountConfirm').disabled = false;
    });
});

// ── BUAT AKUN MASSAL ─────────────────────────────────────────
document.getElementById('btnBulkAccount').addEventListener('click', function() {
    const checks = document.querySelectorAll('.teacher-check:checked');
    const names  = [];
    checks.forEach(c => {
        const row = c.closest('tr');
        names.push(row.querySelector('td:nth-child(3) .fw-semibold').textContent.trim());
    });
    document.getElementById('bulkCount').textContent = checks.length;
    document.getElementById('bulkList').innerHTML = names.map(n => `<div>• ${n}</div>`).join('');
    new bootstrap.Modal(document.getElementById('modalBulkAccount')).show();
});

document.getElementById('btnBulkConfirm').addEventListener('click', function() {
    const ids = [...document.querySelectorAll('.teacher-check:checked')].map(c => c.value);
    document.getElementById('bulkLabel').style.display  = 'none';
    document.getElementById('bulkLoading').style.display = '';
    this.disabled = true;

    const fd = new FormData();
    fd.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');
    ids.forEach(id => fd.append('teacher_ids[]', id));

    fetch('/teacher/create-account-bulk', {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: fd
    })
    .then(r => r.json())
    .then(data => {
        bootstrap.Modal.getInstance(document.getElementById('modalBulkAccount')).hide();
        showToast(data.message, data.success ? 'success' : 'danger');
        if (data.success) setTimeout(() => location.reload(), 1500);
        document.getElementById('bulkLabel').style.display   = '';
        document.getElementById('bulkLoading').style.display  = 'none';
        document.getElementById('btnBulkConfirm').disabled    = false;
    });
});

// ── RESET PASSWORD ───────────────────────────────────────────
function resetPassword(id, name) {
    if (!confirm(`Reset password ${name} ke NIP / guru123?`)) return;
    const fd = new FormData();
    fd.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');
    fetch(`/teacher/reset-password/${id}`, {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: fd
    })
    .then(r => r.json())
    .then(data => showToast(data.message, data.success ? 'success' : 'danger'));
}

// ── TOAST HELPER ─────────────────────────────────────────────
function showToast(msg, type = 'success') {
    const w = document.createElement('div');
    w.className = 'position-fixed bottom-0 end-0 p-3';
    w.style.zIndex = '9999';
    w.innerHTML = `
        <div class="toast align-items-center text-white bg-${type} border-0 show">
            <div class="d-flex">
                <div class="toast-body fw-semibold small">${msg}</div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" onclick="this.closest('.position-fixed').remove()"></button>
            </div>
        </div>`;
    document.body.appendChild(w);
    setTimeout(() => w.remove(), 4500);
}

// ── INIT ─────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('infoCount').textContent =
        `${document.querySelectorAll('.teacher-row').length} guru`;
    document.getElementById('infoCountInactive').textContent =
        `${document.querySelectorAll('.inactive-row').length} guru`;

    // Simpan tab aktif di localStorage
    const saved = localStorage.getItem('teacherTab');
    if (saved) {
        const el = document.querySelector(`#teacherTab button[data-bs-target="${saved}"]`);
        if (el) bootstrap.Tab.getOrCreateInstance(el).show();
    }
    document.querySelectorAll('#teacherTab button').forEach(el => {
        el.addEventListener('shown.bs.tab', () => {
            localStorage.setItem('teacherTab', el.dataset.bsTarget);
        });
    });
});
</script>
<?= $this->endSection() ?>
