<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

<?php
// Letakkan di paling atas, sebelum tag <style>
if (!function_exists('maskId')) {
    function maskId($val) {
        if (empty($val)) return '—';
        $s = (string)$val;
        if (strlen($s) <= 8) return str_repeat('x', strlen($s));
        return substr($s, 0, 4) . str_repeat('*', strlen($s) - 8) . substr($s, -4);
    }
}
?>

<style>

/* ===== DASHBOARD KEPENDUDUKAN ===== */

/* ── Stat Grid Besar (gaya pemilih) ── */
.pemilu-stat-grid {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 14px;
    margin-bottom: 14px;
}
.pemilu-stat-grid-2 {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 14px;
    margin-bottom: 20px;
}
.pemilu-stat-card {
    border-radius: 14px;
    padding: 20px 18px;
    position: relative;
    overflow: hidden;
    color: #fff;
    transition: transform .2s, box-shadow .2s;
    cursor: pointer;
    text-decoration: none;
    display: block;
    -webkit-tap-highlight-color: transparent;
    min-height: 110px;
}
.pemilu-stat-card:hover {
    transform: translateY(-4px);
    color: #fff;
    text-decoration: none;
}
.pemilu-stat-card:active { transform: translateY(0); }
.pemilu-stat-card::before {
    content: '';
    position: absolute;
    top: -28px; right: -28px;
    width: 120px; height: 120px;
    border-radius: 50%;
    background: rgba(255,255,255,.1);
}
.pemilu-stat-card::after {
    content: '';
    position: absolute;
    bottom: -45px; right: 40px;
    width: 160px; height: 160px;
    border-radius: 50%;
    background: rgba(255,255,255,.06);
}
.sc-label {
    font-size: .72rem;
    font-weight: 600;
    opacity: .85;
    text-transform: uppercase;
    letter-spacing: .06em;
    margin-bottom: 8px;
    position: relative;
    z-index: 1;
    display: flex;
    align-items: center;
    gap: 5px;
}
.sc-value {
    font-size: 1.55rem;
    font-weight: 800;
    line-height: 1.15;
    position: relative;
    z-index: 1;
}
.sc-sub {
    font-size: .72rem;
    opacity: .75;
    margin-top: 5px;
    position: relative;
    z-index: 1;
}
.sc-icon {
    position: absolute;
    right: 16px; top: 50%;
    transform: translateY(-50%);
    width: 46px; height: 46px;
    background: rgba(255,255,255,.16);
    border-radius: 12px;
    display: flex; align-items: center; justify-content: center;
    font-size: 1.3rem;
    z-index: 1;
}

