

<?php $__env->startSection('content'); ?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

<style>
    .gw {
        --primary: #4f46e5;
        --border:  #e2e8f0;
        --soft:    #f8fafc;
        --muted:   #64748b;
    }

    .gw .btn-h {
        display: inline-flex; align-items: center; gap: 7px;
        padding: 9px 18px; border-radius: 10px;
        font-size: 13px; font-weight: 700;
        cursor: pointer; transition: all 0.15s;
        text-decoration: none; white-space: nowrap; border: none;
    }
    .gw .btn-outline          { background: #fff; color: #1e293b; border: 1px solid var(--border); }
    .gw .btn-outline:hover    { background: var(--soft); }
    .gw .btn-primary-h        { background: var(--primary); color: #fff; }
    .gw .btn-primary-h:hover  { background: #4338ca; }
    .gw .btn-success-h        { background: #16a34a; color: #fff; }
    .gw .btn-success-h:hover  { background: #15803d; }
    .gw .btn-danger-h         { background: #fff; color: #dc2626; border: 1px solid #fca5a5; }
    .gw .btn-danger-h:hover   { background: #fef2f2; }

    .gw .main-card { border: 1px solid var(--border); border-radius: 16px; background: #fff; overflow: hidden; }

    .gw table { width: 100%; border-collapse: collapse; }
    .gw thead th {
        background: var(--soft); font-size: 11px; font-weight: 700;
        text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted);
        padding: 12px 20px; border-bottom: 1px solid var(--border); white-space: nowrap;
    }
    .gw tbody td {
        padding: 14px 20px; border-bottom: 1px solid #f8fafc;
        vertical-align: middle; font-size: 13px; color: #1e293b;
    }
    .gw tbody tr:last-child td { border-bottom: none; }
    .gw tbody tr:hover td { background: #fafbff; }

    /* Avatar gelar */
    .gw .avatar {
        width: 40px; height: 40px; border-radius: 10px;
        background: #eef2ff; color: #4f46e5;
        display: flex; align-items: center; justify-content: center;
        font-size: 11px; font-weight: 700; flex-shrink: 0;
        text-align: center; line-height: 1.2;
    }

    .gw .badge-id {
        font-family: 'Courier New', monospace; font-size: 10px; font-weight: 700;
        background: var(--soft); color: var(--muted); border: 1px solid var(--border);
        padding: 2px 7px; border-radius: 5px; display: inline-block; margin-right: 4px;
    }
    .gw .badge-male   { background: #e0f2fe; color: #0369a1; border: 1px solid #bae6fd; }
    .gw .badge-female { background: #fce7f3; color: #be185d; border: 1px solid #fbcfe8; }
    .gw .badge-gender {
        display: inline-flex; align-items: center; gap: 5px;
        font-size: 11px; font-weight: 700; padding: 4px 10px; border-radius: 20px;
    }

    /* Layout nama guru dalam tabel */
    .guru-nama-line {
        display: flex; align-items: center; flex-wrap: wrap; gap: 4px;
        margin-bottom: 3px;
    }
    .guru-nama {
        font-weight: 700; font-size: 13px; color: #0f172a;
        white-space: nowrap;
    }
    .guru-gelar-line {
        display: flex; flex-wrap: wrap; gap: 3px;
        margin-bottom: 4px;
    }
    .guru-nip-line {
        display: flex; align-items: center; gap: 4px;
        margin-top: 2px;
    }

    /* Badge gelar depan & belakang */
    .gw .badge-gelar {
        display: inline-block;
        font-size: 10px; font-weight: 700;
        padding: 2px 7px; border-radius: 5px;
        margin: 1px 2px 1px 0;
        white-space: nowrap;
    }
    .gw .badge-gelar.depan {
        background: #fffbeb; color: #92400e; border: 1px solid #fde68a;
    }
    .gw .badge-gelar.belakang {
        background: #f0f9ff; color: #0369a1; border: 1px solid #bae6fd;
    }

    .gw .btn-act {
        display: inline-flex; align-items: center; justify-content: center;
        width: 34px; height: 34px; border-radius: 8px;
        border: 1px solid var(--border); background: #fff;
        font-size: 14px; cursor: pointer; transition: all 0.15s;
        color: var(--muted); text-decoration: none;
    }
    .gw .btn-act:hover     { background: #eef2ff; color: var(--primary); border-color: #c7d2fe; }
    .gw .btn-act.del:hover { background: #fef2f2; color: #ef4444; border-color: #fecaca; }

    .gw .empty-state { padding: 56px 20px; text-align: center; }
    .gw .empty-state i { font-size: 36px; color: #cbd5e1; display: block; margin-bottom: 10px; }
    .gw .empty-state p { font-size: 13px; color: var(--muted); margin: 0; }
    .gw .empty-state a { color: var(--primary); font-weight: 600; text-decoration: none; }
    .gw .empty-state a:hover { text-decoration: underline; }

    /* Search bar */
    .gw .search-box { position: relative; flex: 1; max-width: 420px; }
    .gw .search-box input {
        width: 100%; padding: 10px 36px 10px 36px;
        border: 1px solid var(--border); border-radius: 10px;
        font-size: 13px; color: #1e293b; background: #fff;
        transition: border-color 0.15s, box-shadow 0.15s; font-family: inherit;
    }
    .gw .search-box input:focus {
        outline: none; border-color: var(--primary);
        box-shadow: 0 0 0 3px rgba(79,70,229,0.1);
    }
    .gw .search-box .search-icon {
        position: absolute; left: 13px; top: 50%; transform: translateY(-50%);
        color: #94a3b8; font-size: 13px; pointer-events: none;
    }
    .gw .search-box .clear-btn {
        position: absolute; right: 10px; top: 50%; transform: translateY(-50%);
        color: #94a3b8; font-size: 14px; text-decoration: none; cursor: pointer;
        display: flex; align-items: center;
    }
    .gw .search-box .clear-btn:hover { color: #475569; }
    .gw .search-result-hint {
        font-size: 12px; color: var(--muted); margin-top: 6px;
    }
    .gw .search-result-hint a { color: var(--primary); font-weight: 600; text-decoration: none; }
    .gw .search-result-hint a:hover { text-decoration: underline; }

    /* Import Preview */
    #import-preview {
        max-height: 280px; overflow-y: auto;
        border: 1px solid var(--border); border-radius: 10px;
        margin-top: 12px; display: none;
    }
    #import-preview table { width: 100%; border-collapse: collapse; font-size: 12px; }
    #import-preview thead th {
        background: #f8fafc; color: var(--muted); font-size: 10px; font-weight: 700;
        text-transform: uppercase; letter-spacing: 0.05em;
        padding: 8px 12px; border-bottom: 1px solid var(--border); position: sticky; top: 0;
    }
    #import-preview tbody td { padding: 8px 12px; border-bottom: 1px solid #f8fafc; color: #1e293b; }
    #import-preview tbody tr:last-child td { border-bottom: none; }

    .import-info-box {
        background: #f0f9ff; border: 1px solid #bae6fd;
        border-radius: 10px; padding: 12px 14px;
        font-size: 12px; color: #0369a1; margin-bottom: 14px;
        display: flex; align-items: flex-start; gap: 8px;
    }
    .import-info-box i { flex-shrink: 0; font-size: 15px; margin-top: 1px; }
    .import-cols-wrap { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
    .col-pill          { background: #fff; border: 1px solid #bae6fd; border-radius: 6px; padding: 2px 9px; font-size: 11px; font-weight: 700; color: #0369a1; font-family: 'Courier New', monospace; }
    .col-pill.required { background: #eef2ff; border-color: #c7d2fe; color: #4338ca; }
    .col-pill.optional { background: #f0fdf4; border-color: #bbf7d0; color: #15803d; }

    .import-stat { display: flex; gap: 10px; margin-top: 10px; }
    .import-stat .is-box { flex: 1; text-align: center; background: #f8fafc; border: 1px solid var(--border); border-radius: 8px; padding: 8px 4px; }
    .import-stat .is-val { font-size: 20px; font-weight: 700; color: #0f172a; }
    .import-stat .is-lbl { font-size: 10px; color: var(--muted); }
    .import-stat .is-box.ok  .is-val { color: #16a34a; }
    .import-stat .is-box.err .is-val { color: #dc2626; }

    #col-map-wrap { margin-top: 14px; display: none; }
    #col-map-wrap label {
        font-size: 11px; font-weight: 700; text-transform: uppercase;
        letter-spacing: 0.06em; color: var(--muted); margin-bottom: 4px; display: block;
    }
    .col-map-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }

    .pwd-info {
        background: #fffbeb; border: 1px solid #fde68a;
        border-radius: 8px; padding: 10px 12px;
        font-size: 11px; color: #92400e; margin-top: 10px;
        display: flex; align-items: flex-start; gap: 7px;
    }

    /* Modal */
    .gm .modal-content { border: none; border-radius: 20px; box-shadow: 0 20px 40px rgba(0,0,0,0.15); }
    .gm .modal-header  { padding: 22px 24px 0; border: none; }
    .gm .modal-body    { padding: 18px 24px 24px; }
    .gm .modal-title   { font-size: 16px; font-weight: 700; color: #0f172a; }
    .gm label {
        font-size: 11px; font-weight: 700; text-transform: uppercase;
        letter-spacing: 0.06em; color: var(--muted); margin-bottom: 6px; display: block;
    }
    .gm .form-ctrl {
        width: 100%; padding: 9px 14px; border: 1px solid var(--border); border-radius: 10px;
        font-size: 13px; color: #1e293b; background: #fff;
        transition: border-color 0.15s, box-shadow 0.15s; margin-bottom: 14px; font-family: inherit;
    }
    .gm .form-ctrl:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(79,70,229,0.1); }
    .gm .icon-wrap {
        width: 38px; height: 38px; border-radius: 10px; background: #eef2ff; color: var(--primary);
        display: flex; align-items: center; justify-content: center; font-size: 16px; flex-shrink: 0;
    }
    .gm .icon-wrap.green { background: #f0fdf4; color: #16a34a; }
    .gm .btn-submit {
        width: 100%; padding: 11px; border-radius: 10px; font-size: 13px; font-weight: 700;
        background: var(--primary); color: #fff; border: none; cursor: pointer;
        transition: background 0.15s; margin-top: 4px; font-family: inherit;
    }
    .gm .btn-submit:hover       { background: #4338ca; }
    .gm .btn-submit.green       { background: #16a34a; }
    .gm .btn-submit.green:hover { background: #15803d; }
    .gm .btn-cancel {
        flex: 1; padding: 10px; border-radius: 10px; font-size: 13px; font-weight: 600;
        background: var(--soft); color: var(--muted); border: 1px solid var(--border);
        cursor: pointer; transition: all 0.15s; font-family: inherit;
    }
    .gm .btn-cancel:hover { background: #f1f5f9; }
    .gm .row-2 { display: grid; grid-template-columns: 1fr 1.5fr; gap: 12px; }
    .gm .row-2 .form-ctrl { margin-bottom: 0; }

    .drop-zone {
        border: 2px dashed #c7d2fe; border-radius: 12px; padding: 28px 20px;
        text-align: center; cursor: pointer; transition: all 0.2s; background: #fafbff;
    }
    .drop-zone:hover, .drop-zone.dragover { border-color: var(--primary); background: #eef2ff; }
    .drop-zone i { font-size: 28px; color: #a5b4fc; display: block; margin-bottom: 8px; }
    .drop-zone p { font-size: 13px; color: var(--muted); margin: 0; }
    .drop-zone .dz-hint { font-size: 11px; color: #94a3b8; margin-top: 4px; }
    .drop-zone input[type=file] { display: none; }
    #file-chosen { font-size: 12px; color: #16a34a; font-weight: 700; margin-top: 8px; display: none; }

    .akun-info {
        background: #f0fdf4; border: 1px solid #bbf7d0;
        border-radius: 10px; padding: 12px 14px; margin-top: 12px;
        font-size: 12px; color: #15803d;
    }
    .akun-info code { background: #fff; padding: 1px 6px; border-radius: 4px; border: 1px solid #bbf7d0; font-size: 12px; }

    /* Pagination */
    .gw-pagination {
        display: flex; align-items: center; justify-content: space-between;
        padding: 14px 20px; border-top: 1px solid var(--border);
        background: #fff; flex-wrap: wrap; gap: 8px;
    }
    .gw-pagination .pg-info {
        font-size: 12px; color: var(--muted);
    }
    .gw-pagination .pg-btns {
        display: flex; gap: 4px; align-items: center;
    }
    .gw-pagination .pg-btn {
        display: inline-flex; align-items: center; justify-content: center;
        width: 32px; height: 32px; border-radius: 8px;
        border: 1px solid var(--border); background: #fff;
        font-size: 12px; font-weight: 700; cursor: pointer;
        color: var(--muted); transition: all 0.15s;
    }
    .gw-pagination .pg-btn:hover:not(:disabled) { background: #eef2ff; color: var(--primary); border-color: #c7d2fe; }
    .gw-pagination .pg-btn.active { background: var(--primary); color: #fff; border-color: var(--primary); }
    .gw-pagination .pg-btn:disabled { opacity: 0.35; cursor: not-allowed; }
    .gw-pagination select.pg-rows {
        border: 1px solid var(--border); border-radius: 8px;
        padding: 5px 8px; font-size: 12px; color: #1e293b;
        background: #fff; cursor: pointer;
    }

    /* ── HEADER ACTIONS — mobile ── */
    @media (max-width: 640px) {
        .gw .header-row { flex-direction: column; align-items: flex-start !important; }
        .gw .header-actions {
            display: grid;
            grid-template-columns: 1fr 1fr;
            width: 100%;
            gap: 8px;
        }
        .gw .btn-h { justify-content: center; width: 100%; padding: 10px 12px; font-size: 12px; }
        .gw .search-box { max-width: 100%; width: 100%; }
    }

    /* ── TABLE card stack — mobile (PERBAIKAN) ── */
    @media (max-width: 768px) {
        .gw thead { display: none; }
        .gw tbody tr {
            display: block;
            border: 1px solid var(--border);
            border-radius: 14px;
            margin: 10px 12px;
            background: #fff;
            box-shadow: 0 1px 4px rgba(0,0,0,.04);
            overflow: hidden;
        }
        .gw tbody tr:hover td { background: #fff; }
        .gw tbody td {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 11px 14px;
            border: none;
            border-bottom: 1px solid #f1f5f9;
            font-size: 13px;
            gap: 10px;
        }
        .gw tbody td:last-child { border-bottom: none; }
        .gw tbody td::before {
            content: attr(data-label);
            font-size: 11px; font-weight: 700; color: var(--muted);
            text-transform: uppercase; letter-spacing: .04em;
            flex-shrink: 0; min-width: 72px;
        }
        
        /* Reset layout flex agar baris profil guru bertumpuk rapi di HP */
        .gw tbody td[data-label="Nama"] {
            flex-direction: column;
            align-items: flex-start;
            gap: 6px;
        }
        .gw tbody td[data-label="Nama"] .d-flex {
            flex-direction: column !important;
            align-items: flex-start !important;
            gap: 8px !important;
            width: 100%;
        }
        
        /* Nama dan Gelar: diizinkan bungkus baris baru */
        .guru-nama { white-space: normal; word-break: break-word; }
        .gw .badge-gelar { white-space: normal; }
        
        /* Email panjang: break text agar tidak offscreen */
        .gw tbody td[data-label="Akun"] {
            flex-direction: column;
            align-items: flex-start;
        }
        .gw tbody td[data-label="Akun"] div {
            width: 100%;
            word-break: break-all;
        }
        .gw tbody td[data-label="Akun"] span { word-break: break-all; font-size: 12px; }
        
        /* Aksi dan Gender disesuaikan posisinya */
        .gw tbody td[data-label="Gender"] {
            justify-content: space-between;
        }
        .gw tbody td[data-label="Aksi"] { justify-content: flex-end; }
        .gw tbody td[data-label="Aksi"]::before { display: none; }
    }

    /* ── PAGINATION — mobile ── */
    @media (max-width: 640px) {
        .gw-pagination { flex-direction: column; align-items: flex-start; gap: 10px; }
        .gw-pagination .pg-btns { flex-wrap: wrap; }
    }

    /* ── MODAL row-2 — HP kecil ── */
    @media (max-width: 480px) {
        .gm .row-2 { grid-template-columns: 1fr; }
        .gm .row-2 .form-ctrl { margin-bottom: 14px; }
    }

    /* ── Import col-map — mobile ── */
    @media (max-width: 600px) {
        .col-map-grid { grid-template-columns: 1fr; }
    }
</style>

<?php
function parseNamaGuru(string $namaLengkap): array
{
    $GELAR_DEPAN = [
        'Prof.', 'Prof', 'Dr.', 'DR.', 'Dr', 'DR', 'dr.', 'dr',
        'Drs.', 'Drs', 'Dra.', 'Dra',
        'Ir.', 'Ir',
        'H.', 'H', 'Hj.', 'Hj',
        'KH.', 'KH',
        'Lc.', 'Lc',
        'Ust.', 'Ust', 'Ustadz', 'Ustadzah',
        'M.', 'Drs.H.',
    ];

    usort($GELAR_DEPAN, fn($a, $b) => strlen($b) - strlen($a));

    $depan   = [];
    $sisa    = trim($namaLengkap);

    foreach ($GELAR_DEPAN as $g) {
        $pattern = '/^' . preg_quote($g, '/') . '\s+/i';
        if (preg_match($pattern, $sisa)) {
            $depan[] = rtrim($g, '.') . '.';
            $sisa    = preg_replace($pattern, '', $sisa, 1);
            reset($GELAR_DEPAN);
        }
    }

    $parts       = explode(',', $sisa, 2);
    $namaBersih  = trim($parts[0]);
    $belakang    = [];

    if (isset($parts[1])) {
        foreach (explode(',', $parts[1]) as $bg) {
            $bg = trim($bg);
            if ($bg !== '') $belakang[] = $bg;
        }
    }

    $kata     = array_filter(explode(' ', $namaBersih));
    $inisial  = implode('', array_map(
        fn($k) => strtoupper(mb_substr($k, 0, 1)),
        array_slice($kata, 0, 2)
    ));

    $jumlahGelar = count($depan) + count($belakang);
    return compact('depan', 'namaBersih', 'belakang', 'inisial', 'jumlahGelar');
}

$gurusSorted = $gurus->sortByDesc(function($g) {
    $p = parseNamaGuru($g->nama);
    return count($p['depan']) + count($p['belakang']);
})->values();
?>

<div class="gw container-fluid px-3 px-md-4 pb-5 pt-4">

    
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-3 header-row">
        <div>
            <h3 style="font-size:20px;font-weight:700;color:#0f172a;margin-bottom:4px;">Manajemen Guru</h3>
            <p style="font-size:13px;color:#64748b;margin:0;">
                <i class="bi bi-people me-1"></i> <?php echo e($gurus->count()); ?> tenaga pengajar
                <?php if(!empty($search)): ?>
                    ditemukan untuk "<strong><?php echo e($search); ?></strong>"
                <?php else: ?>
                    terdaftar
                <?php endif; ?>
            </p>
        </div>
        <div class="d-flex gap-2 flex-wrap header-actions">
            <a href="<?php echo e(route('admin.guru.cetak')); ?>" class="btn-h btn-outline">
                <i class="bi bi-printer"></i> Cetak Semua QR
            </a>
            <button class="btn-h btn-success-h" data-bs-toggle="modal" data-bs-target="#modalImportGuru">
                <i class="bi bi-file-earmark-arrow-up"></i> Import Excel
            </button>
            <button class="btn-h btn-primary-h" data-bs-toggle="modal" data-bs-target="#modalTambahGuru">
                <i class="bi bi-person-plus"></i> Tambah Guru
            </button>
        </div>
    </div>

    
    <div class="mb-3">
        <form method="GET" action="<?php echo e(route('admin.guru.index')); ?>" class="search-box" id="formSearchGuru">
            <i class="bi bi-search search-icon"></i>
            <input type="text" name="search" id="inputSearchGuru" value="<?php echo e($search ?? ''); ?>"
                   placeholder="Cari nama, NIP/NUPTK/NIK, username, atau email guru...">
            <?php if(!empty($search)): ?>
                <a href="<?php echo e(route('admin.guru.index')); ?>" class="clear-btn" title="Hapus pencarian">
                    <i class="bi bi-x-circle-fill"></i>
                </a>
            <?php endif; ?>
        </form>
    </div>

    
    <div class="main-card shadow-sm">
        <div style="overflow-x:auto;">
            <table>
                <thead>
                    <tr>
                        <th style="padding-left:24px;">Profil Guru</th>
                        <th class="text-center">Jenis Kelamin</th>
                        <th>Kredensial Akun</th>
                        <th class="text-end" style="padding-right:24px;">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $__empty_1 = true; $__currentLoopData = $gurusSorted; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $idx => $g): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                    <?php $parsed = parseNamaGuru($g->nama); ?>
                    <tr class="guru-row" data-idx="<?php echo e($idx); ?>">
                        <td data-label="Nama" style="padding-left:24px;">
                            <div class="d-flex align-items-center gap-3">

                                
                                <div class="avatar"><?php echo e($parsed['inisial']); ?></div>

                                <div class="w-100">
                                    
                                    <div class="guru-nama-line">
                                        <?php $__currentLoopData = $parsed['depan']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $gd): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <span class="badge-gelar depan"><?php echo e($gd); ?></span>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        <span class="guru-nama"><?php echo e($parsed['namaBersih']); ?></span>
                                    </div>

                                    
                                    <?php if($parsed['belakang']): ?>
                                        <div class="guru-gelar-line">
                                            <?php $__currentLoopData = $parsed['belakang']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $gb): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <span class="badge-gelar belakang"><?php echo e($gb); ?></span>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        </div>
                                    <?php endif; ?>

                                    
                                    <div class="guru-nip-line">
                                        <span class="badge-id"><?php echo e($g->jenis_identitas); ?></span>
                                        <span style="font-family:'Courier New',monospace;font-size:11px;color:#64748b;"><?php echo e($g->nomor_identitas); ?></span>
                                    </div>
                                </div>
                            </div>
                        </td>

                        <td data-label="Gender" class="text-center">
                            <span class="badge-gender <?php echo e($g->jenis_kelamin == 'L' ? 'badge-male' : 'badge-female'); ?>">
                                <i class="bi <?php echo e($g->jenis_kelamin == 'L' ? 'bi-gender-male' : 'bi-gender-female'); ?>"></i>
                                <?php echo e($g->jenis_kelamin == 'L' ? 'Laki-laki' : 'Perempuan'); ?>

                            </span>
                        </td>

                        <td data-label="Akun">
                            <div style="margin-bottom:4px;">
                                <i class="bi bi-envelope" style="color:#94a3b8;font-size:12px;margin-right:5px;"></i>
                                <span style="font-size:13px;"><?php echo e($g->user->email ?? '—'); ?></span>
                            </div>
                            <div>
                                <i class="bi bi-person-badge" style="color:#94a3b8;font-size:12px;margin-right:5px;"></i>
                                <span style="font-size:11px;color:#64748b;"><?php echo e($g->user->username ?? '—'); ?></span>
                            </div>
                        </td>

                        <td data-label="Aksi" class="text-end" style="padding-right:24px;">
                            <div class="d-flex justify-content-end gap-2">
                                <a href="<?php echo e(route('admin.guru.cetak', ['id' => $g->id])); ?>" class="btn-act" title="Cetak QR">
                                    <i class="bi bi-printer"></i>
                                </a>
                                <button class="btn-act" data-bs-toggle="modal" data-bs-target="#edit<?php echo e($g->id); ?>" title="Edit">
                                    <i class="bi bi-pencil-square"></i>
                                </button>
                                <form id="del-<?php echo e($g->id); ?>" action="<?php echo e(route('admin.guru.destroy', $g->id)); ?>" method="POST" class="d-inline">
                                    <?php echo csrf_field(); ?> <?php echo method_field('DELETE'); ?>
                                    <button type="button" class="btn-act del"
                                            onclick="confirmDelete('<?php echo e($g->id); ?>', '<?php echo e(addslashes($g->nama)); ?>')"
                                            title="Hapus">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                    <tr>
                        <td colspan="4">
                            <div class="empty-state">
                                <i class="bi bi-inbox"></i>
                                <?php if(!empty($search)): ?>
                                    <p style="font-weight:600;margin-bottom:4px;">Tidak ditemukan guru untuk "<?php echo e($search); ?>".</p>
                                    <p>Coba kata kunci lain atau <a href="<?php echo e(route('admin.guru.index')); ?>">tampilkan semua data</a>.</p>
                                <?php else: ?>
                                    <p style="font-weight:600;margin-bottom:4px;">Belum ada data guru.</p>
                                    <p>Tambahkan guru baru atau import dari file Excel.</p>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        
        <div class="gw-pagination" id="paginationBar">
            <div class="pg-info" id="pgInfo">Memuat...</div>
            <div class="d-flex align-items-center gap-3 flex-wrap">
                <div class="d-flex align-items-center gap-2">
                    <span style="font-size:12px;color:var(--muted);">Baris per halaman:</span>
                    <select class="pg-rows" id="pgRows" onchange="changePgRows()">
                        <option value="10" selected>10</option>
                        <option value="20">20</option>
                        <option value="50">50</option>
                    </select>
                </div>
                <div class="pg-btns" id="pgBtns"></div>
            </div>
        </div>

    </div>
</div>


<div class="modal fade gm" id="modalImportGuru" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered modal-lg modal-fullscreen-sm-down">
        <div class="modal-content">
            <div class="modal-header">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon-wrap green"><i class="bi bi-file-earmark-arrow-up"></i></div>
                    <div>
                        <h5 class="modal-title">Import Data Guru dari Excel</h5>
                        <p style="font-size:11px;color:#64748b;margin:2px 0 0;">Petakan kolom Excel ke field sistem — format bebas</p>
                    </div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" onclick="resetImport()"></button>
            </div>
            <div class="modal-body">

                <div class="import-info-box">
                    <i class="bi bi-info-circle-fill"></i>
                    <div>
                        <div style="font-weight:700;margin-bottom:6px;">
                            Kolom <span style="color:#dc2626;">wajib</span> &amp;
                            <span style="color:#15803d;">opsional</span>:
                        </div>
                        <div class="import-cols-wrap">
                            <span class="col-pill required">Nama Guru</span>
                            <span class="col-pill required">NIP / NUPTK / NRG / NPK / NIK / PegID</span>
                            <span class="col-pill required">Jenis Kelamin</span>
                            <span class="col-pill optional">Email (opsional)</span>
                        </div>
                        <div style="margin-top:8px;font-size:11px;color:#64748b;">
                            Jika email tidak ada, akan digenerate otomatis: <code style="background:#fff;padding:1px 5px;border-radius:4px;">namaguru@gmail.com</code>.
                            Kolom lain (No, NIK, dll.) diabaikan otomatis.
                        </div>
                    </div>
                </div>

                <form id="formImport" method="POST" action="<?php echo e(route('admin.guru.import')); ?>" enctype="multipart/form-data">
                    <?php echo csrf_field(); ?>

                    <div class="drop-zone" id="dropZone" onclick="document.getElementById('excelFile').click()">
                        <i class="bi bi-cloud-arrow-up"></i>
                        <p>Klik atau <strong>drag &amp; drop</strong> file Excel di sini</p>
                        <p class="dz-hint">.xlsx atau .xls, maks. 5MB</p>
                        <input type="file" id="excelFile" name="file" accept=".xlsx,.xls" onchange="handleFile(this)">
                    </div>
                    <div id="file-chosen" style="display:none;">
                        <i class="bi bi-check-circle-fill me-1"></i>
                        <span id="file-name"></span>
                    </div>

                    <div id="col-map-wrap">
                        <div style="font-size:12px;font-weight:700;color:#0f172a;margin-bottom:10px;margin-top:16px;">
                            <i class="bi bi-arrow-left-right me-1 text-primary"></i>
                            Petakan kolom Excel → field sistem
                        </div>
                        <div class="col-map-grid">
                            <?php $__currentLoopData = [
                                'nama'            => ['label' => 'Nama Guru',                      'wajib' => true],
                                'jenis_identitas' => ['label' => 'Jenis ID (NIP/NRG/NPK/NIK/NUPTK/PegID)', 'wajib' => false],
                                'nomor_identitas' => ['label' => 'Nomor Identitas',                'wajib' => true],
                                'jenis_kelamin'   => ['label' => 'Jenis Kelamin',                  'wajib' => true],
                                'email'           => ['label' => 'Email (opsional)',                'wajib' => false],
                            ]; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $field => $cfg): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <div>
                                <label>
                                    <?php echo e($cfg['label']); ?>

                                    <?php if($cfg['wajib']): ?>
                                        <span style="color:#dc2626;">*</span>
                                    <?php else: ?>
                                        <span style="color:#16a34a;font-size:10px;">(opsional)</span>
                                    <?php endif; ?>
                                </label>
                                <select name="map[<?php echo e($field); ?>]" class="form-ctrl"
                                        id="map_<?php echo e($field); ?>" style="margin-bottom:0;">
                                    <option value="">— Pilih kolom Excel —</option>
                                </select>
                            </div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>

                        <div class="pwd-info" style="margin-top:12px;">
                            <i class="bi bi-key-fill" style="margin-top:1px;"></i>
                            <div>
                                <strong>Akun guru dibuat otomatis:</strong><br>
                                • Password: <code style="background:#fff;padding:1px 5px;border-radius:4px;border:1px solid #fde68a;">Gunungpari13</code><br>
                                • Username: nama tanpa gelar, huruf kecil
                                <span style="color:#92400e;">(contoh: DR. H. Budi Santoso, S.Pd → <code style="background:#fff;padding:1px 5px;border-radius:4px;border:1px solid #fde68a;">budisantoso</code>)</span><br>
                                • Email: dari kolom email, atau <code style="background:#fff;padding:1px 5px;border-radius:4px;border:1px solid #fde68a;">namaguru@gmail.com</code> jika kosong
                            </div>
                        </div>

                        <div id="import-stats" class="import-stat" style="display:none;">
                            <div class="is-box ok">
                                <div class="is-val" id="stat-total">0</div>
                                <div class="is-lbl">Total Baris</div>
                            </div>
                            <div class="is-box ok">
                                <div class="is-val" id="stat-valid">0</div>
                                <div class="is-lbl">Siap Import</div>
                            </div>
                            <div class="is-box err">
                                <div class="is-val" id="stat-skip">0</div>
                                <div class="is-lbl">Baris Dilewati</div>
                            </div>
                        </div>

                        <div id="import-preview">
                            <table>
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Nama</th>
                                        <th>Jenis ID</th>
                                        <th>Nomor ID</th>
                                        <th>Jenis Kelamin</th>
                                        <th>Email</th>
                                        <th>Username</th>
                                    </tr>
                                </thead>
                                <tbody id="preview-body"></tbody>
                            </table>
                        </div>

                        <div class="d-flex gap-2 mt-3">
                            <button type="button" class="btn-cancel"
                                    data-bs-dismiss="modal" onclick="resetImport()">Batal</button>
                            <button type="submit" class="btn-submit green"
                                    id="btnSubmitImport" disabled>
                                <i class="bi bi-check-circle me-1"></i> Import Sekarang
                            </button>
                        </div>
                    </div>

                    <input type="hidden" name="mapped_data" id="mappedDataInput">
                </form>
            </div>
        </div>
    </div>
</div>


<?php $__currentLoopData = $gurusSorted; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $g): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<div class="modal fade gm" id="edit<?php echo e($g->id); ?>" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-fullscreen-sm-down">
        <div class="modal-content">
            <div class="modal-header">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon-wrap"><i class="bi bi-pencil-square"></i></div>
                    <h5 class="modal-title">Edit Data Guru</h5>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form method="POST" action="<?php echo e(route('admin.guru.update', $g->id)); ?>" class="form-edit-guru">
                    <?php echo csrf_field(); ?> <?php echo method_field('PUT'); ?>

                    <label>Nama Lengkap</label>
                    <input type="text" name="nama" class="form-ctrl" value="<?php echo e($g->nama); ?>" required>

                    <div class="row-2" style="margin-bottom:14px;">
                        <div>
                            <label>Jenis ID</label>
                            <select name="jenis_identitas" class="form-ctrl" style="margin-bottom:0;">
                                <?php $__currentLoopData = ['NIP','NUPTK','NRG','PegID','NPK','NIK']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $opt): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($opt); ?>" <?php echo e($g->jenis_identitas == $opt ? 'selected' : ''); ?>><?php echo e($opt); ?></option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                        </div>
                        <div>
                            <label>Nomor Identitas</label>
                            <input type="text" name="nomor_identitas" class="form-ctrl"
                                   value="<?php echo e($g->nomor_identitas); ?>"
                                   style="font-family:'Courier New',monospace;margin-bottom:0;" required>
                        </div>
                    </div>

                    <label>Alamat Email</label>
                    <input type="email" name="email" class="form-ctrl" value="<?php echo e($g->user->email ?? ''); ?>" required>

                    <label>Jenis Kelamin</label>
                    <select name="jenis_kelamin" class="form-ctrl">
                        <option value="L" <?php echo e($g->jenis_kelamin == 'L' ? 'selected' : ''); ?>>Laki-laki</option>
                        <option value="P" <?php echo e($g->jenis_kelamin == 'P' ? 'selected' : ''); ?>>Perempuan</option>
                    </select>

                    <div class="d-flex gap-2">
                        <button type="button" class="btn-cancel" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn-submit btn-submit-edit" style="margin-top:0;">Simpan Perubahan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>


<div class="modal fade gm" id="modalTambahGuru" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-fullscreen-sm-down">
        <div class="modal-content">
            <div class="modal-header">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon-wrap"><i class="bi bi-person-plus"></i></div>
                    <h5 class="modal-title">Tambah Guru Baru</h5>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form method="POST" action="<?php echo e(route('admin.guru.store')); ?>" id="formTambahGuru">
                    <?php echo csrf_field(); ?>

                    <label>Nama Lengkap</label>
                    <input type="text" name="nama" class="form-ctrl"
                           placeholder="Contoh: DR. H. Budi Santoso, S.Pd., M.M." required>

                    <div class="row-2" style="margin-bottom:14px;">
                        <div>
                            <label>Jenis ID</label>
                            <select name="jenis_identitas" class="form-ctrl" style="margin-bottom:0;">
                                <option value="NIP">NIP</option>
                                <option value="NUPTK">NUPTK</option>
                                <option value="NRG">NRG</option>
                                <option value="PegID">PegID</option>
                                <option value="NPK">NPK</option>
                                <option value="NIK">NIK</option>
                            </select>
                        </div>
                        <div>
                            <label>Nomor Identitas</label>
                            <input type="text" name="nomor_identitas" class="form-ctrl"
                                   placeholder="1980xxxx"
                                   style="font-family:'Courier New',monospace;margin-bottom:0;" required>
                        </div>
                    </div>

                    <label>Alamat Email</label>
                    <input type="email" name="email" class="form-ctrl" placeholder="guru@gmail.com" required>

                    <label>Jenis Kelamin</label>
                    <select name="jenis_kelamin" class="form-ctrl">
                        <option value="" disabled selected>Pilih Jenis Kelamin...</option>
                        <option value="L">Laki-laki</option>
                        <option value="P">Perempuan</option>
                    </select>

                    <div class="pwd-info">
                        <i class="bi bi-info-circle-fill" style="margin-top:1px;"></i>
                        <div>
                            Username dibuat otomatis dari nama (tanpa gelar, huruf kecil).<br>
                            Password default: <code style="background:#fff;padding:1px 5px;border-radius:4px;border:1px solid #fde68a;">Gunungpari13</code>
                        </div>
                    </div>

                    <button type="submit" class="btn-submit" style="margin-top:14px;" id="btnSubmitTambah">
                        <i class="bi bi-check-circle me-2"></i> Daftarkan Guru
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>

<script>
<?php if(session('success')): ?>
    <?php if(!session('import_success_detail')): ?>
        Swal.fire({
            icon: 'success',
            title: 'Berhasil!',
            text: <?php echo json_encode(session('success')); ?>,
            timer: 2200,
            showConfirmButton: false,
            customClass: { popup: 'rounded-4' }
        });
    <?php endif; ?>
<?php endif; ?>

<?php if(session('error')): ?>
    Swal.fire({
        icon: 'error',
        title: 'Gagal!',
        text: <?php echo json_encode(session('error')); ?>,
        confirmButtonColor: '#dc2626',
        customClass: { popup: 'rounded-4', confirmButton: 'rounded-3 px-4' }
    });
<?php endif; ?>

<?php if(session('success') && session('import_success_detail')): ?>
<?php
    $okLines = array_filter(explode('||', session('import_success_detail')));
    $okHtml  = implode('', array_map(
        fn($l) => '<li style="padding:4px 0;border-bottom:1px solid #f1f5f9;">' . e(trim($l)) . '</li>',
        $okLines
    ));
?>
Swal.fire({
    icon: 'success',
    title: 'Import Berhasil',
    html: `<div style="text-align:left;font-size:12px;">
        <p style="color:#15803d;font-weight:700;margin:0 0 8px;"><?php echo e(session('success')); ?></p>
        <p style="color:#64748b;margin:0 0 6px;">Guru yang berhasil ditambahkan:</p>
        <ul style="max-height:260px;overflow-y:auto;list-style:none;margin:0;padding:6px 10px;
                   border:1px solid #f1f5f9;border-radius:8px;">
            <?php echo $okHtml; ?>

        </ul>
    </div>`,
    confirmButtonColor: '#16a34a',
    customClass: { popup: 'rounded-4', confirmButton: 'rounded-3 px-4' }
});
<?php endif; ?>

<?php if(session('warning')): ?>
<?php
    $warnLines = array_filter(explode(';', session('warning')));
    $warnHtml  = implode('', array_map(
        fn($l) => '<li style="padding:4px 0;border-bottom:1px solid #f1f5f9;">' . e(trim($l)) . '</li>',
        $warnLines
    ));
?>
Swal.fire({
    icon: 'warning',
    title: 'Import Sebagian Berhasil',
    html: `<div style="text-align:left;font-size:12px;">
        <p style="color:#64748b;margin:0 0 8px;">Data berikut gagal diimport:</p>
        <ul style="max-height:260px;overflow-y:auto;list-style:none;margin:0;padding:6px 10px;
                   border:1px solid #f1f5f9;border-radius:8px;">
            <?php echo $warnHtml; ?>

        </ul>
    </div>`,
    confirmButtonColor: '#4f46e5',
    customClass: { popup: 'rounded-4', confirmButton: 'rounded-3 px-4' }
});
<?php endif; ?>

<?php if($errors->any()): ?>
<?php
    $errHtml = implode('', array_map(
        fn($e) => '<li style="padding:4px 0;border-bottom:1px solid #f1f5f9;">' . e($e) . '</li>',
        $errors->all()
    ));
?>
Swal.fire({
    icon: 'error',
    title: 'Validasi Gagal',
    html: `<ul style="text-align:left;font-size:12px;list-style:none;margin:0;padding:6px 10px;
               max-height:240px;overflow-y:auto;border:1px solid #f1f5f9;border-radius:8px;">
        <?php echo $errHtml; ?>

    </ul>`,
    customClass: { popup: 'rounded-4', confirmButton: 'rounded-3 px-4' }
});
<?php endif; ?>

(function () {
    const formTambah = document.getElementById('formTambahGuru');
    if (formTambah) {
        formTambah.addEventListener('submit', function () {
            const btn = document.getElementById('btnSubmitTambah');
            btn.disabled = true;
            btn.innerHTML = '<i class="bi bi-arrow-repeat me-2"></i> Menyimpan...';
        });
    }

    document.querySelectorAll('.form-edit-guru').forEach(function (form) {
        form.addEventListener('submit', function () {
            const btn = form.querySelector('.btn-submit-edit');
            if (btn) {
                btn.disabled = true;
                btn.innerHTML = '<i class="bi bi-arrow-repeat me-2"></i> Menyimpan...';
            }
        });
    });
})();

(function () {
    const inputSearch = document.getElementById('inputSearchGuru');
    const formSearch   = document.getElementById('formSearchGuru');
    if (!inputSearch || !formSearch) return;

    let debounceTimer;
    inputSearch.addEventListener('input', function () {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => formSearch.submit(), 500);
    });
})();

function confirmDelete(id, nama) {
    Swal.fire({
        title: 'Hapus Data Guru?',
        html: `Data <strong>${nama}</strong> dan akun login-nya akan terhapus permanen.`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444', cancelButtonColor: '#94a3b8',
        confirmButtonText: 'Ya, Hapus', cancelButtonText: 'Batal',
        reverseButtons: true,
        customClass: { popup: 'rounded-4', confirmButton: 'rounded-3', cancelButton: 'rounded-3' }
    }).then(r => {
        if (r.isConfirmed) {
            Swal.fire({
                title: 'Menghapus...', allowOutsideClick: false, showConfirmButton: false,
                didOpen: () => Swal.showLoading(),
                customClass: { popup: 'rounded-4' }
            });
            document.getElementById('del-' + id).submit();
        }
    });
}

let excelData = [];
let excelCols = [];

const FIELDS = ['nama', 'jenis_identitas', 'nomor_identitas', 'jenis_kelamin', 'email'];
const WAJIB  = ['nama', 'nomor_identitas', 'jenis_kelamin'];

const AUTO_MAP = {
    'nama'            : ['namaguru', 'nama', 'namalengkap', 'namasiswa', 'guru'],
    'jenis_identitas' : ['jenisidentitas', 'jenisid', 'tipeid'],
    'nomor_identitas' : ['nip', 'nuptk', 'nrg', 'npk', 'pegid', 'nik', 'nomoridentitas', 'nomorid', 'identitas'],
    'jenis_kelamin'   : ['jeniskelamin', 'kelamin', 'gender', 'lp', 'jk'],
    'email'           : ['email', 'emailguru', 'surel'],
};

const dz = document.getElementById('dropZone');
dz.addEventListener('dragover',  e => { e.preventDefault(); dz.classList.add('dragover'); });
dz.addEventListener('dragleave', () => dz.classList.remove('dragover'));
dz.addEventListener('drop', e => {
    e.preventDefault(); dz.classList.remove('dragover');
    const f = e.dataTransfer.files[0];
    if (f) { document.getElementById('excelFile').files = e.dataTransfer.files; handleFile({ files: [f] }); }
});

function handleFile(input) {
    const file = input.files[0];
    if (!file) return;

    document.getElementById('file-chosen').style.display = 'block';
    document.getElementById('file-name').textContent = file.name;
    dz.style.borderColor = '#16a34a';

    const reader = new FileReader();
    reader.onload = e => {
        const wb  = XLSX.read(e.target.result, { type: 'array' });
        const ws  = wb.Sheets[wb.SheetNames[0]];
        const raw = XLSX.utils.sheet_to_json(ws, { header: 1, defval: '' });

        if (raw.length < 2) {
            Swal.fire({
                icon: 'error',
                title: 'File Tidak Valid',
                text: 'File kosong atau tidak memiliki data.',
                confirmButtonColor: '#dc2626',
                customClass: { popup: 'rounded-4', confirmButton: 'rounded-3 px-4' }
            });
            return;
        }

        excelCols = raw[0].map(c => String(c).trim());
        excelData = raw.slice(1).filter(r => r.some(c => String(c).trim() !== ''));

        FIELDS.forEach(field => {
            const sel = document.getElementById('map_' + field);
            sel.innerHTML = '<option value="">— Pilih kolom Excel —</option>';

            if (!WAJIB.includes(field)) {
                const optAuto = document.createElement('option');
                optAuto.value = 'auto';
                optAuto.textContent = '✦ Tidak ada / Generate otomatis';
                sel.appendChild(optAuto);
            }

            excelCols.forEach((col, i) => {
                const opt      = document.createElement('option');
                opt.value      = i;
                opt.textContent = col;

                const colClean = col.toLowerCase().replace(/[\s_\-\.\/]/g, '');
                const keywords = AUTO_MAP[field] || [];
                if (keywords.some(kw => colClean === kw || colClean.includes(kw) || kw.includes(colClean))) {
                    opt.selected = true;
                }
                sel.appendChild(opt);
            });

            if (!WAJIB.includes(field) && sel.value === '') sel.value = 'auto';
            sel.addEventListener('change', updatePreview);
        });

        document.getElementById('col-map-wrap').style.display = 'block';
        updatePreview();
    };
    reader.readAsArrayBuffer(file);
}

function generateUsername(namaAsli) {
    let nama = namaAsli.split(',')[0];
    const gelarDepan = [
        'Prof.', 'Prof', 'Dr.', 'Dr', 'dr.', 'dr',
        'Drs.', 'Drs.H.', 'Drs', 'Dra.', 'Dra',
        'Ir.', 'Ir', 'H.', 'H', 'Hj.', 'Hj',
        'KH.', 'KH', 'Lc.', 'Lc',
        'Ust.', 'Ust', 'Ustadz', 'Ustadzah',
    ].sort((a, b) => b.length - a.length);

    nama = nama.trim();
    for (const gelar of gelarDepan) {
        const pattern = new RegExp('^' + gelar.replace('.', '\\.') + '\\s', 'i');
        if (pattern.test(nama)) {
            nama = nama.replace(pattern, '').trim();
        }
    }
    return nama.toLowerCase().replace(/[^a-z]/g, '') || 'guru';
}

function generateEmail(namaAsli) {
    return generateUsername(namaAsli) + '13@gmail.com';
}

function deteksiJenisID(colName) {
    const c = (colName || '').toUpperCase();
    if (c.includes('NUPTK')) return 'NUPTK';
    if (c.includes('NRG'))   return 'NRG';
    if (c.includes('NPK'))   return 'NPK';
    if (c.includes('PegID'))  return 'PegID';
    if (c.includes('NIK'))   return 'NIK';
    return 'NIP';
}

function updatePreview() {
    const map = {};
    FIELDS.forEach(f => {
        const v = document.getElementById('map_' + f).value;
        map[f]  = (v !== '' && v !== 'auto') ? parseInt(v) : null;
    });

    const nomorIdxEl   = document.getElementById('map_nomor_identitas');
    const nomorColName = nomorIdxEl.options[nomorIdxEl.selectedIndex]?.textContent || '';

    const rows = excelData.map(row => {
        const obj = {};
        FIELDS.forEach(f => {
            obj[f] = (map[f] !== null)
                ? String(row[map[f]] ?? '').trim().replace(/^'+/, '')
                : '';
        });

        if (!obj['jenis_identitas'])        obj['jenis_identitas'] = deteksiJenisID(nomorColName);
        if (!obj['email'] && obj['nama'])   { obj['email'] = generateEmail(obj['nama']); obj['_email_auto'] = true; }
        obj['_username'] = obj['nama'] ? generateUsername(obj['nama']) : '—';
        return obj;
    });

    const valid = rows.filter(r => r.nama && r.nomor_identitas && r.jenis_kelamin);
    const skip  = rows.length - valid.length;

    document.getElementById('stat-total').textContent = rows.length;
    document.getElementById('stat-valid').textContent = valid.length;
    document.getElementById('stat-skip').textContent  = skip;
    document.getElementById('import-stats').style.display = 'flex';

    const tbody = document.getElementById('preview-body');
    tbody.innerHTML = '';
    rows.slice(0, 10).forEach((r, i) => {
        const ok = r.nama && r.nomor_identitas && r.jenis_kelamin;
        const tr = document.createElement('tr');
        tr.style.background = ok ? '' : '#fff7f7';
        tr.innerHTML = `
            <td style="color:#94a3b8;font-size:10px;">${i + 1}</td>
            <td style="font-weight:600;">${r.nama || '<span style="color:#dc2626;">—</span>'}</td>
            <td><span style="font-family:monospace;font-size:10px;background:#eef2ff;padding:1px 6px;border-radius:4px;color:#4338ca;">${r.jenis_identitas}</span></td>
            <td style="font-family:monospace;font-size:11px;">${r.nomor_identitas || '<span style="color:#dc2626;">—</span>'}</td>
            <td>${r.jenis_kelamin || '<span style="color:#dc2626;">—</span>'}</td>
            <td style="font-size:10px;color:${r._email_auto ? '#94a3b8' : '#1e293b'};">
                ${r.email}${r._email_auto ? ' <span style="font-size:9px;">(auto)</span>' : ''}
            </td>
            <td style="font-size:10px;color:#64748b;font-family:monospace;">${r._username}</td>
        `;
        tbody.appendChild(tr);
    });

    if (rows.length > 10) {
        const tr = document.createElement('tr');
        tr.innerHTML = `<td colspan="7" style="text-align:center;color:#94a3b8;font-size:11px;padding:8px;">
            … dan ${rows.length - 10} baris lainnya
        </td>`;
        tbody.appendChild(tr);
    }

    document.getElementById('import-preview').style.display = 'block';

    const validClean = valid.map(r => {
        const clean = {};
        FIELDS.forEach(f => clean[f] = r[f]);
        return clean;
    });
    document.getElementById('mappedDataInput').value   = JSON.stringify(validClean);
    document.getElementById('btnSubmitImport').disabled = valid.length === 0;
}

function resetImport() {
    excelData = []; excelCols = [];
    document.getElementById('excelFile').value                  = '';
    document.getElementById('file-chosen').style.display        = 'none';
    document.getElementById('col-map-wrap').style.display       = 'none';
    document.getElementById('import-preview').style.display     = 'none';
    document.getElementById('import-stats').style.display       = 'none';
    document.getElementById('btnSubmitImport').disabled         = true;
    document.getElementById('dropZone').style.borderColor       = '';
    FIELDS.forEach(f => {
        const s = document.getElementById('map_' + f);
        if (s) s.innerHTML = '<option value="">— Pilih kolom Excel —</option>';
    });
}

let pgCurrent = 1;
let pgRows    = 10;

function getRows() {
    return Array.from(document.querySelectorAll('.guru-row'));
}

function renderPage(page) {
    pgCurrent     = page;
    const rows    = getRows();
    const total   = rows.length;
    const pages   = Math.ceil(total / pgRows) || 1;
    pgCurrent     = Math.min(pgCurrent, pages);

    const start = (pgCurrent - 1) * pgRows;
    const end   = start + pgRows;

    rows.forEach((tr, i) => {
        tr.style.display = (i >= start && i < end) ? '' : 'none';
    });

    const from = total === 0 ? 0 : start + 1;
    const to   = Math.min(end, total);
    document.getElementById('pgInfo').textContent =
        `Menampilkan ${from}–${to} dari ${total} guru`;

    const btns = document.getElementById('pgBtns');
    btns.innerHTML = '';

    const prev = document.createElement('button');
    prev.className   = 'pg-btn';
    prev.innerHTML   = '<i class="bi bi-chevron-left"></i>';
    prev.disabled    = pgCurrent === 1;
    prev.onclick     = () => renderPage(pgCurrent - 1);
    btns.appendChild(prev);

    const rangeStart = Math.max(1, pgCurrent - 2);
    const rangeEnd   = Math.min(pages, pgCurrent + 2);

    if (rangeStart > 1) {
        btns.appendChild(mkPageBtn(1, pages));
        if (rangeStart > 2) btns.appendChild(mkEllipsis());
    }
    for (let i = rangeStart; i <= rangeEnd; i++) {
        btns.appendChild(mkPageBtn(i, pages));
    }
    if (rangeEnd < pages) {
        if (rangeEnd < pages - 1) btns.appendChild(mkEllipsis());
        btns.appendChild(mkPageBtn(pages, pages));
    }

    const next = document.createElement('button');
    next.className   = 'pg-btn';
    next.innerHTML   = '<i class="bi bi-chevron-right"></i>';
    next.disabled    = pgCurrent === pages;
    next.onclick     = () => renderPage(pgCurrent + 1);
    btns.appendChild(next);
}

function mkPageBtn(n, pages) {
    const btn = document.createElement('button');
    btn.className   = 'pg-btn' + (n === pgCurrent ? ' active' : '');
    btn.textContent = n;
    btn.onclick     = () => renderPage(n);
    return btn;
}

function mkEllipsis() {
    const span = document.createElement('span');
    span.textContent = '…';
    span.style.cssText = 'font-size:12px;color:#94a3b8;padding:0 4px;';
    return span;
}

function changePgRows() {
    pgRows = parseInt(document.getElementById('pgRows').value);
    renderPage(1);
}

window.addEventListener('load', function() { renderPage(1); });
</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.admin', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\absensi_muttaqin_v2\resources\views/guru/index.blade.php ENDPATH**/ ?>