<style>
/* ===== RESET FOCUS ===== */
.btn:focus, .form-control:focus, .form-select:focus { box-shadow: none; }
.form-control:focus, .form-select:focus { border-color: #20c997; box-shadow: 0 0 0 3px rgba(32,201,151,.12); }
.form-control, .form-select { border-radius: 8px; border: 1.5px solid #e5e7eb; font-size: .88rem; padding: 9px 12px; }

/* ===== STATUS BADGES ===== */
.status-badge {
    display: inline-flex; align-items: center; gap: 4px;
    padding: 4px 10px; border-radius: 999px;
    font-size: .75rem; font-weight: 600; white-space: nowrap;
}
.sb-lunas      { background:#dcfce7; color:#166534; border:1px solid #bbf7d0; }
.sb-cicil      { background:#ede9fe; color:#5b21b6; border:1px solid #c4b5fd; }
.sb-verifikasi { background:#fef9c3; color:#854d0e; border:1px solid #fde68a; }
.sb-pending    { background:#fee2e2; color:#991b1b; border:1px solid #fecaca; }
.sb-other      { background:#f3f4f6; color:#6b7280; border:1px solid #e5e7eb; }

/* ===== STAT CARDS ===== */
.stat-card { border-radius:12px; border:none; box-shadow:0 1px 4px rgba(0,0,0,.08); }

/* ===== SECTION / TABLE CARD ===== */
.section-card { border-radius:14px; border:none; box-shadow:0 1px 6px rgba(0,0,0,.07); overflow:hidden; margin-bottom:20px; }
.section-card-header {
    padding:13px 20px; display:flex; align-items:center; justify-content:space-between;
    border-bottom:1px solid #f1f3f5; background:#fff;
}
.section-card-header .title { font-size:.85rem; font-weight:700; color:#374151; display:flex; align-items:center; gap:6px; }
.section-card-header .title i { color:#20c997; }

/* ===== TABLES ===== */
.iuran-table th {
    font-size:.75rem; text-transform:uppercase; letter-spacing:.04em;
    color:#6b7280; font-weight:700; padding:10px 16px;
    background:#f8fffe; border-bottom:1.5px solid #e5e7eb;
    white-space:nowrap;
}
.iuran-table td { padding:10px 16px; vertical-align:middle; font-size:.85rem; border-bottom:1px solid #f3f4f6; }
.iuran-table tbody tr:last-child td { border-bottom:none; }
.iuran-table tbody tr:hover { background:#f8fffe; }

/* Verifikasi table highlight */
.row-verif td { background:#fffbeb !important; }
.row-verif:hover td { background:#fef3c7 !important; }

/* Cicil row highlight */
.row-cicil td { background:#faf5ff !important; }
.row-cicil:hover td { background:#f3e8ff !important; }

/* ===== FILTER CARD ===== */
.filter-card { border-radius:12px; border:1.5px solid #e5e7eb; box-shadow:none; margin-bottom:20px; }
.filter-card .card-body { padding:16px 20px; }

/* ===== ALERT VERIF ===== */
.verif-alert {
    background:#fffbeb; border:1.5px solid #fde68a; border-radius:12px;
    padding:13px 18px; margin-bottom:16px;
    display:flex; align-items:center; justify-content:space-between; gap:12px;
}
.verif-alert .va-text { font-size:.85rem; font-weight:600; color:#92400e; }
.btn-verif-now { background:#f59e0b; border:none; color:#fff; border-radius:8px; padding:6px 14px; font-size:.8rem; font-weight:700; white-space:nowrap; }
.btn-verif-now:hover { background:#d97706; color:#fff; }

/* ===== ACTION BUTTONS in table ===== */
.btn-act { font-size:.78rem; padding:5px 10px; border-radius:7px; font-weight:600; white-space:nowrap; display:inline-flex; align-items:center; gap:4px; }

/* ===== PROGRESS CICIL ===== */
.cicil-progress-wrap { margin-top:5px; }
.cicil-bar-bg { background:#e9d5ff; border-radius:999px; height:5px; overflow:hidden; }
.cicil-bar-fill { background:linear-gradient(90deg,#7c3aed,#a855f7); height:5px; border-radius:999px; }
.cicil-info { display:flex; justify-content:space-between; font-size:.69rem; margin-top:3px; }
.cicil-info .ci-bayar { color:#7c3aed; font-weight:700; }
.cicil-info .ci-sisa  { color:#dc2626; font-weight:700; }

/* ===== DESKTOP: tabel tampil, card list sembunyi ===== */
.desktop-table   { display: block; }
.mobile-iuran-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: 20px;
}
.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; cursor: pointer;
}
.btn-tambah:hover { background: #0b7a6e; box-shadow: 0 5px 16px rgba(13,148,136,0.38); transform: translateY(-1px); color: #fff; }
.btn-tambah-outline {
  display: inline-flex; align-items: center; gap: 7px;
  padding: 10px 24px; border-radius: 50px; border: 2px solid #0d9488;
  background: transparent; color: #0d9488; font-size: 0.85rem; font-weight: 700;
  text-decoration: none; transition: all .2s; white-space: nowrap; cursor: pointer;
}
.btn-tambah-outline:hover { background: #0d9488; color: #fff; transform: translateY(-1px); }

/* ===== MOBILE ===== */
@media (max-width: 767.98px) {
    .container-fluid { padding-left:12px !important; padding-right:12px !important; }
    .ar-page-header { flex-direction: column; align-items: flex-start; }
    .iuran-header-buttons {
        display: grid !important; grid-template-columns: 1fr 1fr; gap: 8px; width: 100%;
    }
    .iuran-header-buttons .btn-tambah-outline,
    .iuran-header-buttons .btn-tambah { width: 100%; justify-content: center; }
    .iuran-header-buttons .btn-tambah:last-child { grid-column: 1 / -1; }
    .stat-row > [class*='col-'] { flex:0 0 50% !important; max-width:50% !important; }
    .stat-card .card-body { padding:10px 12px !important; }
    .filter-row > [class*='col-'] { flex:0 0 100% !important; max-width:100% !important; }
    .filter-row .col-btn { flex:0 0 100% !important; max-width:100% !important; }
    .filter-row .col-btn .btn { width:100%; }
    .desktop-table     { display: none !important; }
    .mobile-iuran-list { display: flex !important; flex-direction: column; gap: 10px; padding: 12px; }
    .verif-alert { flex-direction:column; align-items:flex-start; }
    .btn-verif-now { width:100%; text-align:center; }
}
</style>

<!-- ===== PAGE HEADER ===== -->
<div class="ar-page-header">
    <div class="ar-header-left">
        <h4>
            <span class="hi"><i class="bi bi-cash-coin"></i></span>
            <?php echo is_warga() ? 'Iuran Saya' : 'Iuran Warga'; ?>
        </h4>
        <div class="ar-breadcrumb">
            <a href="<?php echo base_url('dashboard'); ?>">Dashboard</a>
            <span class="sep">/</span>
            <span><?php echo is_warga() ? 'Iuran Saya' : 'Iuran Warga'; ?></span>
        </div>
    </div>

    <?php if(is_admin()): ?>
    <div class="iuran-header-buttons" style="display:flex; gap:8px; flex-wrap:wrap;">
        <a href="<?php echo base_url('jenis_iuran'); ?>" class="btn-tambah-outline"><i class="bi bi-tags"></i> Jenis Iuran</a>
        <a href="<?php echo base_url('iuran/bayar_massal'); ?>" class="btn-tambah-outline"><i class="bi bi-cash-stack"></i> Bayar Massal</a>
        <a href="<?php echo base_url('iuran/generate_tagihan'); ?>" class="btn-tambah-outline"><i class="bi bi-arrow-repeat"></i> Generate Tagihan</a>
       <a href="<?php echo base_url('iuran/statistik'); ?>" class="btn-tambah-outline">
    <i class="bi bi-bar-chart-line"></i> Statistik
</a>
        <a href="<?php echo base_url('export/index/iuran/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/iuran/pdf'); ?>" class="btn-tambah" style="background:linear-gradient(135deg,#dc2626,#ef4444);"><i class="bi bi-file-earmark-pdf"></i> Export PDF</a>
        <a href="<?php echo base_url('iuran/tambah'); ?>" class="btn-tambah"><i class="bi bi-plus-circle"></i> Tambah Iuran</a>
    </div>
    <?php endif; ?>
</div>

<!-- ===== ALERT VERIFIKASI ADMIN ===== -->
<?php if(is_admin() && !empty($menunggu_verifikasi)): ?>
<div class="verif-alert">
    <div class="va-text">
        <i class="bi bi-clock-history me-2" style="color:#f59e0b;"></i>
        Ada <strong><?php echo count($menunggu_verifikasi); ?> pembayaran</strong> menunggu verifikasi
    </div>
    <a href="#menunggu-verifikasi" class="btn-verif-now btn">Lihat Sekarang</a>
</div>
<?php endif; ?>

<?php
// =====================================================================
// HELPER: deteksi status aktual (cicil jika ada terbayar tapi belum lunas)
// =====================================================================
function getStatusAktual($row) {
    $status         = isset($row->status_bayar) ? $row->status_bayar
                    : (isset($row->status) ? $row->status : 'pending');
    if(empty($status)) $status = 'pending';

    // Jika DB sudah 'cicil' → percaya DB
    if($status === 'cicil') return 'cicil';

    // Fallback: status 'pending' tapi total_terbayar > 0 dan masih ada sisa
    $total_terbayar = (float)($row->total_terbayar ?? 0);
    $nominal        = (float)($row->nominal        ?? 0);
    $sisa           = (float)($row->sisa_tagihan   ?? $nominal);
    if($status === 'pending' && $total_terbayar > 0 && $sisa > 0) return 'cicil';

    return $status;
}

function getStatusBadge($status) {
    switch($status) {
        case 'lunas':               return ['sb-lunas',     'bi-check-circle',        'Lunas'];
        case 'cicil':               return ['sb-cicil',     'bi-hourglass-split',     'Cicil'];
        case 'menunggu_verifikasi': return ['sb-verifikasi','bi-clock-history',        'Menunggu Verifikasi'];
        case 'pending':
        case 'belum':               return ['sb-pending',   'bi-exclamation-triangle', 'Belum Dibayar'];
        default:                    return ['sb-other',      'bi-dash-circle',          ucfirst($status)];
    }
}
?>
<?php
$bulan_names = ['','Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
$bulan_short = ['','Jan','Feb','Mar','Apr','Mei','Jun','Jul','Ags','Sep','Okt','Nov','Des'];
?>

<!-- ===== STAT CARDS WARGA ===== -->
<?php if(is_warga()):
    $belum_lunas     = array_filter($iuran, fn($i) => getStatusAktual($i) == 'pending');
    $sedang_cicil    = array_filter($iuran, fn($i) => getStatusAktual($i) == 'cicil');
    $lunas           = array_filter($iuran, fn($i) => getStatusAktual($i) == 'lunas');
    $total_tunggakan = 0;
    foreach($belum_lunas as $b) $total_tunggakan += $b->nominal;
    $total_sisa_cicil = 0;
    foreach($sedang_cicil as $sc) $total_sisa_cicil += (float)($sc->sisa_tagihan ?? 0);
?>
<div class="row g-3 mb-4 stat-row">
    <div class="col-md-3 col-6">
        <div class="card stat-card" style="border-left:4px solid #ef4444 !important;">
            <div class="card-body d-flex align-items-center py-3">
                <div class="rounded-3 d-flex align-items-center justify-content-center me-3 flex-shrink-0" style="width:42px;height:42px;background:#fee2e2;">
                    <i class="bi bi-exclamation-triangle text-danger"></i>
                </div>
                <div>
                    <div class="text-muted small fw-semibold">Belum Dibayar</div>
                    <div class="fw-bold fs-4 lh-1 text-danger"><?php echo count($belum_lunas); ?></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 col-6">
        <div class="card stat-card" style="border-left:4px solid #7c3aed !important;">
            <div class="card-body d-flex align-items-center py-3">
                <div class="rounded-3 d-flex align-items-center justify-content-center me-3 flex-shrink-0" style="width:42px;height:42px;background:#ede9fe;">
                    <i class="bi bi-hourglass-split" style="color:#7c3aed;"></i>
                </div>
                <div>
                    <div class="text-muted small fw-semibold">Sedang Dicicil</div>
                    <div class="fw-bold fs-4 lh-1" style="color:#7c3aed;"><?php echo count($sedang_cicil); ?></div>
                    <?php if($total_sisa_cicil > 0): ?>
                    <div style="font-size:.68rem;color:#7c3aed;">Sisa Rp <?php echo number_format($total_sisa_cicil,0,',','.'); ?></div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 col-6">
        <div class="card stat-card" style="border-left:4px solid #f59e0b !important;">
            <div class="card-body d-flex align-items-center py-3">
                <div class="rounded-3 d-flex align-items-center justify-content-center me-3 flex-shrink-0" style="width:42px;height:42px;background:#fef3c7;">
                    <i class="bi bi-clock-history text-warning"></i>
                </div>
                <div>
                    <div class="text-muted small fw-semibold">Menunggu Verif</div>
                    <div class="fw-bold fs-4 lh-1 text-warning"><?php echo isset($menunggu_verifikasi) ? count($menunggu_verifikasi) : 0; ?></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 col-6">
        <div class="card stat-card" style="border-left:4px solid #20c997 !important;">
            <div class="card-body d-flex align-items-center py-3">
                <div class="rounded-3 d-flex align-items-center justify-content-center me-3 flex-shrink-0" style="width:42px;height:42px;background:#d1fae5;">
                    <i class="bi bi-check-circle" style="color:#20c997;"></i>
                </div>
                <div>
                    <div class="text-muted small fw-semibold">Sudah Lunas</div>
                    <div class="fw-bold fs-4 lh-1" style="color:#20c997;"><?php echo count($lunas); ?></div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- ===== BANNER BAYAR SEMUA/MASSAL ===== -->
<?php
$show_bayar_semua  = false;
$bayar_semua_count = 0;
$bayar_semua_total = 0;
if(is_admin()) {
    $all_pending = array_filter(isset($iuran) ? $iuran : [], function($x){ return $x->status == 'pending'; });
    if(count($all_pending) > 1) {
        $show_bayar_semua  = true;
        $bayar_semua_count = count($all_pending);
        foreach($all_pending as $ap) $bayar_semua_total += $ap->nominal;
    }
} elseif(is_warga() && !empty($tagihan_pending) && count($tagihan_pending) > 1) {
    $show_bayar_semua  = true;
    $bayar_semua_count = count($tagihan_pending);
    foreach($tagihan_pending as $p) $bayar_semua_total += $p->nominal;
}
?>
<?php if($show_bayar_semua): ?>
<div class="verif-alert" style="background:#eff6ff; border:1.5px solid #bfdbfe;">
    <div class="va-text" style="color:#1e40af;">
        <i class="bi bi-collection me-2" style="color:#3b82f6;"></i>
        Ada <strong><?php echo $bayar_semua_count; ?> tagihan</strong> belum dibayar —
        total <strong>Rp <?php echo number_format($bayar_semua_total, 0, ',', '.'); ?></strong>
    </div>
    <a href="<?php echo base_url(is_admin() ? 'iuran/bayar_massal' : 'iuran/bayar_semua'); ?>" class="btn-verif-now btn" style="background:#3b82f6;">
        <i class="bi bi-collection me-1"></i><?php echo is_admin() ? 'Bayar Massal' : 'Bayar Semua'; ?>
    </a>
</div>
<?php endif; ?>

<!-- ===== FILTER ===== -->
<div class="filter-card card">
    <div class="card-body">
        <div class="row g-2 align-items-end filter-row">
            <div class="col-md-3">
                <label class="form-label small fw-semibold text-muted mb-1">Status</label>
                <select id="f_status" class="form-select form-select-sm">
                    <option value="">Semua Status</option>
                    <option value="pending">Belum Dibayar</option>
                    <option value="cicil">Sedang Dicicil</option>
                    <option value="menunggu_verifikasi">Menunggu Verifikasi</option>
                    <option value="lunas">Lunas</option>
                </select>
            </div>
            <!-- Jenis Iuran -->
            <div class="col-md-2">
                <label class="form-label small fw-semibold text-muted mb-1">Jenis Iuran</label>
                <select id="f_jenis_iuran_id" class="form-select form-select-sm">
                    <option value="">Semua Jenis</option>
                    <?php foreach($jenis_iuran_list as $ji): ?>
                    <option value="<?php echo $ji->id; ?>"><?php echo htmlspecialchars($ji->nama_iuran); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label small fw-semibold text-muted mb-1">Bulan</label>
                <select id="f_bulan" class="form-select form-select-sm">
                    <option value="">Semua Bulan</option>
                    <?php
                    $bulan_filter = ['','Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
                    for($b = 1; $b <= 12; $b++):
                    ?>
                    <option value="<?php echo $b; ?>"><?php echo $bulan_filter[$b]; ?></option>
                    <?php endfor; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label small fw-semibold text-muted mb-1">Tahun</label>
                <select id="f_tahun" class="form-select form-select-sm">
                    <option value="">Semua Tahun</option>
                    <?php for($i = date('Y')-2; $i <= date('Y'); $i++): ?>
                    <option value="<?php echo $i; ?>" <?php echo ($i == date('Y')) ? 'selected' : ''; ?>><?php echo $i; ?></option>
                    <?php endfor; ?>
                </select>
            </div>
            <div class="col-md-2 col-btn">
                <div class="d-flex gap-2">
                    <button id="btnFilter" type="button" class="btn btn-sm fw-semibold d-flex align-items-center gap-1" style="background:#20c997;color:#fff;border:none;border-radius:8px;padding:9px 18px;">
                        <i class="bi bi-funnel"></i> Filter
                    </button>
                    <button id="btnResetFilter" type="button" class="btn btn-sm fw-semibold d-flex align-items-center gap-1" style="background:#f3f4f6;color:#374151;border:1px solid #e5e7eb;border-radius:8px;padding:9px 12px;" title="Reset">
                        <i class="bi bi-x-circle"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ===== TABEL IURAN UTAMA ===== -->
<div class="section-card">
    <div class="section-card-header">
        <div class="title">
            <i class="bi bi-list-ul"></i>
            <?php echo is_admin() ? 'Semua Data Iuran' : 'Riwayat Iuran Saya'; ?>
        </div>
        <div class="text-muted" style="font-size:.75rem;" id="dtInfoText"></div>
    </div>

    <!-- ── DESKTOP TABLE ── -->
    <div class="desktop-table table-responsive">
        <table class="table iuran-table mb-0" id="tableIuran" style="width:100%;">
            <thead><tr>
                <th style="width:44px;">No</th>
                <?php if(is_admin()): ?><th>Nama Warga</th><?php endif; ?>
                <th>Jenis Iuran</th>
                <th>Periode</th>
                <th class="text-end">Nominal / Progress</th>
                <th>Status</th>
                <th>Tgl Bayar</th>
                <th>Aksi</th>
                <th style="display:none;">_mobile</th>
            </tr></thead>
            <tbody></tbody>
        </table>
    </div>

    <!-- ── MOBILE CARD LIST ── -->
    <div class="mobile-iuran-list" id="mobileIuranList" style="display:none;flex-direction:column;gap:10px;padding:12px;"></div>

    <!-- Loading indicator -->
    <div id="dtLoading" class="text-center py-4" style="display:none;">
        <div class="spinner-border spinner-border-sm text-success me-2" role="status"></div>
        <span class="text-muted" style="font-size:.85rem;">Memuat data…</span>
    </div>

    <!-- Empty state -->
    <div id="dtEmpty" class="text-center py-5 text-muted" style="display:none;">
        <i class="bi bi-inbox fs-1 d-block mb-3 opacity-50"></i>
        <h6>Belum ada data iuran</h6>
    </div>
</div>

<?php if(is_admin() && !empty($menunggu_verifikasi)): ?>
<div class="section-card" id="menunggu-verifikasi">
    <div class="section-card-header" style="background:#fffbeb; border-bottom:1.5px solid #fde68a;">
        <div class="title" style="color:#92400e;">
            <i class="bi bi-clock-history" style="color:#f59e0b;"></i>
            Menunggu Verifikasi
            <span class="badge rounded-pill ms-1 fw-bold" style="background:#fef3c7; color:#92400e; border:1px solid #fde68a;"><?php echo count($menunggu_verifikasi); ?></span>
        </div>
    </div>
    <div class="desktop-table table-responsive">
        <table class="table iuran-table mb-0">
            <thead><tr>
                <th style="width:44px;">No</th>
                <th>Nama Warga</th><th>Jenis Iuran</th><th>Periode</th>
                <th class="text-end">Nominal</th><th>Tgl Upload</th><th>Aksi</th>
            </tr></thead>
            <tbody>
            <?php $no=1; foreach($menunggu_verifikasi as $m): ?>
            <tr class="row-verif">
                <td><?php echo $no++; ?></td>
                <td class="fw-semibold"><?php echo htmlspecialchars($m->nama_lengkap); ?></td>
                <td><?php echo htmlspecialchars($m->nama_iuran); ?></td>
                <td><?php echo $bulan_short[(int)$m->periode_bulan].' '.$m->periode_tahun; ?></td>
                <td class="text-end fw-bold" style="color:#20c997;">Rp <?php echo number_format($m->nominal,0,',','.'); ?></td>
                <td><?php echo date('d/m/Y H:i', strtotime($m->tanggal_bayar)); ?></td>
                <td>
                    <a href="<?php echo base_url('iuran/verifikasi/'.$m->id); ?>" class="btn-act btn" style="background:#fef3c7; border:1px solid #fde68a; color:#92400e;">
                        <i class="bi bi-check-square"></i> Verifikasi
                    </a>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <div class="mobile-iuran-list">
        <?php foreach($menunggu_verifikasi as $m): ?>
        <div style="border-radius:10px; border:1.5px solid #fde68a; background:#fffbeb; padding:12px 14px;">
            <div class="d-flex justify-content-between align-items-start mb-1">
                <span class="fw-semibold" style="font-size:.88rem;"><?php echo htmlspecialchars($m->nama_lengkap); ?></span>
                <span class="fw-bold" style="color:#20c997; font-size:.88rem;">Rp <?php echo number_format($m->nominal,0,',','.'); ?></span>
            </div>
            <div style="font-size:.78rem; color:#6b7280;" class="mb-2">
                <?php echo htmlspecialchars($m->nama_iuran); ?> &nbsp;·&nbsp;
                <?php echo $bulan_short[(int)$m->periode_bulan].' '.$m->periode_tahun; ?> &nbsp;·&nbsp;
                <?php echo date('d/m/Y H:i', strtotime($m->tanggal_bayar)); ?>
            </div>
            <a href="<?php echo base_url('iuran/verifikasi/'.$m->id); ?>" class="btn w-100 fw-semibold" style="background:#fef3c7; border:1px solid #fde68a; color:#92400e; border-radius:8px; font-size:.82rem; padding:8px;">
                <i class="bi bi-check-square me-1"></i>Verifikasi Sekarang
            </a>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>


<!-- ===== INFO WARGA ===== -->
<?php if(is_warga()): ?>
<div style="background:#eff6ff; border:1.5px solid #bfdbfe; border-radius:12px; padding:13px 16px; font-size:.82rem; color:#1e40af; display:flex; gap:10px; align-items:flex-start;">
    <i class="bi bi-info-circle-fill flex-shrink-0 mt-1"></i>
    <div>
        <strong>Informasi:</strong> Klik <strong>"Bayar Sekarang"</strong> untuk membayar penuh,
        <strong>"Lanjut Cicil"</strong> untuk menambah cicilan, atau <strong>"Bayar Semua"</strong>
        untuk membayar semua tagihan sekaligus. Tunggu verifikasi admin maks. 1×24 jam.
    </div>
</div>
<?php endif; ?>

<!-- ===== MODAL KONFIRMASI HAPUS ===== -->
<div class="modal fade" id="modalHapusIuran" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" style="max-width:400px;">
    <div class="modal-content" style="border-radius:16px;border:none;overflow:hidden;">
      <div class="modal-header" style="background:#fef2f2;border-bottom:1.5px solid #fecaca;padding:18px 20px;">
        <div class="d-flex align-items-center gap-2">
          <div style="width:36px;height:36px;background:#fee2e2;border-radius:10px;display:flex;align-items:center;justify-content:center;">
            <i class="bi bi-trash-fill" style="color:#dc2626;font-size:1rem;"></i>
          </div>
          <h6 class="modal-title mb-0 fw-bold" style="color:#991b1b;font-size:.95rem;">Hapus Data Iuran</h6>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" style="padding:20px;">
        <p style="font-size:.85rem;color:#334155;margin-bottom:10px;">Anda akan menghapus data iuran:</p>
        <div style="background:#fef2f2;border:1.5px solid #fecaca;border-radius:10px;padding:12px 16px;">
          <div style="font-weight:700;font-size:.88rem;color:#991b1b;" id="hapusIuranNama">-</div>
          <div style="font-size:.78rem;color:#b91c1c;margin-top:3px;" id="hapusIuranWarga"></div>
        </div>
        <div style="background:#fffbeb;border:1.5px solid #fde68a;border-radius:8px;padding:9px 14px;margin-top:12px;font-size:.78rem;color:#92400e;">
          <i class="bi bi-exclamation-triangle-fill me-1"></i>
          Data akan <strong>terhapus permanen</strong> dan tidak dapat dikembalikan.
        </div>
      </div>
      <div class="modal-footer" style="border:none;padding:0 20px 18px;gap:8px;">
        <button type="button" class="btn" data-bs-dismiss="modal"
          style="border-radius:8px;border:1.5px solid #e5e7eb;font-size:.82rem;font-weight:600;color:#64748b;padding:7px 18px;flex:1;">
          <i class="bi bi-x-lg me-1"></i>Batal
        </button>
        <a href="#" id="btnKonfirmasiHapusIuran"
          style="border-radius:8px;border:none;font-size:.82rem;font-weight:700;color:#fff;padding:7px 18px;flex:1;background:linear-gradient(135deg,#dc2626,#ef4444);box-shadow:0 4px 12px rgba(220,38,38,.28);cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:6px;text-decoration:none;">
          <i class="bi bi-trash-fill"></i>Ya, Hapus
        </a>
      </div>
    </div>
  </div>
</div>

<script>
var _bsModalHapusIuran = null;
function konfirmasiHapusIuran(url, namaIuran, namaWarga) {
    var elNama  = document.getElementById('hapusIuranNama');
    var elWarga = document.getElementById('hapusIuranWarga');
    var elBtn   = document.getElementById('btnKonfirmasiHapusIuran');
    if(elNama)  elNama.textContent  = namaIuran || '-';
    if(elWarga) elWarga.textContent = namaWarga ? 'Warga: ' + namaWarga : '';
    if(elBtn)   elBtn.href          = url;
    var modalEl = document.getElementById('modalHapusIuran');
    if(!modalEl) return;
    if(!_bsModalHapusIuran) _bsModalHapusIuran = new bootstrap.Modal(modalEl);
    _bsModalHapusIuran.show();
}

// ── Kirim Tagihan WA via WAHA (otomatis) ──────────────────────────
function kirimTagihanWa(btn) {
    const iuranId = btn.dataset.id;
    const nama    = btn.dataset.nama;

    const modalEl = document.getElementById('modalKonfirmasiWaha');
    const modalBody = document.getElementById('wahaModalBody');
    const btnProses = document.getElementById('btnProsesWaha');
    
    modalBody.innerHTML = 'Kirim tagihan iuran ke <strong>' + nama + '</strong> via WhatsApp otomatis (WAHA)?';
    
    const myModal = new bootstrap.Modal(modalEl);
    myModal.show();

    btnProses.onclick = function() {
        myModal.hide();
        
        btn.disabled = true;
        const origHtml = btn.innerHTML;
        btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Mengirim...';

        const fd = new FormData();
        fd.append('iuran_id', iuranId);

        fetch('<?php echo base_url("iuran/kirim_tagihan_wa"); ?>', {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body: fd,
        })
        .then(async r => {
            const text = await r.text();
            try {
                return JSON.parse(text);
            } catch (e) {
                console.error('JSON Parse Error. Raw Response:', text);
                throw new Error('Respon server tidak valid (bukan JSON).');
            }
        })
        .then(data => {
            const tipe = data.status === 'ok' ? 'success' : 'danger';
            // Toast notifikasi
            const 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:280px;border-radius:12px;font-size:.85rem;box-shadow:0 4px 20px rgba(0,0,0,.15);';
            div.innerHTML = '<i class="bi bi-whatsapp me-2"></i>' + (data.msg || 'Selesai') +
                '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
            document.body.appendChild(div);
            setTimeout(() => { div.classList.remove('show'); setTimeout(() => div.remove(), 400); }, 5000);
        })
        .catch(e => alert('Kesalahan: ' + e.message))
        .finally(() => {
            btn.disabled = false;
            btn.innerHTML = origHtml;
        });
    };
}
</script>

<!-- Modal Konfirmasi WAHA -->
<div class="modal fade" id="modalKonfirmasiWaha" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content" style="border-radius:15px; border:none; box-shadow: 0 10px 30px rgba(0,0,0,0.1);">
      <div class="modal-header" style="border:none; padding: 20px 25px 10px;">
        <h5 class="modal-title fw-bold" id="wahaModalTitle">Konfirmasi Pengiriman</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body" style="padding: 10px 25px 25px;">
        <p id="wahaModalBody" class="text-muted" style="font-size:.95rem;"></p>
      </div>
      <div class="modal-footer" style="border:none; padding: 0 25px 25px; gap: 10px;">
        <button type="button" class="btn" data-bs-dismiss="modal" style="border-radius:10px; padding: 10px 20px; font-size:.85rem; font-weight:600; background:#f1f5f9; color:#475569; border:none; flex:1;">Batal</button>
        <button type="button" id="btnProsesWaha" class="btn" style="border-radius:10px; padding: 10px 20px; font-size:.85rem; font-weight:600; background:linear-gradient(135deg, #25D366, #128C7E); color:#fff; border:none; flex:1; box-shadow: 0 4px 15px rgba(37,211,102,0.3);">
            <i class="bi bi-send-fill me-1"></i>Kirim Sekarang
        </button>
      </div>
    </div>
  </div>
</div>



<!-- ===== DATATABLES SERVER-SIDE SCRIPT ===== -->
<!-- CSS DataTables (dimuat di sini, tidak perlu tunggu jQuery) -->
<!-- <link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css"> -->
 <link rel="stylesheet" href="<?= base_url('assets/css/dataTables.bootstrap5.min.css'); ?>">

<style>
/* ===== DATATABLES CUSTOM ===== */
#tableIuran_wrapper .dataTables_filter input {
    border-radius: 8px; border: 1.5px solid #e5e7eb; font-size:.85rem; padding: 7px 12px;
}
#tableIuran_wrapper .dataTables_filter input:focus { border-color:#20c997; outline:none; box-shadow:0 0 0 3px rgba(32,201,151,.12); }
#tableIuran_wrapper .dataTables_length select {
    border-radius: 8px; border: 1.5px solid #e5e7eb; font-size:.85rem; padding: 5px 30px 5px 12px; cursor:pointer; min-width: 70px;
}
#tableIuran_wrapper .dataTables_info { font-size:.8rem; color:#6b7280; }
#tableIuran_wrapper .dataTables_paginate .paginate_button {
    border-radius: 7px !important; font-size:.8rem !important; border:none !important;
}
#tableIuran_wrapper .dataTables_paginate .paginate_button.current {
    background: #0d9488 !important; color:#fff !important; border:none !important;
}
#tableIuran_wrapper .dataTables_paginate .paginate_button:hover:not(.current):not(.disabled) {
    background: #f0fdf4 !important; color:#0d9488 !important; border:none !important;
}
div.dataTables_processing { color:#0d9488; font-size:.85rem; }
</style>

<script>
// ── jQuery belum dimuat di footer, gunakan polling ──
// Script ini ada di body view (sebelum footer), jQuery baru ada setelah footer dimuat.
(function waitForJQuery() {
    if (typeof jQuery === 'undefined' || typeof jQuery.fn.dataTable === 'undefined') {
        return setTimeout(waitForJQuery, 50);
    }

    'use strict';
    var $ = jQuery;

    var isMobile    = function(){ return window.innerWidth <= 767; };
    var dtTable     = null;
    var MQ          = window.matchMedia('(max-width: 767.98px)');
    var isAdmin     = <?php echo is_admin() ? 'true' : 'false'; ?>;
    var mobileColIdx = isAdmin ? 8 : 7;

    function getFilter() {
        return {
            f_status         : $('#f_status').val(),
            f_bulan          : $('#f_bulan').val(),
            f_tahun          : $('#f_tahun').val(),
            f_jenis_iuran_id : $('#f_jenis_iuran_id').val(),
        };
    }

    function renderMobile(data) {
        var list = document.getElementById('mobileIuranList');
        if (!list) return;
        list.innerHTML = '';
        if (!data || data.length === 0) return;
        data.forEach(function(row) {
            var wrap = document.createElement('div');
            wrap.innerHTML = row[mobileColIdx] || '';
            if (wrap.firstChild) list.appendChild(wrap.firstChild);
        });
    }

    function applyResponsive() {
        var mobile      = isMobile();
        var desktopWrap = document.querySelector('.desktop-table.table-responsive');
        var mobileList  = document.getElementById('mobileIuranList');
        if (!desktopWrap || !mobileList) return;
        if (mobile) {
            desktopWrap.style.display = 'none';
            mobileList.style.display  = 'flex';
        } else {
            desktopWrap.style.display = '';
            mobileList.style.display  = 'none';
        }
    }

    dtTable = $('#tableIuran').DataTable({
        processing : true,
        serverSide : true,
        ajax : {
            url  : '<?php echo base_url('iuran/ajax_datatables'); ?>',
            type : 'POST',
            data : function(d) {
                var f = getFilter();
                d.f_status         = f.f_status;
                d.f_bulan          = f.f_bulan;
                d.f_tahun          = f.f_tahun;
                d.f_jenis_iuran_id = f.f_jenis_iuran_id;
            },
            error: function(xhr, err, thrown) {
                console.error('DataTables AJAX error:', err, thrown, xhr.responseText);
            }
        },
        columns : (function() {
            var cols = [{ title:'No', orderable:false, width:'44px' }];
            if (isAdmin) cols.push({ title:'Nama Warga' });
            cols.push(
                { title:'Jenis Iuran' },
                { title:'Periode' },
                { title:'Nominal / Progress', className:'text-end' },
                { title:'Status' },
                { title:'Tgl Bayar' },
                { title:'Aksi', orderable:false },
                { title:'_mobile', visible:false, searchable:false }
            );
            return cols;
        })(),
        language: {
            search           : '',
            searchPlaceholder: 'Cari nama, jenis iuran…',
            lengthMenu       : 'Tampilkan _MENU_ data',
            info             : 'Menampilkan _START_–_END_ dari _TOTAL_ data',
            infoEmpty        : 'Tidak ada data',
            infoFiltered     : '(difilter dari _MAX_ total data)',
            paginate         : { previous:'‹', next:'›' },
            processing       : '<i class="bi bi-arrow-repeat"></i> Memuat data…',
            zeroRecords      : 'Tidak ada data sesuai filter',
            emptyTable       : 'Belum ada data iuran',
        },
        pageLength  : 25,
        order       : isAdmin ? [[3,'desc']] : [[2,'desc']],
        drawCallback: function(settings) {
            var api  = this.api();
            var data = api.rows().data().toArray();
            renderMobile(data);
            applyResponsive();

            var info = api.page.info();
            var el   = document.getElementById('dtInfoText');
            if (el) el.textContent = info.recordsDisplay + ' data ditampilkan';

            // Cicil row highlight
            api.rows().every(function() {
                var rowData = this.data();
                var nomIdx  = isAdmin ? 4 : 3;
                if (typeof rowData[nomIdx] === 'string' && rowData[nomIdx].indexOf('cicil-bar') !== -1) {
                    $(this.node()).addClass('row-cicil');
                }
            });
        }
    });

    $('#btnFilter').on('click', function() {
        dtTable.ajax.reload();
    });

    $('#btnResetFilter').on('click', function() {
        $('#f_status, #f_bulan, #f_tahun, #f_jenis_iuran_id').val('');
        dtTable.search('').ajax.reload();
    });

    MQ.addEventListener('change', applyResponsive);
    applyResponsive();

})();
</script>