/* Card color variants */
.sc-teal   { background: linear-gradient(135deg, #0b5a52, #0d9488, #2dd4bf); box-shadow: 0 8px 28px rgba(13,148,136,.28); }
.sc-teal:hover   { box-shadow: 0 12px 32px rgba(13,148,136,.40); }
.sc-green  { background: linear-gradient(135deg, #065f46, #059669, #34d399); box-shadow: 0 8px 28px rgba(16,185,129,.28); }
.sc-green:hover  { box-shadow: 0 12px 32px rgba(16,185,129,.40); }
.sc-blue   { background: linear-gradient(135deg, #1e40af, #3b82f6, #93c5fd); box-shadow: 0 8px 28px rgba(29,78,216,.28); }
.sc-blue:hover   { box-shadow: 0 12px 32px rgba(29,78,216,.40); }
.sc-rose   { background: linear-gradient(135deg, #9f1239, #e11d48, #fb7185); box-shadow: 0 8px 28px rgba(225,29,72,.28); }
.sc-rose:hover   { box-shadow: 0 12px 32px rgba(225,29,72,.40); }
.sc-orange { background: linear-gradient(135deg, #d97706, #f59e0b, #fbbf24); box-shadow: 0 8px 28px rgba(245,158,11,.28); }
.sc-orange:hover { box-shadow: 0 12px 32px rgba(245,158,11,.40); }
.sc-purple { background: linear-gradient(135deg, #5b21b6, #7c3aed, #a78bfa); box-shadow: 0 8px 28px rgba(124,58,237,.28); }
.sc-purple:hover { box-shadow: 0 12px 32px rgba(124,58,237,.40); }
.sc-amber  { background: linear-gradient(135deg, #b45309, #d97706, #f59e0b); box-shadow: 0 8px 28px rgba(180,83,9,.28); }
.sc-amber:hover  { box-shadow: 0 12px 32px rgba(180,83,9,.40); }
.sc-slate  { background: linear-gradient(135deg, #334155, #64748b, #94a3b8); box-shadow: 0 4px 16px rgba(100,116,139,.2); }
.sc-slate:hover  { box-shadow: 0 8px 24px rgba(100,116,139,.36); }

/* Section label pemisah */
.stat-section-label {
    font-size: .72rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .07em;
    color: #94a3b8;
    margin-bottom: 10px;
    margin-top: 4px;
    display: flex;
    align-items: center;
    gap: 6px;
}
.stat-section-label::after {
    content: '';
    flex: 1;
    height: 1px;
    background: #e5e7eb;
    border-radius: 1px;
}

/* ── Banner Filter Aktif ── */
.filter-banner {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 16px;
    background: #f0fdfa;
    border: 1.5px solid #99f6e4;
    border-radius: 10px;
    margin-bottom: 16px;
    flex-wrap: wrap;
}
.filter-banner-label {
    display: flex;
    align-items: center;
    gap: 7px;
    font-size: .83rem;
    font-weight: 700;
    color: #0b5a52;
}
.filter-banner-label i { color: #0d9488; font-size: .9rem; }
.filter-banner-badge {
    padding: 3px 12px;
    border-radius: 999px;
    font-size: .78rem;
    font-weight: 700;
    background: #0d9488;
    color: #fff;
}
.filter-banner-count {
    font-size: .78rem;
    color: #475569;
    font-weight: 600;
}
.filter-banner-clear {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-size: .77rem;
    color: #ef4444;
    text-decoration: none;
    font-weight: 700;
    padding: 4px 10px;
    border-radius: 6px;
    border: 1.5px solid #fca5a5;
    background: #fff;
    transition: all .15s;
    margin-left: auto;
}
.filter-banner-clear:hover {
    background: #ef4444;
    color: #fff;
    border-color: #ef4444;
}

/* 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; }

/* ── No HP cell ── */
.nohp-link {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    color: #0d9488;
    text-decoration: none;
    font-size: .82rem;
    font-weight: 600;
    transition: color .15s;
}
.nohp-link:hover { color: #0b7a6e; text-decoration: underline; }
.nohp-empty { color: #d1d5db; font-size: .8rem; }

/* ── Badge Role ── */
.role-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-size: .7rem;
    font-weight: 700;
    padding: 3px 9px;
    border-radius: 6px;
    white-space: nowrap;
}
.role-badge.admin      { background: #fef3c7; color: #92400e; border: 1px solid #fcd34d; }
.role-badge.ketua_rt   { background: #dbeafe; color: #1e40af; border: 1px solid #93c5fd; }
.role-badge.sekretaris { background: #ede9fe; color: #5b21b6; border: 1px solid #c4b5fd; }
.role-badge.bendahara  { background: #dcfce7; color: #166534; border: 1px solid #86efac; }
.role-badge.warga      { background: #f3f4f6; color: #374151; border: 1px solid #d1d5db; }

/* ── Tombol ubah role kecil ── */
.btn-ubah-role {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 3px 8px;
    border-radius: 6px;
    border: 1.5px solid #e2e8f0;
    background: #f8fafc;
    color: #475569;
    font-size: .7rem;
    font-weight: 600;
    cursor: pointer;
    transition: all .15s;
    white-space: nowrap;
    margin-left: 4px;
}
.btn-ubah-role:hover { background: #0d9488; border-color: #0d9488; color: #fff; }

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

/* ── Modal ubah role ── */
.modal-ubah-role .modal-content {
    border-radius: 16px;
    border: none;
    box-shadow: 0 8px 40px rgba(0,0,0,.18);
    overflow: hidden;
}
.modal-ubah-role .modal-header {
    background: linear-gradient(135deg, #1e40af, #3b82f6);
    border: none;
    padding: 16px 20px;
}
.modal-ubah-role .modal-body  { padding: 20px; }
.modal-ubah-role .modal-footer { border-top: 1px solid #f1f3f5; padding: 12px 20px; }

/* Radio role pills */
.role-radio-group {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 10px;
}
.role-radio-group input[type="radio"] { display: none; }
.role-radio-group label {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 7px 14px;
    border-radius: 8px;
    border: 2px solid #e5e7eb;
    background: #f9fafb;
    color: #374151;
    font-size: .8rem;
    font-weight: 600;
    cursor: pointer;
    transition: all .15s;
}
.role-radio-group input[type="radio"]:checked + label {
    border-color: #0d9488;
    background: #f0fdfa;
    color: #0b5a52;
    box-shadow: 0 0 0 3px rgba(13,148,136,.12);
}
.role-radio-group label:hover { border-color: #0d9488; background: #f0fdfa; }

/* 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;
}

/* ── Banner meninggal ── */
.bm-pill {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 3px 10px;
    border-radius: 999px;
    font-size: .72rem;
    font-weight: 600;
    background: #f3f4f6;
    border: 1px solid #d1d5db;
    color: #374151;
    text-decoration: none;
    transition: all .15s;
}
.bm-pill:hover {
    background: #4b5563;
    color: #fff;
    border-color: #4b5563;
}

/* Toast notifikasi role */
#toastRoleWrap {
    position: fixed;
    bottom: 24px;
    right: 24px;
    z-index: 9999;
    display: flex;
    flex-direction: column;
    gap: 8px;
}
.toast-role {
    min-width: 260px;
    padding: 12px 16px;
    border-radius: 10px;
    background: #fff;
    box-shadow: 0 4px 20px rgba(0,0,0,.14);
    font-size: .82rem;
    font-weight: 600;
    color: #374151;
    display: flex;
    align-items: center;
    gap: 10px;
    border-left: 4px solid #0d9488;
    animation: slideInToast .3s ease;
}
.toast-role.error { border-left-color: #ef4444; }
@keyframes slideInToast {
    from { transform: translateX(60px); opacity: 0; }
    to   { transform: translateX(0);    opacity: 1; }
}

/* ===== MOBILE ===== */
@media (max-width: 1199px) {
    .pemilu-stat-grid,
    .pemilu-stat-grid-2 { grid-template-columns: repeat(3, 1fr); }
}
@media (max-width: 767.98px) {
    .pemilu-stat-grid,
    .pemilu-stat-grid-2 { grid-template-columns: repeat(2, 1fr); gap: 10px; }
    .sc-value  { font-size: 1.1rem; }
    .sc-icon   { width: 38px; height: 38px; font-size: 1rem; right: 12px; }
    .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; }
    .filter-banner-clear { margin-left: 0; }
}
</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>

<?php
/* ── Label & konfigurasi filter ── */
$filter_config = [
    'balita'    => ['label'=>'Balita (0–4 tahun)',         'icon'=>'bi-emoji-smile-fill',  'color'=>'#f59e0b'],
    'lansia'    => ['label'=>'Lansia (≥60 tahun)',          'icon'=>'bi-person-walking',    'color'=>'#7c3aed'],
    'janda'     => ['label'=>'Janda (Cerai – Perempuan)',   'icon'=>'bi-person-heart',      'color'=>'#e11d48'],
    'duda'      => ['label'=>'Duda (Cerai – Laki-laki)',    'icon'=>'bi-person-heart',      'color'=>'#1d4ed8'],
    'laki'      => ['label'=>'Laki-laki',                   'icon'=>'bi-gender-male',       'color'=>'#0d9488'],
    'perempuan' => ['label'=>'Perempuan',                   'icon'=>'bi-gender-female',     'color'=>'#e11d48'],
    'meninggal' => ['label'=>'Warga Meninggal',             'icon'=>'bi-heartbreak',        'color'=>'#6b7280'],
];
$filter_aktif  = $filter ?? null;
$filter_info   = $filter_aktif ? ($filter_config[$filter_aktif] ?? null) : null;

/* ── Hitung balita, lansia, janda, duda dari $warga ── */
$_now = new DateTime();
$_total_balita = 0; $_total_lansia = 0; $_total_janda = 0; $_total_duda = 0;
$_cerai_kw = ['cerai','cerai hidup','cerai mati','duda','janda'];
foreach($warga as $_w) {
    if (!empty($_w->tanggal_lahir)) {
        $_umur = (int)$_now->diff(new DateTime($_w->tanggal_lahir))->y;
        if ($_umur <= 4)  $_total_balita++;
        if ($_umur >= 60) $_total_lansia++;
    }
    if (!empty($_w->status_perkawinan)) {
        $_sp_low = strtolower(trim($_w->status_perkawinan));
        $_is_cerai = false;
        foreach ($_cerai_kw as $_kw) { if (strpos($_sp_low, $_kw) !== false) { $_is_cerai = true; break; } }
        if ($_is_cerai) {
            $_jk = strtolower(trim($_w->jenis_kelamin ?? ''));
            if (in_array($_jk, ['perempuan','p'])) $_total_janda++;
            elseif (in_array($_jk, ['laki-laki','laki','l'])) $_total_duda++;
        }
    }
}

/* ── Hitung persentase ── */
$_total_jiwa = $statistik['total_jiwa'] ?? 0;
$_pct_pria   = $_total_jiwa > 0 ? round(($statistik['total_pria']  / $_total_jiwa) * 100, 1) : 0;
$_pct_wanita = $_total_jiwa > 0 ? round(($statistik['total_wanita'] / $_total_jiwa) * 100, 1) : 0;
?>

<!-- ── 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>
        <?php if($this->session->userdata('role') === 'admin'): ?>
        <!-- Tombol Kirim Ucapan Ultah via WAHA -->
        <button type="button" id="btnKirimUltah"
                class="btn-tambah"
                style="background:linear-gradient(135deg,#f59e0b,#d97706);"
                title="Kirim ucapan selamat ulang tahun ke warga yang berulang tahun hari ini">
            <i class="bi bi-balloon-heart"></i> Ucapan Ultah WA
        </button>
        <a href="<?php echo base_url('export/index/warga/excel'); ?>" class="btn-tambah" style="background:linear-gradient(135deg,#059669,#10b981);">
            <i class="bi bi-file-earmark-spreadsheet"></i> Export Excel
        </a>
        <a href="<?php echo base_url('export/index/warga/pdf'); ?>" class="btn-tambah" style="background:linear-gradient(135deg,#dc2626,#ef4444);">
            <i class="bi bi-file-earmark-pdf"></i> Export PDF
        </a>
        <?php endif; ?>
    </div>
</div>

<!-- ══════════ STAT CARDS ROW 1 — Ringkasan Utama ══════════ -->
<div class="stat-section-label">
    <i class="bi bi-people-fill" style="color:#0d9488;"></i> Ringkasan Kependudukan
</div>

<div class="pemilu-stat-grid mb-3">

    <!-- Total Jiwa -->
    <a href="<?php echo base_url('warga'); ?>" class="pemilu-stat-card sc-teal" title="Semua warga">
        <div class="sc-label"><i class="bi bi-people-fill"></i> Total Jiwa</div>
        <div class="sc-value"><?php echo number_format($statistik['total_jiwa'], 0, ',', '.'); ?></div>
        <div class="sc-sub">seluruh warga aktif</div>
        <div class="sc-icon"><i class="bi bi-people-fill"></i></div>
    </a>

    <!-- Total KK -->
    <a href="<?php echo base_url('kartu-keluarga'); ?>" class="pemilu-stat-card sc-green" title="Kartu Keluarga">
        <div class="sc-label"><i class="bi bi-house-door-fill"></i> Total KK</div>
        <div class="sc-value"><?php echo number_format($statistik['total_kk'], 0, ',', '.'); ?></div>
        <div class="sc-sub">kartu keluarga</div>
        <div class="sc-icon"><i class="bi bi-house-door-fill"></i></div>
    </a>

    <!-- Laki-laki -->
    <a href="<?php echo base_url('warga?filter=laki'); ?>" class="pemilu-stat-card sc-blue" title="Filter warga laki-laki">
        <div class="sc-label"><i class="bi bi-gender-male"></i> Laki-Laki</div>
        <div class="sc-value"><?php echo number_format($statistik['total_pria'], 0, ',', '.'); ?></div>
        <div class="sc-sub"><?php echo $_pct_pria; ?>% dari total jiwa</div>
        <div class="sc-icon"><i class="bi bi-gender-male"></i></div>
    </a>

    <!-- Perempuan -->
    <a href="<?php echo base_url('warga?filter=perempuan'); ?>" class="pemilu-stat-card sc-rose" title="Filter warga perempuan">
        <div class="sc-label"><i class="bi bi-gender-female"></i> Perempuan</div>
        <div class="sc-value"><?php echo number_format($statistik['total_wanita'], 0, ',', '.'); ?></div>
        <div class="sc-sub"><?php echo $_pct_wanita; ?>% dari total jiwa</div>
        <div class="sc-icon"><i class="bi bi-gender-female"></i></div>
    </a>

    <!-- Meninggal -->
    <?php if(!empty($statistik['total_meninggal']) && $statistik['total_meninggal'] > 0): ?>
    <a href="<?php echo base_url('warga?filter=meninggal'); ?>" class="pemilu-stat-card sc-slate" title="Lihat warga meninggal">
        <div class="sc-label"><i class="bi bi-heartbreak"></i> Meninggal</div>
        <div class="sc-value"><?php echo number_format($statistik['total_meninggal'], 0, ',', '.'); ?></div>
        <div class="sc-sub">tercatat di sistem</div>
        <div class="sc-icon"><i class="bi bi-heartbreak"></i></div>
    </a>
    <?php else: ?>
    <!-- Placeholder kosong agar grid tetap 5 kolom jika tidak ada meninggal -->
    <div></div>
    <?php endif; ?>

</div>

<!-- ══════════ STAT CARDS ROW 2 — Segmentasi Usia & Status ══════════ -->
<div class="stat-section-label">
    <i class="bi bi-clock-history" style="color:#7c3aed;"></i> Segmentasi Usia &amp; Status
</div>

<div class="pemilu-stat-grid-2 mb-3">

    <!-- Balita -->
    <a href="<?php echo base_url('warga?filter=balita'); ?>" class="pemilu-stat-card sc-orange" title="Filter balita">
        <div class="sc-label"><i class="bi bi-emoji-smile-fill"></i> Balita</div>
        <div class="sc-value"><?php echo number_format($_total_balita, 0, ',', '.'); ?></div>
        <div class="sc-sub">usia 0–4 tahun</div>
        <div class="sc-icon"><i class="bi bi-emoji-smile-fill"></i></div>
    </a>

    <!-- Lansia -->
    <a href="<?php echo base_url('warga?filter=lansia'); ?>" class="pemilu-stat-card sc-purple" title="Filter lansia">
        <div class="sc-label"><i class="bi bi-person-walking"></i> Lansia</div>
        <div class="sc-value"><?php echo number_format($_total_lansia, 0, ',', '.'); ?></div>
        <div class="sc-sub">usia ≥60 tahun</div>
        <div class="sc-icon"><i class="bi bi-person-walking"></i></div>
    </a>

    <!-- Janda -->
    <a href="<?php echo base_url('warga?filter=janda'); ?>" class="pemilu-stat-card sc-rose" title="Filter janda">
        <div class="sc-label"><i class="bi bi-person-heart"></i> Janda</div>
        <div class="sc-value"><?php echo number_format($_total_janda, 0, ',', '.'); ?></div>
        <div class="sc-sub">cerai – perempuan</div>
        <div class="sc-icon"><i class="bi bi-person-heart"></i></div>
    </a>

    <!-- Duda -->
    <a href="<?php echo base_url('warga?filter=duda'); ?>" class="pemilu-stat-card sc-blue" title="Filter duda">
        <div class="sc-label"><i class="bi bi-person-heart"></i> Duda</div>
        <div class="sc-value"><?php echo number_format($_total_duda, 0, ',', '.'); ?></div>
        <div class="sc-sub">cerai – laki-laki</div>
        <div class="sc-icon"><i class="bi bi-person-heart"></i></div>
    </a>

    <!-- Pemilih (link ke halaman pemilih) -->
    <a href="<?php echo base_url('warga/pemilih'); ?>" class="pemilu-stat-card sc-amber" title="Lihat data pemilih">
        <div class="sc-label"><i class="bi bi-person-vcard"></i> Pemilih</div>
        <div class="sc-value">
            <?php
            /* Hitung estimasi pemilih dari $warga: usia ≥17 dan tidak meninggal */
            $_total_pemilih = 0;
            foreach($warga as $_wp) {
                if (!empty($_wp->status_meninggal) && $_wp->status_meninggal == 1) continue;
                if (!empty($_wp->tanggal_lahir)) {
                    $_u = (int)$_now->diff(new DateTime($_wp->tanggal_lahir))->y;
                    if ($_u >= 17) $_total_pemilih++;
                } elseif (!empty($_wp->status_perkawinan) && strtolower(trim($_wp->status_perkawinan)) === 'kawin') {
                    $_total_pemilih++; /* sudah menikah, berapapun umurnya */
                }
            }
            echo number_format($_total_pemilih, 0, ',', '.');
            ?>
        </div>
        <div class="sc-sub">usia ≥17 tahun</div>
        <div class="sc-icon"><i class="bi bi-person-vcard"></i></div>
    </a>

</div>

<!-- ── Banner Filter Aktif ── -->
<?php if($filter_aktif && $filter_info): ?>
<div class="filter-banner">
    <div class="filter-banner-label">
        <i class="bi bi-funnel-fill"></i>
        Filter aktif:
    </div>
    <span class="filter-banner-badge" style="background:<?php echo $filter_info['color']; ?>;">
        <i class="bi <?php echo $filter_info['icon']; ?> me-1"></i>
        <?php echo $filter_info['label']; ?>
    </span>
    <span class="filter-banner-count">
        — <?php echo number_format(count($warga)); ?> data ditemukan
    </span>
    <a href="<?php echo base_url('warga'); ?>" class="filter-banner-clear">
        <i class="bi bi-x-circle"></i> Hapus filter
    </a>
</div>
<?php endif; ?>

<!-- ── Banner Warga Meninggal ── -->
<?php if(!empty($warga_meninggal) && count($warga_meninggal) > 0 && $filter_aktif !== 'meninggal'): ?>
<div class="mb-3">
    <div style="font-size:.75rem; font-weight:700; color:#6b7280; text-transform:uppercase; letter-spacing:.04em; margin-bottom:7px;">
        <i class="bi bi-heartbreak me-1"></i>Catatan Warga Meninggal — Klik nama untuk ke detail KK
    </div>
    <div style="display:flex; flex-wrap:wrap; gap:6px;">
        <?php foreach($warga_meninggal as $wm): ?>
        <a href="<?php echo base_url('kartu-keluarga/detail/' . $wm->kk_id); ?>"
           class="bm-pill" title="Lihat KK <?php echo htmlspecialchars($wm->nama_kepala_kk ?? '-'); ?>">
            <i class="bi bi-heartbreak" style="font-size:.65rem;"></i>
            <?php echo htmlspecialchars($wm->nama_lengkap); ?>
            <?php if(!empty($wm->tanggal_meninggal)): ?>
            <span style="opacity:.65; font-weight:400;">— <?php echo date('d/m/Y', strtotime($wm->tanggal_meninggal)); ?></span>
            <?php endif; ?>
        </a>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<!-- ── 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>
            <?php if($filter_aktif && $filter_info): ?>
                Data Warga — <span style="color:<?php echo $filter_info['color']; ?>;"><?php echo $filter_info['label']; ?></span>
            <?php else: ?>
                Detail Data Warga
            <?php endif; ?>
        </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(count($warga)); ?> Orang
            </span>
            <?php if(!empty($statistik['total_meninggal']) && $statistik['total_meninggal'] > 0 && !$filter_aktif): ?>
            <a href="<?php echo base_url('warga?filter=meninggal'); ?>"
               class="badge fw-semibold text-decoration-none"
               style="background:#f3f4f6; color:#6b7280; font-size:.75rem; border:1px solid #e5e7eb;">
                <i class="bi bi-heartbreak me-1"></i><?php echo $statistik['total_meninggal']; ?> meninggal tercatat
            </a>
            <?php endif; ?>
            <?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 & Role
            </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'];
    $role_icon = ['admin'=>'bi-shield-fill-check','ketua_rt'=>'bi-person-badge-fill','sekretaris'=>'bi-journal-text','bendahara'=>'bi-cash-coin','warga'=>'bi-person-fill'];
    $role_label = ['admin'=>'Admin','ketua_rt'=>'Ketua RT','sekretaris'=>'Sekretaris','bendahara'=>'Bendahara','warga'=>'Warga'];
    $hasWarga = !empty($warga);
    $isAdmin  = ($this->session->userdata('role') === 'admin');
    ?>

    <?php if($hasWarga): ?>

    <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>
                    <th>Status</th>
                    <th>KTP</th>
                    <?php if($isAdmin): ?>
                    <th>No. HP</th>
                    <?php endif; ?>
                    <th>Username</th>
                    <th>Password</th>
                    <th>Role</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);
                $isMenuinggal = (!empty($w->status_meninggal) && $w->status_meninggal == 1);
                $role_akun    = $w->role_akun ?? 'warga';
                $user_id_akun = $w->user_id_akun ?? 0;
            ?>
            <tr style="<?php echo $isMenuinggal ? 'opacity:.55; background:#fafafa;' : ''; ?>">
                <td class="px-3"><?php echo $no++; ?></td>
                <td>
                    <!-- <code style="font-size:.78rem; color:<?php echo $isMenuinggal ? '#9ca3af' : '#e11d48'; ?>;"><?php echo htmlspecialchars($w->nik ?? '-'); ?></code> -->
                    <!-- Start hidden nik masking xxxx -->
                    <code style="font-size:.78rem; color:<?php echo $isMenuinggal ? '#9ca3af' : '#e11d48'; ?>;"><?php echo htmlspecialchars(maskId($w->nik ?? '')); ?>
                         <!-- End hidden nik masking xxx -->
                </td>
                <td>
                    <strong style="font-size:.83rem; <?php echo $isMenuinggal ? 'text-decoration:line-through; color:#9ca3af;' : ''; ?>">
                        <?php echo htmlspecialchars($w->nama_lengkap ?? '-'); ?>
                    </strong>
                    <?php if($isMenuinggal): ?>
                    <br><small style="color:#ef4444; font-size:.7rem;"><i class="bi bi-heartbreak me-1"></i>Meninggal<?php echo !empty($w->tanggal_meninggal) ? ' '.date('d/m/Y',strtotime($w->tanggal_meninggal)) : ''; ?></small>
                    <?php else: ?>
                    <br><small class="text-muted"><?php echo ($w->jenis_kelamin ?? '') == 'L' ? 'Laki-laki' : 'Perempuan'; ?></small>
                    <?php endif; ?>
                </td>
                <!-- <td>
                    <?php if(!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> -->
 <!-- Start hidden nik masking xxxx -->
                <td>
    <?php if(!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(maskId($w->no_kk ?? '')); ?>
        </a>
    <?php else: ?>
        <span class="text-muted">-</span>
    <?php endif; ?>
</td>
  <!-- End hidden nik masking xxx -->
                <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>
                <td>
                    <?php if($isMenuinggal): ?>
                    <span style="display:inline-flex;align-items:center;gap:4px;padding:3px 9px;border-radius:999px;font-size:.72rem;font-weight:600;background:#f3f4f6;border:1px solid #d1d5db;color:#6b7280;">
                        <i class="bi bi-heartbreak"></i>Meninggal
                    </span>
                    <?php else: ?>
                    <span style="display:inline-flex;align-items:center;gap:4px;padding:3px 9px;border-radius:999px;font-size:.72rem;font-weight:600;background:#dcfce7;border:1px solid #bbf7d0;color:#166534;">
                        <i class="bi bi-check-circle"></i>Aktif
                    </span>
                    <?php endif; ?>
                </td>
                <td>
                    <?php if(!empty($w->foto_ktp)): ?>
                        <span class="badge bg-success" style="font-size:.7rem;" title="KTP Tersedia"><i class="bi bi-person-vcard me-1"></i>Ada</span>
                    <?php else: ?>
                        <span class="badge bg-danger" style="font-size:.7rem;" title="KTP Belum Diupload"><i class="bi bi-x-circle me-1"></i>Belum</span>
                    <?php endif; ?>
                </td>
                <?php if($isAdmin): ?>
                <td>
                    <?php if(!empty($w->no_hp)): ?>
                        <a href="tel:<?php echo htmlspecialchars($w->no_hp); ?>" class="nohp-link">
                            <i class="bi bi-telephone-fill" style="font-size:.75rem;"></i>
                            <?php echo htmlspecialchars($w->no_hp); ?>
                        </a>
                    <?php else: ?>
                        <span class="nohp-empty">—</span>
                    <?php endif; ?>
                </td>
                <?php endif; ?>
                <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 mb-1">
                            <i class="bi bi-person-x"></i> Belum punya
                        </span>
                        <?php if($isAdmin && !empty($w->nik)): ?>
                        <button type="button" class="btn btn-sm btn-outline-primary d-block mt-1 py-0 px-2" style="font-size:.7rem;" onclick="bukaModalBuatAkun(<?php echo $w->id; ?>, '<?php echo addslashes(htmlspecialchars($w->nama_lengkap ?? '-')); ?>', '<?php echo htmlspecialchars($w->nik); ?>')">Buat Akun</button>
                        <?php endif; ?>
                    <?php endif; ?>
                </td>
                <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 if($isAdmin && $user_id_akun): ?>
                        <button type="button" class="btn btn-sm btn-outline-warning d-block mt-1 py-0 px-2" style="font-size:.7rem;" onclick="bukaModalResetPassword(<?php echo $user_id_akun; ?>, '<?php echo htmlspecialchars($w->username); ?>', '<?php echo htmlspecialchars($w->nik); ?>')">Reset Password</button>
                        <?php endif; ?>
                    <?php else: ?>
                        <span class="text-muted">—</span>
                    <?php endif; ?>
                </td>
                <td>
                    <?php if($punya_akun && $user_id_akun): ?>
                        <div class="d-flex align-items-center gap-1 flex-wrap" id="role-wrap-<?php echo $user_id_akun; ?>">
                            <span class="role-badge <?php echo htmlspecialchars($role_akun); ?>" id="role-badge-<?php echo $user_id_akun; ?>">
                                <i class="bi <?php echo $role_icon[$role_akun] ?? 'bi-person-fill'; ?>"></i>
                                <?php echo $role_label[$role_akun] ?? ucfirst($role_akun); ?>
                            </span>
                            <button type="button"
                                    class="btn-ubah-role"
                                    title="Ubah Role"
                                    onclick="bukaModalUbahRole(
                                        <?php echo $user_id_akun; ?>,
                                        '<?php echo htmlspecialchars($w->username); ?>',
                                        '<?php echo htmlspecialchars($w->nama_lengkap ?? '-'); ?>',
                                        '<?php echo htmlspecialchars($role_akun); ?>'
                                    )">
                                <i class="bi bi-pencil-square"></i> Ubah
                            </button>
                        </div>
                    <?php else: ?>
                        <span class="text-muted" style="font-size:.75rem;">—</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);
            $isMenuinggal = (!empty($w->status_meninggal) && $w->status_meninggal == 1);
            $role_akun    = $w->role_akun ?? 'warga';
            $user_id_akun = $w->user_id_akun ?? 0;
        ?>
        <div style="border-radius:10px; border:1.5px solid <?php echo $isMenuinggal ? '#e5e7eb' : '#f1f3f5'; ?>; border-left:4px solid <?php echo $isMenuinggal ? '#9ca3af' : $bc; ?>; background:<?php echo $isMenuinggal ? '#f9fafb' : '#fff'; ?>; padding:11px 13px; opacity:<?php echo $isMenuinggal ? '0.6' : '1'; ?>;">
            <div class="d-flex justify-content-between align-items-start mb-1">
                <div>
                    <div class="fw-semibold <?php echo $isMenuinggal ? 'text-decoration-line-through text-muted' : ''; ?>" 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>
                <div class="d-flex flex-column gap-1 align-items-end">
                    <span class="badge bg-<?php echo $badge; ?> flex-shrink-0 ms-2" style="font-size:.72rem;"><?php echo ucfirst($dom); ?></span>
                    <?php if($isMenuinggal): ?>
                    <span style="font-size:.68rem;font-weight:600;color:#ef4444;"><i class="bi bi-heartbreak me-1"></i>Meninggal</span>
                    <?php endif; ?>
                </div>
            </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->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>
            <?php if($isMenuinggal && !empty($w->tanggal_meninggal)): ?>
            <div style="font-size:.73rem; color:#ef4444; margin-top:5px;">
                <i class="bi bi-heartbreak me-1"></i>Meninggal <?php echo date('d/m/Y', strtotime($w->tanggal_meninggal)); ?>
                <?php if(!empty($w->keterangan_meninggal)): ?> — <?php echo htmlspecialchars($w->keterangan_meninggal); ?><?php endif; ?>
            </div>
            <?php endif; ?>
            <?php if($isAdmin): ?>
            <div class="info-akun-mobile mt-2" style="display:none; border-top:1px solid #f3f4f6; padding-top:8px;">
                <?php if(!empty($w->no_hp)): ?>
                <div style="font-size:.75rem; color:#374151; margin-bottom:6px;">
                    <i class="bi bi-telephone-fill me-1" style="color:#0d9488;"></i>
                    <strong>No. HP:</strong>
                    <a href="tel:<?php echo htmlspecialchars($w->no_hp); ?>" class="nohp-link ms-1">
                        <?php echo htmlspecialchars($w->no_hp); ?>
                    </a>
                </div>
                <?php else: ?>
                <div style="font-size:.75rem; color:#9ca3af; margin-bottom:6px;">
                    <i class="bi bi-telephone me-1"></i>
                    <strong>No. HP:</strong> <span style="font-style:italic;">Belum diisi</span>
                </div>
                <?php endif; ?>
                <?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; margin-bottom:5px; display:flex; align-items:center; flex-wrap:wrap; gap:4px;">
                    <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>
                    <?php if($user_id_akun): ?>
                    <button type="button" class="btn btn-sm btn-outline-warning py-0 px-2" style="font-size:.7rem;" onclick="bukaModalResetPassword(<?php echo $user_id_akun; ?>, '<?php echo htmlspecialchars($w->username); ?>', '<?php echo htmlspecialchars($w->nik); ?>')">Reset</button>
                    <?php endif; ?>
                </div>
                <div style="display:flex; align-items:center; gap:6px; flex-wrap:wrap;">
                    <span class="role-badge <?php echo htmlspecialchars($role_akun); ?>" id="role-badge-mob-<?php echo $user_id_akun; ?>">
                        <i class="bi <?php echo $role_icon[$role_akun] ?? 'bi-person-fill'; ?>"></i>
                        <?php echo $role_label[$role_akun] ?? ucfirst($role_akun); ?>
                    </span>
                    <?php if($user_id_akun): ?>
                    <button type="button"
                            class="btn-ubah-role"
                            onclick="bukaModalUbahRole(
                                <?php echo $user_id_akun; ?>,
                                '<?php echo htmlspecialchars($w->username); ?>',
                                '<?php echo htmlspecialchars($w->nama_lengkap ?? '-'); ?>',
                                '<?php echo htmlspecialchars($role_akun); ?>'
                            )">
                        <i class="bi bi-pencil-square"></i> Ubah Role
                    </button>
                    <?php endif; ?>
                </div>
                <?php else: ?>
                <div style="font-size:.75rem; color:#9ca3af; display:flex; align-items:center; gap:8px;">
                    <div><i class="bi bi-person-x me-1"></i>Belum memiliki akun</div>
                    <?php if(!empty($w->nik)): ?>
                    <button type="button" class="btn btn-sm btn-outline-primary py-0 px-2" style="font-size:.7rem;" onclick="bukaModalBuatAkun(<?php echo $w->id; ?>, '<?php echo addslashes(htmlspecialchars($w->nama_lengkap ?? '-')); ?>', '<?php echo htmlspecialchars($w->nik); ?>')">Buat Akun</button>
                    <?php endif; ?>
                </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>
        <?php if($filter_aktif && $filter_info): ?>
        <div class="fw-semibold mb-1">Tidak ada data untuk filter <strong><?php echo $filter_info['label']; ?></strong></div>
        <a href="<?php echo base_url('warga'); ?>" class="btn btn-outline-secondary btn-sm mt-2">
            <i class="bi bi-x-circle me-1"></i>Hapus filter
        </a>
        <?php else: ?>
        <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>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<!-- ── Toast Container ── -->
<div id="toastRoleWrap"></div>


<?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, No. HP & role 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>

<!-- ===== MODAL UBAH ROLE ===== -->
<div class="modal fade modal-ubah-role" id="modalUbahRole" tabindex="-1"
     data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog modal-dialog-centered" style="max-width:400px;">
        <div class="modal-content">
            <div class="modal-header">
                <div>
                    <h6 class="modal-title text-white fw-bold mb-0">
                        <i class="bi bi-person-gear me-2"></i>Ubah Role Akun
                    </h6>
                    <div style="font-size:.73rem; color:rgba(255,255,255,.8); margin-top:2px;" id="modalRoleSubtitle">
                        Pilih role baru untuk akun ini
                    </div>
                </div>
                <button type="button" class="btn-close btn-close-white ms-3" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div style="background:#f8fafc; border:1px solid #e2e8f0; border-radius:10px; padding:12px 14px; margin-bottom:16px;">
                    <div style="font-size:.75rem; color:#94a3b8; font-weight:600; margin-bottom:4px;">AKUN WARGA</div>
                    <div style="font-size:.88rem; font-weight:700; color:#0f172a;" id="modalRoleNama">—</div>
                    <div style="font-size:.78rem; color:#64748b;" id="modalRoleUsername">—</div>
                    <div style="margin-top:8px; display:flex; align-items:center; gap:6px;">
                        <span style="font-size:.74rem; color:#94a3b8;">Role saat ini:</span>
                        <span class="role-badge warga" id="modalRoleCurrent">—</span>
                    </div>
                </div>
                <div style="font-size:.78rem; font-weight:700; color:#374151; margin-bottom:6px;">
                    <i class="bi bi-arrow-right-circle me-1" style="color:#0d9488;"></i>Pilih Role Baru
                </div>
                <div class="role-radio-group" id="roleRadioGroup">
                    <input type="radio" name="pilih_role" id="role_admin"      value="admin">
                    <label for="role_admin"><i class="bi bi-shield-fill-check" style="color:#d97706;"></i> Admin</label>

                    <input type="radio" name="pilih_role" id="role_ketua_rt"   value="ketua_rt">
                    <label for="role_ketua_rt"><i class="bi bi-person-badge-fill" style="color:#1d4ed8;"></i> Ketua RT</label>

                    <input type="radio" name="pilih_role" id="role_sekretaris" value="sekretaris">
                    <label for="role_sekretaris"><i class="bi bi-journal-text" style="color:#7c3aed;"></i> Sekretaris</label>

                    <input type="radio" name="pilih_role" id="role_bendahara"  value="bendahara">
                    <label for="role_bendahara"><i class="bi bi-cash-coin" style="color:#059669;"></i> Bendahara</label>

                    <input type="radio" name="pilih_role" id="role_warga"      value="warga">
                    <label for="role_warga"><i class="bi bi-person-fill" style="color:#6b7280;"></i> Warga</label>
                </div>
                <div id="pesanErrorRole" style="font-size:.78rem; color:#ef4444; font-weight:600; margin-top:10px; min-height:18px;"></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="btnSimpanRole"
                    style="background:#1e40af;color:#fff;border:none;border-radius:8px;padding:7px 20px;font-size:.82rem;">
                    <i class="bi bi-check2-circle me-1"></i>Simpan Role
                </button>
            </div>
        </div>
    </div>
</div>

<!-- ===== MODAL BUAT AKUN ===== -->
<div class="modal fade" id="modalBuatAkun" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered" style="max-width:400px;">
        <div class="modal-content" style="border-radius: 16px; border: none; box-shadow: 0 8px 40px rgba(0,0,0,.18); overflow: hidden;">
            <div class="modal-header" style="background: linear-gradient(135deg, #0d9488, #14b8a6); border: none; padding: 16px 20px;">
                <h6 class="modal-title text-white fw-bold"><i class="bi bi-person-plus me-2"></i>Buat Akun Warga</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" style="padding: 20px;">
                <div style="font-size: .85rem; color: #374151; margin-bottom: 12px;">
                    Anda akan membuat akun untuk warga berikut:
                </div>
                <div style="background: #f0fdfa; border: 1.5px solid #99f6e4; border-radius: 10px; padding: 12px; margin-bottom: 16px;">
                    <div style="font-weight: 700; color: #0b5a52; font-size: .95rem;" id="baNamaLengkap">—</div>
                    <div style="font-family: monospace; color: #0d9488; font-size: .8rem; margin-top: 4px;" id="baNik">—</div>
                </div>
                <div style="font-size: .8rem; color: #4b5563;">
                    <i class="bi bi-info-circle text-info me-1"></i> Username dan Password akan menggunakan <strong>NIK</strong> tersebut.
                </div>
                <div id="pesanErrorBA" style="font-size:.78rem; color:#ef4444; font-weight:600; margin-top:10px; min-height:18px;"></div>
            </div>
            <div class="modal-footer justify-content-between" style="border-top: 1px solid #f1f3f5; padding: 12px 20px;">
                <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal" style="border-radius:8px;">Batal</button>
                <button type="button" class="btn btn-sm fw-bold" id="btnSubmitBuatAkun" style="background:#0d9488; color:#fff; border-radius:8px; padding:7px 20px;">
                    <i class="bi bi-check-lg me-1"></i>Buat Akun
                </button>
            </div>
        </div>
    </div>
</div>

<!-- ===== MODAL RESET PASSWORD ===== -->
<div class="modal fade" id="modalResetPassword" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered" style="max-width:400px;">
        <div class="modal-content" style="border-radius: 16px; border: none; box-shadow: 0 8px 40px rgba(0,0,0,.18); overflow: hidden;">
            <div class="modal-header" style="background: linear-gradient(135deg, #f59e0b, #d97706); border: none; padding: 16px 20px;">
                <h6 class="modal-title text-white fw-bold"><i class="bi bi-key me-2"></i>Reset Password</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" style="padding: 20px;">
                <div style="font-size: .85rem; color: #374151; margin-bottom: 12px;">
                    Apakah Anda yakin ingin mereset password akun ini?
                </div>
                <div style="background: #fffbeb; border: 1.5px solid #fde68a; border-radius: 10px; padding: 12px; margin-bottom: 16px;">
                    <div style="font-weight: 700; color: #92400e; font-size: .95rem;"><i class="bi bi-person me-1"></i> <span id="rpUsername">—</span></div>
                    <div style="font-family: monospace; color: #d97706; font-size: .8rem; margin-top: 4px;"><i class="bi bi-credit-card-2-front me-1"></i> NIK: <span id="rpNik">—</span></div>
                </div>
                <div style="font-size: .8rem; color: #b45309;">
                    <i class="bi bi-exclamation-triangle-fill me-1"></i> Password akan dikembalikan ke default sesuai dengan <strong>NIK</strong>.
                </div>
                <div id="pesanErrorRP" style="font-size:.78rem; color:#ef4444; font-weight:600; margin-top:10px; min-height:18px;"></div>
            </div>
            <div class="modal-footer justify-content-between" style="border-top: 1px solid #f1f3f5; padding: 12px 20px;">
                <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal" style="border-radius:8px;">Batal</button>
                <button type="button" class="btn btn-sm fw-bold" id="btnSubmitResetPassword" style="background:#d97706; color:#fff; border-radius:8px; padding:7px 20px;">
                    <i class="bi bi-arrow-clockwise me-1"></i>Reset Password
                </button>
            </div>
        </div>
    </div>
</div>

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

    dtTable = $('#tabelWarga').DataTable({
        responsive  : true,
        pageLength  : 10,
        order       : [[2, 'asc']],
        columnDefs  : [
            { orderable: false, targets: [0, 6, 7, 8, 9, 10<?php echo $isAdmin ? ', 11' : ''; ?>] },
            { visible: false, targets: [8, 9, 10<?php echo $isAdmin ? ', 11' : ''; ?>] }
        ],
        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' }
        }
    });

    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 });
    });

    $(modalEl).on('show.bs.modal', function () {
        if (sudahUnlock) {
            bootstrap.Modal.getInstance(modalEl).hide();
            sembunyikanAkun();
            return;
        }
        resetInput();
        setTimeout(function(){ if (digits[0]) digits[0].focus(); }, 420);
    });

    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);
        }
    });

    function tampilkanAkun() {
        dtTable.columns([8, 9, 10<?php echo $isAdmin ? ', 11' : ''; ?>]).visible(true);
        document.querySelectorAll('.info-akun-mobile').forEach(function(el){ el.style.display = 'block'; });
        if (btnLihat) {
            btnLihat.classList.add('aktif');
            btnLihat.innerHTML = '<i class="bi bi-shield-check"></i> Sembunyikan Akun & HP';
            btnLihat.removeAttribute('data-bs-toggle');
            btnLihat.removeAttribute('data-bs-target');
            btnLihat.addEventListener('click', sembunyikanAkun, { once: true });
        }
    }

    function sembunyikanAkun() {
        sudahUnlock = false;
        dtTable.columns([8, 9, 10<?php echo $isAdmin ? ', 11' : ''; ?>]).visible(false);
        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 & Role';
            btnLihat.setAttribute('data-bs-toggle', 'modal');
            btnLihat.setAttribute('data-bs-target', '#modalKodeRahasia');
        }
    }

    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);
    }

    document.getElementById('btnSimpanRole').addEventListener('click', function () {
        var userId   = parseInt(this.dataset.userId || 0);
        var roleBaru = document.querySelector('input[name="pilih_role"]:checked');

        if (!userId) {
            document.getElementById('pesanErrorRole').textContent = 'User ID tidak valid.'; return;
        }
        if (!roleBaru) {
            document.getElementById('pesanErrorRole').textContent = 'Pilih role terlebih dahulu.'; return;
        }

        var btnThis = this;
        btnThis.disabled = true;
        btnThis.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Menyimpan...';

        $.ajax({
            url     : '<?php echo base_url("warga/ubah_role"); ?>',
            method  : 'POST',
            data    : { user_id: userId, role_baru: roleBaru.value },
            dataType: 'json',
            success : function (res) {
                btnThis.disabled = false;
                btnThis.innerHTML = '<i class="bi bi-check2-circle me-1"></i>Simpan Role';

                if (res.status === 'ok') {
                    bootstrap.Modal.getInstance(document.getElementById('modalUbahRole')).hide();

                    var badge    = document.getElementById('role-badge-' + userId);
                    var badgeMob = document.getElementById('role-badge-mob-' + userId);
                    var roleMap  = {
                        admin:      { label: 'Admin',      icon: 'bi-shield-fill-check' },
                        ketua_rt:   { label: 'Ketua RT',   icon: 'bi-person-badge-fill' },
                        sekretaris: { label: 'Sekretaris', icon: 'bi-journal-text'      },
                        bendahara:  { label: 'Bendahara',  icon: 'bi-cash-coin'         },
                        warga:      { label: 'Warga',      icon: 'bi-person-fill'       }
                    };
                    var info = roleMap[res.role_baru] || { label: res.role_baru, icon: 'bi-person-fill' };
                    var html = '<i class="bi ' + info.icon + '"></i> ' + info.label;

                    if (badge) {
                        badge.className = 'role-badge ' + res.role_baru;
                        badge.innerHTML = html;
                        var btnUbah = badge.parentElement && badge.parentElement.querySelector('.btn-ubah-role');
                        if (btnUbah) {
                            var oldOnclick = btnUbah.getAttribute('onclick');
                            btnUbah.setAttribute('onclick',
                                oldOnclick.replace(/,\s*'[^']*'\s*\)/, ", '" + res.role_baru + "')"));
                        }
                    }
                    if (badgeMob) {
                        badgeMob.className = 'role-badge ' + res.role_baru;
                        badgeMob.innerHTML = html;
                    }
                    tampilToast('<i class="bi bi-check-circle-fill" style="color:#0d9488;font-size:1rem;"></i> ' + res.msg, false);
                } else {
                    document.getElementById('pesanErrorRole').textContent = res.msg || 'Gagal menyimpan.';
                    tampilToast('<i class="bi bi-x-circle-fill" style="color:#ef4444;font-size:1rem;"></i> ' + (res.msg || 'Gagal'), true);
                }
            },
            error: function () {
                btnThis.disabled = false;
                btnThis.innerHTML = '<i class="bi bi-check2-circle me-1"></i>Simpan Role';
                document.getElementById('pesanErrorRole').textContent = 'Gagal terhubung ke server.';
            }
        });
    });

    window.tampilToast = function(html, isError) {
        var wrap  = document.getElementById('toastRoleWrap');
        var toast = document.createElement('div');
        toast.className = 'toast-role' + (isError ? ' error' : '');
        toast.innerHTML = html;
        wrap.appendChild(toast);
        setTimeout(function(){ toast.style.opacity = '0'; toast.style.transition = 'opacity .4s'; }, 3200);
        setTimeout(function(){ if (toast.parentNode) toast.parentNode.removeChild(toast); }, 3700);
    };

    document.getElementById('btnSubmitBuatAkun').addEventListener('click', function() {
        var wargaId = this.dataset.wargaId;
        var btnThis = this;

        btnThis.disabled = true;
        btnThis.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Memproses...';
        document.getElementById('pesanErrorBA').textContent = '';

        $.ajax({
            url: '<?php echo base_url("warga/buat_akun"); ?>',
            method: 'POST',
            data: { warga_id: wargaId },
            dataType: 'json',
            success: function(res) {
                btnThis.disabled = false;
                btnThis.innerHTML = '<i class="bi bi-check-lg me-1"></i>Buat Akun';

                if (res.status === 'ok') {
                    bootstrap.Modal.getInstance(document.getElementById('modalBuatAkun')).hide();
                    tampilToast('<i class="bi bi-check-circle-fill" style="color:#0d9488;font-size:1rem;"></i> ' + res.msg, false);
                    setTimeout(function() { window.location.reload(); }, 1500);
                } else {
                    document.getElementById('pesanErrorBA').textContent = res.msg || 'Gagal membuat akun.';
                }
            },
            error: function() {
                btnThis.disabled = false;
                btnThis.innerHTML = '<i class="bi bi-check-lg me-1"></i>Buat Akun';
                document.getElementById('pesanErrorBA').textContent = 'Gagal terhubung ke server.';
            }
        });
    });

    document.getElementById('btnSubmitResetPassword').addEventListener('click', function() {
        var userId = this.dataset.userId;
        var nik = this.dataset.nik;
        var btnThis = this;

        btnThis.disabled = true;
        btnThis.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Memproses...';
        document.getElementById('pesanErrorRP').textContent = '';

        $.ajax({
            url: '<?php echo base_url("warga/reset_password"); ?>',
            method: 'POST',
            data: { user_id: userId, nik: nik },
            dataType: 'json',
            success: function(res) {
                btnThis.disabled = false;
                btnThis.innerHTML = '<i class="bi bi-arrow-clockwise me-1"></i>Reset Password';

                if (res.status === 'ok') {
                    bootstrap.Modal.getInstance(document.getElementById('modalResetPassword')).hide();
                    tampilToast('<i class="bi bi-check-circle-fill" style="color:#0d9488;font-size:1rem;"></i> ' + res.msg, false);
                } else {
                    document.getElementById('pesanErrorRP').textContent = res.msg || 'Gagal mereset password.';
                }
            },
            error: function() {
                btnThis.disabled = false;
                btnThis.innerHTML = '<i class="bi bi-arrow-clockwise me-1"></i>Reset Password';
                document.getElementById('pesanErrorRP').textContent = 'Gagal terhubung ke server.';
            }
        });
    });
});

function bukaModalBuatAkun(wargaId, namaLengkap, nik) {
    document.getElementById('baNamaLengkap').textContent = namaLengkap;
    document.getElementById('baNik').textContent = 'NIK: ' + nik;
    document.getElementById('pesanErrorBA').textContent = '';
    document.getElementById('btnSubmitBuatAkun').dataset.wargaId = wargaId;
    new bootstrap.Modal(document.getElementById('modalBuatAkun')).show();
}

function bukaModalResetPassword(userId, username, nik) {
    document.getElementById('rpUsername').textContent = '@' + username;
    document.getElementById('rpNik').textContent = nik;
    document.getElementById('pesanErrorRP').textContent = '';
    document.getElementById('btnSubmitResetPassword').dataset.userId = userId;
    document.getElementById('btnSubmitResetPassword').dataset.nik = nik;
    new bootstrap.Modal(document.getElementById('modalResetPassword')).show();
}

function bukaModalUbahRole(userId, username, namaLengkap, roleSekarang) {
    var roleLabel = { admin:'Admin', ketua_rt:'Ketua RT', sekretaris:'Sekretaris', bendahara:'Bendahara', warga:'Warga' };
    var roleIcon  = { admin:'bi-shield-fill-check', ketua_rt:'bi-person-badge-fill', sekretaris:'bi-journal-text', bendahara:'bi-cash-coin', warga:'bi-person-fill' };

    document.getElementById('modalRoleNama').textContent     = namaLengkap;
    document.getElementById('modalRoleUsername').textContent = '@' + username;
    document.getElementById('modalRoleSubtitle').textContent = 'Pilih role baru untuk: ' + username;

    var badgeEl = document.getElementById('modalRoleCurrent');
    badgeEl.className = 'role-badge ' + roleSekarang;
    badgeEl.innerHTML = '<i class="bi ' + (roleIcon[roleSekarang] || 'bi-person-fill') + '"></i> ' + (roleLabel[roleSekarang] || roleSekarang);

    document.querySelectorAll('input[name="pilih_role"]').forEach(function(r){ r.checked = (r.value === roleSekarang); });
    document.getElementById('btnSimpanRole').dataset.userId = userId;
    document.getElementById('pesanErrorRole').textContent   = '';

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

// ── Kirim Ucapan Ulang Tahun via WAHA ────────────────────────────
(function() {
    var btn = document.getElementById('btnKirimUltah');
    if (!btn) return;

    btn.addEventListener('click', function() {
        var self = this;

        GlobalModal.confirm({
            title: 'Konfirmasi Broadcast',
            message: 'Kirim ucapan selamat ulang tahun ke <strong>semua warga</strong> yang berulang tahun HARI INI via WhatsApp (WAHA)?',
            confirmText: 'Ya, Kirim Sekarang',
            onConfirm: function() {
                self.disabled = true;
                var origHtml = self.innerHTML;
                self.innerHTML = '<i class="bi bi-hourglass-split"></i> Mengirim...';

                fetch('<?php echo base_url("warga/kirim_ucapan_ultah"); ?>', {
                    method: 'POST',
                    headers: { 'X-Requested-With': 'XMLHttpRequest' },
                })
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    var tipe = (data.kirim > 0 || data.status === 'ok') ? 'success' : 'warning';
                    var icon = tipe === 'success' ? 'bi-balloon-heart-fill' : 'bi-exclamation-triangle-fill';

                    // Toast notifikasi
                    var div = document.createElement('div');
                    div.className = 'alert alert-' + tipe + ' alert-dismissible fade show';
                    div.style.cssText = 'position:fixed;top:20px;right:20px;z-index:9999;min-width:300px;border-radius:12px;font-size:.85rem;box-shadow:0 4px 20px rgba(0,0,0,.15);';
                    div.innerHTML = '<i class="bi ' + icon + ' me-2"></i>' + (data.msg || 'Selesai') +
                        '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';

                    // Detail error jika ada
                    if (data.errors && data.errors.length > 0) {
                        var ul = '<ul class="mt-2 mb-0 small" style="padding-left:16px;">';
                        data.errors.forEach(function(e) { ul += '<li>' + e + '</li>'; });
                        ul += '</ul>';
                        div.innerHTML += ul;
                    }

                    document.body.appendChild(div);
                    setTimeout(function() {
                        div.classList.remove('show');
                        setTimeout(function() { div.remove(); }, 400);
                    }, 6000);
                })
                .catch(function(e) {
                    GlobalModal.alert({ title: 'Terjadi Kesalahan', message: e.message, type: 'danger' });
                })
                .finally(function() {
                    self.disabled = false;
                    self.innerHTML = origHtml;
                });
            }
        });
    });

})();
</script>
<?php endif; ?>
