<style>

/* ===== DASHBOARD KEPENDUDUKAN ===== */
.dash-stat-card {
    border-radius: 10px;
    border: none;
    box-shadow: 0 1px 4px rgba(0,0,0,.08);
    background: linear-gradient(135deg, #1abc9c 0%, #16a085 100%);
    transition: transform .15s, box-shadow .15s;
}
.dash-stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(26,188,156,.25);
}
.dash-stat-card .card-body {
    padding: 14px 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
}
.dash-stat-icon {
    width: 40px; height: 40px;
    border-radius: 8px;
    background: rgba(255,255,255,.22);
    display: flex; align-items: center; justify-content: center;
    flex-shrink: 0;
}
.dash-stat-icon i { font-size: 1.2rem; color: #fff; }
.dash-stat-label {
    font-size: .74rem;
    font-weight: 600;
    opacity: .88;
    color: #fff;
    margin-bottom: 2px;
    white-space: nowrap;
}
.dash-stat-value {
    font-size: 1.35rem;
    font-weight: 800;
    color: #fff;
    line-height: 1.1;
    white-space: nowrap;
}

/* Section card */
.dash-section-card {
    border-radius: 12px;
    border: none;
    box-shadow: 0 1px 5px rgba(0,0,0,.07);
    overflow: hidden;
    margin-bottom: 16px;
}
.dash-section-header {
    padding: 11px 18px;
    display: flex; align-items: center; justify-content: space-between;
    border-bottom: 1px solid #f1f3f5;
    background: #fff;
    flex-wrap: wrap;
    gap: 8px;
}
.dash-section-header .title {
    font-size: .83rem; font-weight: 700; color: #374151;
    display: flex; align-items: center; gap: 6px;
}

/* Warga table */
.dash-warga-table th {
    font-size: .72rem; text-transform: uppercase; letter-spacing: .04em;
    color: #6b7280; font-weight: 700; padding: 9px 14px;
    background: #f8fffe; border-bottom: 1.5px solid #e5e7eb; white-space: nowrap;
}
.dash-warga-table td {
    padding: 9px 14px; vertical-align: middle;
    font-size: .83rem; border-bottom: 1px solid #f3f4f6;
}
.dash-warga-table tbody tr:last-child td { border-bottom: none; }
.dash-warga-table tbody tr:hover { background: #f8fffe; }

/* Mobile card list */
.desktop-table { display: block; }
.mobile-warga-list { display: none; }

/* ─── PAGE HEADER ─────────────────────────────────────────── */
.ar-page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 14px;
  margin-bottom: 16px;
}
.ar-header-left h4 {
  font-size: 1.25rem;
  font-weight: 800;
  color: #0b5a52;
  margin: 0 0 5px;
  display: flex;
  align-items: center;
  gap: 11px;
  letter-spacing: -.3px;
}
.ar-header-left h4 .hi {
  width: 40px; height: 40px;
  border-radius: 11px;
  background: linear-gradient(135deg, #0d9488, #14b8a6);
  display: flex; align-items: center; justify-content: center;
  color: #fff; font-size: 1.05rem;
  box-shadow: 0 4px 12px rgba(13,148,136,0.32);
  flex-shrink: 0;
}
.ar-breadcrumb {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 0.77rem;
  color: #94a3b8;
  padding-left: 51px;
}
.ar-breadcrumb a { color: #0d9488; text-decoration: none; font-weight: 600; }
.ar-breadcrumb a:hover { text-decoration: underline; }
.ar-breadcrumb .sep { color: #e2e8f0; }

.btn-tambah {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  padding: 10px 24px;
  border-radius: 50px;
  border: none;
  background: #0d9488;
  color: #fff;
  font-size: 0.85rem;
  font-weight: 700;
  text-decoration: none;
  box-shadow: 0 3px 12px rgba(13,148,136,0.28);
  transition: all .2s;
  white-space: nowrap;
}
.btn-tambah:hover {
  background: #0b7a6e;
  box-shadow: 0 5px 16px rgba(13,148,136,0.38);
  transform: translateY(-1px);
  color: #fff;
}

/* ── Tombol Lihat Akun ── */
.btn-lihat-akun {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 14px;
    border-radius: 20px;
    border: 1.5px solid #f59e0b;
    background: #fffbeb;
    color: #92400e;
    font-size: .78rem;
    font-weight: 700;
    cursor: pointer;
    transition: all .2s;
    white-space: nowrap;
}
.btn-lihat-akun:hover { background: #f59e0b; color: #fff; border-color: #f59e0b; }
.btn-lihat-akun.aktif { background: #dcfce7; border-color: #6ee7b7; color: #065f46; }

/* ── Badge akun ── */
.akun-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-size: .72rem;
    font-weight: 600;
    padding: 3px 9px;
    border-radius: 6px;
}
.akun-badge.punya { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
.akun-badge.tidak { background: #f3f4f6; color: #9ca3af; border: 1px solid #e5e7eb; }

/* ── Password blur ── */
.pass-blur {
    filter: blur(4px);
    user-select: none;
    transition: filter .25s;
    cursor: pointer;
    font-size: .78rem;
    font-family: monospace;
    letter-spacing: .05em;
    display: inline-block;
}
.pass-blur:hover { filter: none; }

/* ── Modal kode rahasia ── */
.modal-kode .modal-content {
    border-radius: 16px;
    border: none;
    box-shadow: 0 8px 40px rgba(0,0,0,.18);
    overflow: hidden;
}
.modal-kode .modal-header {
    background: linear-gradient(135deg, #0d9488, #14b8a6);
    border: none;
    padding: 18px 22px;
}
.modal-kode .modal-body  { padding: 24px 22px; }
.modal-kode .modal-footer { border-top: 1px solid #f1f3f5; padding: 14px 22px; }

/* Input 4 digit */
.kode-input-wrap {
    display: flex;
    gap: 10px;
    justify-content: center;
    margin: 16px 0 8px;
}
.kode-input-wrap input {
    width: 52px; height: 56px;
    border: 2px solid #e5e7eb;
    border-radius: 10px;
    text-align: center;
    font-size: 1.4rem;
    font-weight: 800;
    color: #0b5a52;
    outline: none;
    transition: border-color .2s, box-shadow .2s;
    -webkit-appearance: none;
    -moz-appearance: textfield;
}
.kode-input-wrap input:focus {
    border-color: #14b8a6;
    box-shadow: 0 0 0 3px rgba(20,184,166,.15);
}
.kode-input-wrap input.salah {
    border-color: #ef4444;
    box-shadow: 0 0 0 3px rgba(239,68,68,.12);
    animation: shake .4s ease;
}
@keyframes shake {
    0%,100% { transform: translateX(0); }
    20%      { transform: translateX(-6px); }
    40%      { transform: translateX(6px); }
    60%      { transform: translateX(-4px); }
    80%      { transform: translateX(4px); }
}
.pesan-error {
    text-align: center;
    font-size: .8rem;
    color: #ef4444;
    font-weight: 600;
    min-height: 20px;
    margin-bottom: 4px;
}

/* ===== MOBILE ===== */
@media (max-width: 767.98px) {
    .stat-row > [class*='col-'] { flex: 0 0 50% !important; max-width: 50% !important; }
    .dash-stat-value { font-size: 1.1rem; }
    .dash-stat-label { font-size: .7rem; }
    .dash-stat-card .card-body { padding: 11px 12px; }
    .chart-row > [class*='col-'] { flex: 0 0 100% !important; max-width: 100% !important; }
    .top5-row  > [class*='col-'] { flex: 0 0 100% !important; max-width: 100% !important; }
    .desktop-table     { display: none !important; }
    .mobile-warga-list { display: flex !important; flex-direction: column; gap: 8px; padding: 10px; }
    .ar-page-header    { flex-direction: column; align-items: flex-start; }
    .btn-tambah        { width: 100%; justify-content: center; }
}
</style>

<script src="<?php echo base_url('assets/js/jquery-3.7.0.min.js'); ?>"></script>
<script src="<?php echo base_url('assets/js/jquery.dataTables.min.js'); ?>"></script>
<script src="<?php echo base_url('assets/js/chart.js'); ?>"></script>

<!-- ── Page Header ── -->
<div class="ar-page-header mb-3">
    <div class="ar-header-left">
        <h4>
            <span class="hi"><i class="bi bi-people-fill"></i></span>
            Dashboard Kependudukan
        </h4>
        <div class="ar-breadcrumb">
            <a href="<?php echo base_url('dashboard'); ?>">Dashboard</a>
            <span class="sep">/</span>
            <span>Kependudukan</span>
        </div>
    </div>
    <div style="display:flex; gap:8px; flex-wrap:wrap;">
        <a href="<?php echo base_url('warga/statistik'); ?>" class="btn-tambah" style="background:#0b7a6e;">
            <i class="bi bi-bar-chart-line"></i> Statistik & Grafik
        </a>
        <a href="<?php echo base_url('kartu-keluarga'); ?>" class="btn-tambah">
            <i class="bi bi-house-door"></i> Kelola via Kartu Keluarga
        </a>
    </div>
</div>

<!-- ── Stat Cards ── -->
<div class="row g-2 mb-3 stat-row">
    <div class="col-xl-3 col-md-6 col-6">
        <div class="card dash-stat-card">
            <div class="card-body">
                <div>
                    <div class="dash-stat-label">Total Jiwa</div>
                    <div class="dash-stat-value"><?php echo number_format($statistik['total_jiwa'], 0, ',', '.'); ?></div>
                </div>
                <div class="dash-stat-icon"><i class="bi bi-people-fill"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 col-6">
        <div class="card dash-stat-card">
            <div class="card-body">
                <div>
                    <div class="dash-stat-label">Total KK</div>
                    <div class="dash-stat-value"><?php echo number_format($statistik['total_kk'], 0, ',', '.'); ?></div>
                </div>
                <div class="dash-stat-icon"><i class="bi bi-house-door-fill"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 col-6">
        <div class="card dash-stat-card">
            <div class="card-body">
                <div>
                    <div class="dash-stat-label">Laki-Laki</div>
                    <div class="dash-stat-value"><?php echo number_format($statistik['total_pria'], 0, ',', '.'); ?></div>
                </div>
                <div class="dash-stat-icon"><i class="bi bi-gender-male"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 col-6">
        <div class="card dash-stat-card">
            <div class="card-body">
                <div>
                    <div class="dash-stat-label">Perempuan</div>
                    <div class="dash-stat-value"><?php echo number_format($statistik['total_wanita'], 0, ',', '.'); ?></div>
                </div>
                <div class="dash-stat-icon"><i class="bi bi-gender-female"></i></div>
            </div>
        </div>
    </div>
</div>

<!-- ── Tabel Warga ── -->
<div class="card dash-section-card">
    <div class="dash-section-header">
        <div class="title">
            <i class="bi bi-people" style="color:#1abc9c;"></i>Detail Data Warga
        </div>
        <div style="display:flex; align-items:center; gap:10px; flex-wrap:wrap;">
            <span class="badge fw-semibold" style="background:#d1fae5; color:#065f46; font-size:.75rem;">
                <?php echo number_format($statistik['total_jiwa']); ?> Orang
            </span>
            <?php if($this->session->userdata('role') === 'admin'): ?>
            <button type="button" class="btn-lihat-akun" id="btnLihatAkun"
                    data-bs-toggle="modal" data-bs-target="#modalKodeRahasia">
                <i class="bi bi-shield-lock"></i> Lihat Data Akun
            </button>
            <?php endif; ?>
        </div>
    </div>

    <?php
    $badge_domisili2   = ['tetap'=>'success','kost'=>'warning','kontrak'=>'info','pendatang'=>'danger','sementara'=>'secondary'];
    $status_hub_label2 = ['kepala_keluarga'=>'Kepala KK','istri'=>'Istri','anak'=>'Anak','cucu'=>'Cucu','orang_tua'=>'Orang Tua','mertua'=>'Mertua','famili_lain'=>'Famili Lain','pembantu'=>'Pembantu','lainnya'=>'Lainnya'];
    $hasWarga = !empty($warga);
    ?>

    <?php if($hasWarga): ?>

    <!-- Desktop Table -->
    <div class="desktop-table table-responsive">
        <table class="table dash-warga-table mb-0" id="tabelWarga">
            <thead>
                <tr>
                    <th class="px-3" style="width:50px;">No</th>
                    <th>NIK</th>
                    <th>Nama Lengkap</th>
                    <th>No KK</th>
                    <th>Status Hubungan</th>
                    <th>Domisili</th>
                    <!-- Index kolom 6 & 7 — dikelola DataTables API -->
                    <th>Username</th>
                    <th>Password</th>
                </tr>
            </thead>
            <tbody>
            <?php $no = 1; foreach($warga as $w):
                $hub        = $w->status_hubungan ?? 'lainnya';
                $dom        = $w->status_domisili ?? 'tetap';
                $badge      = $badge_domisili2[$dom] ?? 'secondary';
                $punya_akun = !empty($w->username);
            ?>
            <tr>
                <td class="px-3"><?php echo $no++; ?></td>
                <td>
                    <code style="font-size:.78rem; color:#e11d48;"><?php echo htmlspecialchars($w->nik ?? '-'); ?></code>
                </td>
                <td>
                    <strong style="font-size:.83rem;"><?php echo htmlspecialchars($w->nama_lengkap ?? '-'); ?></strong><br>
                    <small class="text-muted"><?php echo ($w->jenis_kelamin ?? '') == 'L' ? 'Laki-laki' : 'Perempuan'; ?></small>
                </td>
                <td>
                    <?php if(!empty($w->no_kk) && !empty($w->kk_id_rel)): ?>
                        <a href="<?php echo base_url('kartu-keluarga/detail/'.$w->kk_id_rel); ?>"
                           class="text-decoration-none fw-semibold" style="color:#1abc9c; font-size:.83rem;">
                            <?php echo htmlspecialchars($w->no_kk); ?>
                        </a>
                    <?php else: ?>
                        <span class="text-muted">-</span>
                    <?php endif; ?>
                </td>
                <td>
                    <span class="badge bg-light text-dark border" style="font-size:.73rem;">
                        <?php echo $status_hub_label2[$hub] ?? $hub; ?>
                    </span>
                </td>
                <td>
                    <span class="badge bg-<?php echo $badge; ?>" style="font-size:.73rem;">
                        <?php echo ucfirst($dom); ?>
                    </span>
                    <?php if(!empty($w->keterangan_domisili)): ?>
                        <br><small class="text-muted"><?php echo htmlspecialchars($w->keterangan_domisili); ?></small>
                    <?php endif; ?>
                </td>

                <!-- Kolom Username (index 6) -->
                <td>
                    <?php if($punya_akun): ?>
                        <span class="akun-badge punya">
                            <i class="bi bi-person-check"></i>
                            <?php echo htmlspecialchars($w->username); ?>
                        </span>
                    <?php else: ?>
                        <span class="akun-badge tidak">
                            <i class="bi bi-person-x"></i> Belum punya
                        </span>
                    <?php endif; ?>
                </td>

                <!-- Kolom Password (index 7) — tampilkan NIK sebagai password default -->
                <td>
                    <?php if($punya_akun): ?>
                        <span class="pass-blur" title="Hover untuk melihat">
                            <?php echo htmlspecialchars($w->nik ?? '-'); ?>
                        </span>
                        <br>
                        <small class="text-muted" style="font-size:.67rem;">
                            <i class="bi bi-info-circle"></i> default: NIK
                        </small>
                    <?php else: ?>
                        <span class="text-muted">—</span>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Mobile Card List -->
    <div class="mobile-warga-list">
        <?php foreach($warga as $w):
            $hub   = $w->status_hubungan ?? 'lainnya';
            $dom   = $w->status_domisili ?? 'tetap';
            $badge = $badge_domisili2[$dom] ?? 'secondary';
            $borderColors = ['success'=>'#1abc9c','warning'=>'#f59e0b','info'=>'#0ea5e9','danger'=>'#ef4444','secondary'=>'#9ca3af'];
            $bc = $borderColors[$badge] ?? '#e5e7eb';
            $punya_akun = !empty($w->username);
        ?>
        <div style="border-radius:10px; border:1.5px solid #f1f3f5; border-left:4px solid <?php echo $bc; ?>; background:#fff; padding:11px 13px;">
            <div class="d-flex justify-content-between align-items-start mb-1">
                <div>
                    <div class="fw-semibold" style="font-size:.86rem;"><?php echo htmlspecialchars($w->nama_lengkap ?? '-'); ?></div>
                    <code style="font-size:.74rem; color:#6b7280;"><?php echo htmlspecialchars($w->nik ?? '-'); ?></code>
                </div>
                <span class="badge bg-<?php echo $badge; ?> flex-shrink-0 ms-2" style="font-size:.72rem;">
                    <?php echo ucfirst($dom); ?>
                </span>
            </div>
            <div class="d-flex gap-2 align-items-center mt-1 flex-wrap" style="font-size:.76rem; color:#6b7280;">
                <span class="badge bg-light text-dark border" style="font-size:.71rem;">
                    <?php echo $status_hub_label2[$hub] ?? $hub; ?>
                </span>
                <span>·</span>
                <span><?php echo ($w->jenis_kelamin ?? '') == 'L' ? 'Laki-laki' : 'Perempuan'; ?></span>
                <?php if(!empty($w->no_kk) && !empty($w->kk_id_rel)): ?>
                <span>·</span>
                <a href="<?php echo base_url('kartu-keluarga/detail/'.$w->kk_id_rel); ?>"
                   style="color:#1abc9c; font-size:.74rem; text-decoration:none; font-weight:600;">
                    KK <?php echo htmlspecialchars($w->no_kk); ?>
                </a>
                <?php endif; ?>
            </div>

            <!-- Info akun mobile -->
            <?php if($this->session->userdata('role') === 'admin'): ?>
            <div class="info-akun-mobile mt-2" style="display:none; border-top:1px solid #f3f4f6; padding-top:8px;">
                <?php if($punya_akun): ?>
                <div style="font-size:.75rem; color:#374151; margin-bottom:3px;">
                    <i class="bi bi-person-check me-1" style="color:#1abc9c;"></i>
                    <strong>Username:</strong> <?php echo htmlspecialchars($w->username); ?>
                </div>
                <div style="font-size:.75rem; color:#374151;">
                    <i class="bi bi-key me-1" style="color:#f59e0b;"></i>
                    <strong>Password:</strong>
                    <span class="pass-blur"><?php echo htmlspecialchars($w->nik ?? '-'); ?></span>
                    <small class="text-muted">(default: NIK)</small>
                </div>
                <?php else: ?>
                <div style="font-size:.75rem; color:#9ca3af;">
                    <i class="bi bi-person-x me-1"></i>Belum memiliki akun
                </div>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>

    <?php else: ?>
    <div class="text-center py-5 text-muted">
        <i class="bi bi-inbox fs-1 d-block mb-2 opacity-50"></i>
        <div class="fw-semibold mb-2">Belum ada data warga</div>
        <a href="<?php echo base_url('kartu-keluarga'); ?>" class="btn btn-success btn-sm">
            <i class="bi bi-plus-lg me-1"></i>Tambah via Kartu Keluarga
        </a>
    </div>
    <?php endif; ?>
</div>

</div><!-- /.main wrap -->


<?php if($this->session->userdata('role') === 'admin'): ?>
<!-- ===== MODAL KODE RAHASIA ===== -->
<div class="modal fade modal-kode" id="modalKodeRahasia" tabindex="-1"
     data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog modal-dialog-centered" style="max-width:360px;">
        <div class="modal-content">
            <div class="modal-header">
                <div>
                    <h6 class="modal-title text-white fw-bold mb-0">
                        <i class="bi bi-shield-lock me-2"></i>Verifikasi Kode Rahasia
                    </h6>
                    <div style="font-size:.73rem; color:rgba(255,255,255,.78); margin-top:2px;">
                        Masukkan 4 digit kode untuk mengakses data akun warga
                    </div>
                </div>
                <button type="button" class="btn-close btn-close-white ms-3" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center">
                <div style="width:60px;height:60px;border-radius:14px;background:#f0fdfa;display:flex;align-items:center;justify-content:center;margin:0 auto 14px;border:2px solid #ccfbf1;">
                    <i class="bi bi-incognito" style="font-size:1.6rem;color:#0d9488;"></i>
                </div>
                <div style="font-size:.83rem;color:#6b7280;margin-bottom:4px;">
                    Fitur ini hanya untuk <strong style="color:#0b5a52;">Admin</strong>
                </div>

                <div class="kode-input-wrap" id="kodeInputWrap">
                    <input type="number" class="kode-digit" min="0" max="9" placeholder="•" autocomplete="off">
                    <input type="number" class="kode-digit" min="0" max="9" placeholder="•" autocomplete="off">
                    <input type="number" class="kode-digit" min="0" max="9" placeholder="•" autocomplete="off">
                    <input type="number" class="kode-digit" min="0" max="9" placeholder="•" autocomplete="off">
                </div>

                <div class="pesan-error" id="pesanError"></div>

                <div style="font-size:.73rem;color:#9ca3af;margin-top:6px;">
                    <i class="bi bi-eye-slash me-1"></i>
                    Password ditampilkan dalam mode blur. Hover untuk melihat.
                </div>
            </div>
            <div class="modal-footer justify-content-between">
                <button type="button" class="btn btn-outline-secondary btn-sm"
                        data-bs-dismiss="modal" style="border-radius:8px;font-size:.8rem;">
                    Batal
                </button>
                <button type="button" class="btn btn-sm fw-bold" id="btnVerifikasi"
                    style="background:#0d9488;color:#fff;border:none;border-radius:8px;padding:7px 20px;font-size:.82rem;">
                    <i class="bi bi-unlock me-1"></i>Verifikasi
                </button>
            </div>
        </div>
    </div>
</div>

<script>
$(function () {
    var KODE_RAHASIA = '2016';
    var sudahUnlock  = false;
    var dtTable      = null; // instance DataTables

    // ── Init DataTables — kolom 6 & 7 tersembunyi di awal ──
    dtTable = $('#tabelWarga').DataTable({
        responsive  : true,
        pageLength  : 10,
        order       : [[2, 'asc']],
        columnDefs  : [
            { orderable: false, targets: [0, 6, 7] },
            // KUNCI FIX: sembunyikan kolom 6 & 7 via DataTables API, bukan CSS
            { visible: false, targets: [6, 7] }
        ],
        language: {
            search           : 'Cari:',
            searchPlaceholder: 'Cari nama, NIK...',
            lengthMenu       : 'Tampilkan _MENU_ data',
            info             : 'Menampilkan _START_ - _END_ dari _TOTAL_ warga',
            infoEmpty        : 'Tidak ada data',
            infoFiltered     : '(dari _MAX_ total)',
            zeroRecords      : 'Data tidak ditemukan',
            paginate         : { previous: 'Sebelumnya', next: 'Berikutnya' }
        }
    });

    // ── Input digit: auto-focus & auto-submit ───────────────
    var digits   = document.querySelectorAll('.kode-digit');
    var modalEl  = document.getElementById('modalKodeRahasia');
    var btnVerif = document.getElementById('btnVerifikasi');
    var pesanEl  = document.getElementById('pesanError');
    var btnLihat = document.getElementById('btnLihatAkun');

    digits.forEach(function (inp, idx) {
        inp.addEventListener('input', function () {
            if (this.value.length > 1) this.value = this.value.slice(-1);
            if (this.value !== '' && idx < digits.length - 1) {
                digits[idx + 1].focus();
            }
            var kode = Array.from(digits).map(function(d){ return d.value; }).join('');
            if (kode.length === 4) btnVerif.click();
        });
        inp.addEventListener('keydown', function (e) {
            if (e.key === 'Backspace' && this.value === '' && idx > 0) {
                digits[idx - 1].focus();
            }
        });
        inp.addEventListener('wheel', function(e){ e.preventDefault(); }, { passive: false });
    });

    // ── Reset saat modal dibuka ─────────────────────────────
    $(modalEl).on('show.bs.modal', function () {
        if (sudahUnlock) {
            // Kalau sudah unlock → tombol berfungsi sebagai toggle sembunyikan
            bootstrap.Modal.getInstance(modalEl).hide();
            sembunyikanAkun();
            return;
        }
        resetInput();
        setTimeout(function(){ if (digits[0]) digits[0].focus(); }, 420);
    });

    // ── Verifikasi kode ─────────────────────────────────────
    btnVerif.addEventListener('click', function () {
        var kode = Array.from(digits).map(function(d){ return d.value; }).join('');

        if (kode.length < 4) {
            tampilError('Masukkan 4 digit kode rahasia');
            return;
        }

        if (kode === KODE_RAHASIA) {
            sudahUnlock = true;
            bootstrap.Modal.getInstance(modalEl).hide();
            tampilkanAkun();
        } else {
            tampilError('Kode salah! Silakan coba lagi.');
            digits.forEach(function(d){ d.classList.add('salah'); d.value = ''; });
            setTimeout(function(){
                digits.forEach(function(d){ d.classList.remove('salah'); });
                if (digits[0]) digits[0].focus();
            }, 600);
        }
    });

    // ── Tampilkan kolom akun via DataTables API ─────────────
    function tampilkanAkun() {
        // Gunakan DataTables API — ini yang benar, bukan CSS class
        // Sehingga kolom tetap tampil di semua halaman
        dtTable.columns([6, 7]).visible(true);

        // Mobile: tampilkan info akun
        document.querySelectorAll('.info-akun-mobile').forEach(function(el){
            el.style.display = 'block';
        });

        // Ubah tombol
        if (btnLihat) {
            btnLihat.classList.add('aktif');
            btnLihat.innerHTML = '<i class="bi bi-shield-check"></i> Sembunyikan Akun';
            btnLihat.removeAttribute('data-bs-toggle');
            btnLihat.removeAttribute('data-bs-target');
            btnLihat.addEventListener('click', sembunyikanAkun, { once: true });
        }
    }

    // ── Sembunyikan kolom via DataTables API ────────────────
    function sembunyikanAkun() {
        sudahUnlock = false;

        // Gunakan DataTables API — konsisten dengan tampilkanAkun()
        dtTable.columns([6, 7]).visible(false);

        // Mobile: sembunyikan info akun
        document.querySelectorAll('.info-akun-mobile').forEach(function(el){
            el.style.display = 'none';
        });

        if (btnLihat) {
            btnLihat.classList.remove('aktif');
            btnLihat.innerHTML = '<i class="bi bi-shield-lock"></i> Lihat Data Akun';
            btnLihat.setAttribute('data-bs-toggle', 'modal');
            btnLihat.setAttribute('data-bs-target', '#modalKodeRahasia');
        }
    }

    // ── Helper ──────────────────────────────────────────────
    function resetInput() {
        digits.forEach(function(d){ d.value = ''; d.classList.remove('salah'); });
        pesanEl.textContent = '';
    }
    function tampilError(pesan) {
        pesanEl.textContent = pesan;
        setTimeout(function(){ pesanEl.textContent = ''; }, 3000);
    }
});
</script>
<?php endif; ?>