<style>
.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: 0.88rem;
    padding: 9px 12px;
    color: #111827;
}
.form-control::placeholder { color: #9ca3af; }

/* ===== SECTION CARD ===== */
.form-section {
    border-radius: 14px;
    border: none;
    box-shadow: 0 1px 6px rgba(0,0,0,.07);
    overflow: hidden;
    margin-bottom: 20px;
    background: #fff;
}
.form-section-header {
    padding: 13px 20px;
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 0.8rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .05em;
    color: #374151;
    border-bottom: 1px solid #f1f3f5;
}
.form-section-header i { color: #20c997; }
.form-section-body { padding: 20px; }

.field-label {
    font-size: 0.8rem;
    font-weight: 600;
    color: #374151;
    margin-bottom: 5px;
    display: block;
}
.field-label .req { color: #ef4444; }

/* ===== BADGE STATUS ===== */
.badge-kk {
    display: inline-flex; align-items: center; gap: 4px;
    background: #d1fae5; color: #065f46;
    border: 1px solid #6ee7b7;
    border-radius: 20px;
    font-size: 0.7rem; font-weight: 700;
    padding: 2px 9px;
    white-space: nowrap;
}
.badge-kk i { font-size: .65rem; }

.badge-anggota {
    display: inline-flex; align-items: center; gap: 4px;
    background: #f3f4f6; color: #6b7280;
    border: 1px solid #e5e7eb;
    border-radius: 20px;
    font-size: 0.7rem; font-weight: 600;
    padding: 2px 9px;
    white-space: nowrap;
}

/* ===== WARGA TABLE ===== */
.warga-scroll {
    max-height: 400px;
    overflow-y: auto;
    border: 1.5px solid #e5e7eb;
    border-radius: 10px;
}
.warga-scroll::-webkit-scrollbar { width: 5px; }
.warga-scroll::-webkit-scrollbar-thumb { background: #d1fae5; border-radius: 4px; }

.warga-table { margin: 0; font-size: 0.85rem; }
.warga-table thead th {
    background: #f8fffe;
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: .04em;
    color: #6b7280;
    font-weight: 700;
    padding: 10px 14px;
    border-bottom: 1.5px solid #e5e7eb;
    position: sticky;
    top: 0;
    z-index: 1;
}
.warga-table tbody td { padding: 10px 14px; vertical-align: middle; border-bottom: 1px solid #f3f4f6; }
.warga-table tbody tr:last-child td { border-bottom: none; }
.warga-table tbody tr:hover { background: #f0fdf9; }
.warga-table tbody tr.selected { background: #e6faf5; }
.warga-table tbody tr.row-kk { background: #fafffe; }
.warga-table tbody tr.row-kk.selected { background: #d1fae5; }

/* Custom checkbox */
.form-check-input {
    width: 16px; height: 16px; cursor: pointer;
    border: 1.5px solid #d1d5db; border-radius: 4px;
}
.form-check-input:checked { background-color: #20c997; border-color: #20c997; }

/* ===== SUMMARY BAR ===== */
.summary-bar {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 1px;
    background: #e5e7eb;
    border-radius: 12px;
    overflow: hidden;
    border: 1px solid #e5e7eb;
}
.summary-cell {
    background: #fff;
    padding: 14px 20px;
    text-align: center;
}
.summary-cell .s-label { font-size: 0.75rem; color: #6b7280; font-weight: 600; margin-bottom: 4px; }
.summary-cell .s-value { font-size: 1.4rem; font-weight: 800; color: #111827; line-height: 1; }
.summary-cell .s-value.green { color: #20c997; }
.summary-cell .s-value.blue  { color: #3b82f6; }

/* ===== ACTION BAR ===== */
.action-bar {
    display: flex; gap: 10px; align-items: center; justify-content: space-between;
    padding: 16px 20px;
    background: #fff;
    border-radius: 14px;
    box-shadow: 0 1px 6px rgba(0,0,0,.07);
}
.btn-back {
    background: #f3f4f6; border: 1.5px solid #e5e7eb; color: #6b7280;
    border-radius: 8px; padding: 9px 18px; font-weight: 600; font-size: .88rem;
    display: flex; align-items: center; gap: 6px;
}
.btn-back:hover { background: #e5e7eb; color: #374151; }
.btn-generate {
    background: #20c997; border: none; color: #fff;
    border-radius: 8px; padding: 9px 22px; font-weight: 700; font-size: .88rem;
    display: flex; align-items: center; gap: 6px;
    transition: background .2s;
}
.btn-generate:hover:not(:disabled) { background: #1aab81; color: #fff; }
.btn-generate:disabled { background: #a7f3d0; cursor: not-allowed; }

/* ===== SELECT ALL BAR ===== */
.select-bar {
    display: flex; align-items: center; justify-content: space-between;
    margin-bottom: 10px; flex-wrap: wrap; gap: 8px;
}
.select-bar .label { font-size: 0.82rem; font-weight: 700; color: #374151; display: flex; align-items: center; gap: 6px; }
.select-bar .label i { color: #20c997; }
.btn-sel {
    font-size: 0.78rem; padding: 5px 12px; border-radius: 7px; font-weight: 600;
    border: 1.5px solid; cursor: pointer;
    display: flex; align-items: center; gap: 4px;
    background: none; line-height: 1.4;
}
.btn-sel.all    { border-color: #20c997; color: #20c997; background: #f0fdf9; }
.btn-sel.all:hover { background: #d1fae5; }
.btn-sel.kk     { border-color: #3b82f6; color: #1d4ed8; background: #eff6ff; }
.btn-sel.kk:hover { background: #dbeafe; }
.btn-sel.none   { border-color: #e5e7eb; color: #6b7280; background: #f9fafb; }
.btn-sel.none:hover { background: #f3f4f6; }

/* ===== FILTER TABS ===== */
.filter-tabs {
    display: flex; gap: 6px; margin-bottom: 12px;
}
.filter-tab {
    font-size: 0.78rem; font-weight: 600;
    padding: 5px 14px; border-radius: 20px;
    border: 1.5px solid #e5e7eb; cursor: pointer;
    background: #f9fafb; color: #6b7280;
    transition: all .15s;
}
.filter-tab.active        { background: #20c997; border-color: #20c997; color: #fff; }
.filter-tab.active-kk     { background: #3b82f6; border-color: #3b82f6; color: #fff; }
.filter-tab.active-all    { background: #20c997; border-color: #20c997; color: #fff; }

/* Info box */
.info-box {
    background: #eff6ff; border: 1.5px solid #bfdbfe;
    border-radius: 10px; padding: 13px 16px; margin-bottom: 20px;
    font-size: .82rem; color: #1e40af;
}
.info-box .info-title { font-weight: 700; margin-bottom: 6px; }
.info-box ul { margin: 0; padding-left: 16px; }
.info-box ul li { margin-bottom: 3px; }

/* ===== MOBILE ===== */
@media (max-width: 767.98px) {
    .container-fluid { padding-left: 12px !important; padding-right: 12px !important; }
    .page-header { flex-direction: column; align-items: flex-start !important; gap: 8px; margin-bottom: 14px !important; }
    .page-header h4 { font-size: 1rem; }
    .field-grid > [class*="col-"] { flex: 0 0 100% !important; max-width: 100% !important; }
    .col-bulan-tahun { flex: 0 0 50% !important; max-width: 50% !important; }
    .form-section-body { padding: 14px; }
    .warga-table .col-nik,
    .warga-table .col-alamat { display: none; }
    .summary-bar { grid-template-columns: 1fr 1fr; }
    .summary-cell:last-child { grid-column: span 2; }
    .summary-cell .s-value { font-size: 1.2rem; }
    .action-bar { flex-direction: column; }
    .action-bar .btn-back,
    .action-bar .btn-generate { width: 100%; justify-content: center; }
    .select-bar { flex-direction: column; align-items: flex-start; }
    .filter-tabs { flex-wrap: wrap; }
}
</style>

<div class="container-fluid px-4 py-3">

    <!-- Header -->
    <div class="d-flex align-items-center justify-content-between mb-4 page-header">
        <div>
            <h4 class="mb-0 fw-bold text-dark">
                <i class="bi bi-file-earmark-text me-2" style="color:#20c997;"></i>Generate Tagihan Iuran
            </h4>
            <small class="text-muted">Buat tagihan untuk banyak warga sekaligus</small>
        </div>
        <a href="<?php echo base_url('iuran'); ?>" class="btn btn-sm btn-outline-secondary fw-semibold" style="border-radius:8px;">
            <i class="bi bi-arrow-left me-1"></i>Kembali
        </a>
    </div>

    <!-- Error -->
    <?php if($this->session->flashdata('error')): ?>
    <div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm mb-4" style="border-radius:10px;" role="alert">
        <i class="bi bi-exclamation-triangle-fill me-2"></i><?php echo $this->session->flashdata('error'); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <!-- Info -->
    <div class="info-box">
        <div class="info-title"><i class="bi bi-info-circle me-1"></i>Informasi</div>
        <ul>
            <li>Tagihan yang digenerate akan berstatus <strong>PENDING</strong> (belum dibayar)</li>
            <li>Gunakan tombol <strong>"Pilih Kepala KK"</strong> jika iuran hanya dibebankan kepada Kepala Keluarga</li>
            <li>Kolom <strong>Status</strong> menunjukkan peran warga dalam keluarga</li>
            <li>Nominal berlaku sama untuk semua warga yang dipilih</li>
        </ul>
    </div>

    <form action="<?php echo base_url('iuran/proses_generate_tagihan'); ?>" method="post">

        <!-- ===== Section 1: Detail Tagihan ===== -->
        <div class="form-section">
            <div class="form-section-header">
                <i class="bi bi-receipt"></i> Detail Tagihan
            </div>
            <div class="form-section-body">
                <div class="row g-3 field-grid">

                    <!-- Jenis Iuran -->
                    <div class="col-md-5">
                        <label class="field-label">Jenis Iuran <span class="req">*</span></label>
                        <select name="jenis_iuran_id" class="form-select" id="jenisIuran" required>
                            <option value="">-- Pilih Jenis Iuran --</option>
                            <?php foreach($jenis_iuran as $ji):
                                $nominal = isset($ji->nominal) ? $ji->nominal : 0;
                            ?>
                            <option value="<?php echo $ji->id; ?>" data-nominal="<?php echo $nominal; ?>">
                                <?php echo $ji->nama_iuran; ?> — Rp <?php echo number_format($nominal, 0, ',', '.'); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- Periode Mulai -->
                    <div class="col-md-4">
                        <label class="field-label">Mulai Periode <span class="req">*</span></label>
                        <div class="row g-2">
                            <div class="col-7">
                                <select name="periode_bulan_mulai" class="form-select" id="bulanMulai" required onchange="updateEstimasi()">
                                    <?php
                                    $bulan_nama = ['Januari','Februari','Maret','April','Mei','Juni',
                                                   'Juli','Agustus','September','Oktober','November','Desember'];
                                    for($i = 1; $i <= 12; $i++): ?>
                                    <option value="<?php echo sprintf('%02d', $i); ?>"
                                        <?php echo date('m') == sprintf('%02d', $i) ? 'selected' : ''; ?>>
                                        <?php echo $bulan_nama[$i-1]; ?>
                                    </option>
                                    <?php endfor; ?>
                                </select>
                            </div>
                            <div class="col-5">
                                <select name="periode_tahun_mulai" class="form-select" id="tahunMulai" required onchange="updateEstimasi()">
                                    <?php for($i = date('Y') - 1; $i <= date('Y') + 2; $i++): ?>
                                    <option value="<?php echo $i; ?>" <?php echo date('Y') == $i ? 'selected' : ''; ?>>
                                        <?php echo $i; ?>
                                    </option>
                                    <?php endfor; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- Periode Selesai -->
                    <div class="col-md-4">
                        <label class="field-label">Sampai Periode <span class="req">*</span></label>
                        <div class="row g-2">
                            <div class="col-7">
                                <select name="periode_bulan_selesai" class="form-select" id="bulanSelesai" required onchange="updateEstimasi()">
                                    <?php for($i = 1; $i <= 12; $i++): ?>
                                    <option value="<?php echo sprintf('%02d', $i); ?>"
                                        <?php echo date('m') == sprintf('%02d', $i) ? 'selected' : ''; ?>>
                                        <?php echo $bulan_nama[$i-1]; ?>
                                    </option>
                                    <?php endfor; ?>
                                </select>
                            </div>
                            <div class="col-5">
                                <select name="periode_tahun_selesai" class="form-select" id="tahunSelesai" required onchange="updateEstimasi()">
                                    <?php for($i = date('Y') - 1; $i <= date('Y') + 2; $i++): ?>
                                    <option value="<?php echo $i; ?>" <?php echo date('Y') == $i ? 'selected' : ''; ?>>
                                        <?php echo $i; ?>
                                    </option>
                                    <?php endfor; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- Nominal -->
                    <div class="col-md-4">
                        <label class="field-label">Nominal Per Bulan (Rp) <span class="req">*</span></label>
                        <div style="position:relative;">
                            <span style="position:absolute; left:11px; top:50%; transform:translateY(-50%); font-size:.78rem; font-weight:700; color:#20c997; pointer-events:none;">Rp</span>
                            <input type="number" name="nominal" id="nominal" class="form-control"
                                   required placeholder="0" min="0" step="1000"
                                   style="padding-left:30px;">
                        </div>
                    </div>

                </div>
            </div>
        </div>

        <!-- ===== Section 2: Pilih Warga ===== -->
        <div class="form-section">
            <div class="form-section-header">
                <i class="bi bi-people-fill"></i> Pilih Warga
                <!-- Jumlah Kepala KK Info -->
                <?php
                    $total_kk = 0;
                    if(!empty($warga)) {
                        foreach($warga as $w) {
                            if(isset($w->status_hubungan) && $w->status_hubungan === 'kepala_keluarga') $total_kk++;
                        }
                    }
                ?>
                <span style="margin-left:auto; font-size:0.75rem; font-weight:600; color:#6b7280; text-transform:none; letter-spacing:0;">
                    <span style="color:#20c997;"><?php echo count($warga ?? []); ?></span> total warga &nbsp;·&nbsp;
                    <span style="color:#3b82f6;"><?php echo $total_kk; ?></span> kepala KK
                </span>
            </div>
            <div class="form-section-body">

                <!-- Filter Tabs -->
                <div class="filter-tabs">
                    <button type="button" class="filter-tab active-all active" onclick="filterWarga('all', this)">
                        <i class="bi bi-people me-1"></i>Semua Warga
                    </button>
                    <button type="button" class="filter-tab" onclick="filterWarga('kk', this)" style="border-color:#93c5fd; color:#1d4ed8;">
                        <i class="bi bi-house-fill me-1"></i>Kepala KK Saja
                    </button>
                    <button type="button" class="filter-tab" onclick="filterWarga('anggota', this)" style="border-color:#d1d5db; color:#6b7280;">
                        <i class="bi bi-person me-1"></i>Anggota Saja
                    </button>
                </div>

                <!-- Select Bar -->
                <div class="select-bar">
                    <div class="label">
                        <i class="bi bi-person-check-fill"></i>
                        Centang warga yang akan ditagih <span style="color:#ef4444; margin-left:2px;">*</span>
                    </div>
                    <div class="d-flex gap-2 flex-wrap">
                        <!-- TOMBOL BARU: Pilih Kepala KK -->
                        <button type="button" class="btn-sel kk" onclick="checkKepalaKK()" title="Otomatis pilih semua Kepala Keluarga">
                            <i class="bi bi-house-fill"></i>Pilih Kepala KK
                        </button>
                        <button type="button" class="btn-sel all" onclick="checkAll(true)">
                            <i class="bi bi-check-all"></i>Pilih Semua
                        </button>
                        <button type="button" class="btn-sel none" onclick="checkAll(false)">
                            <i class="bi bi-x-circle"></i>Batal Pilih
                        </button>
                    </div>
                </div>

                <!-- Table -->
                <div class="warga-scroll">
                    <table class="table warga-table">
                        <thead>
                            <tr>
                                <th style="width:42px;">
                                    <input type="checkbox" class="form-check-input" id="checkAllBox" onchange="toggleAll(this)">
                                </th>
                                <th style="width:40px;">No</th>
                                <th>Nama Lengkap</th>
                                <th class="col-status" style="width:130px;">Status</th>
                                <th class="col-nik">NIK</th>
                                <th class="col-alamat">No. KK</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(empty($warga)): ?>
                            <tr>
                                <td colspan="6" class="text-center py-5 text-muted">
                                    <i class="bi bi-people fs-2 d-block mb-2 opacity-50"></i>
                                    Tidak ada data warga
                                </td>
                            </tr>
                            <?php else: ?>
                                <?php $no = 1; foreach($warga as $w):
                                    $is_kk = (isset($w->status_hubungan) && $w->status_hubungan === 'kepala_keluarga');
                                    $status_label = '';
                                    $status_map = [
                                        'kepala_keluarga' => 'Kepala KK',
                                        'istri'           => 'Istri',
                                        'anak'            => 'Anak',
                                        'cucu'            => 'Cucu',
                                        'orang_tua'       => 'Orang Tua',
                                        'mertua'          => 'Mertua',
                                        'famili_lain'     => 'Famili Lain',
                                        'pembantu'        => 'Pembantu',
                                        'lainnya'         => 'Lainnya',
                                    ];
                                    $sh = isset($w->status_hubungan) ? $w->status_hubungan : '';
                                    $status_label = isset($status_map[$sh]) ? $status_map[$sh] : 'Lainnya';
                                ?>
                                <tr class="warga-row <?php echo $is_kk ? 'row-kk' : 'row-anggota'; ?>"
                                    data-type="<?php echo $is_kk ? 'kk' : 'anggota'; ?>">
                                    <td>
                                        <input type="checkbox" name="warga_ids[]" value="<?php echo $w->id; ?>"
                                               class="form-check-input warga-check <?php echo $is_kk ? 'check-kk' : 'check-anggota'; ?>">
                                    </td>
                                    <td class="text-muted" style="font-size:.8rem;"><?php echo $no++; ?></td>
                                    <td>
                                        <div class="d-flex align-items-center gap-2">
                                            <?php if($is_kk): ?>
                                            <span style="width:26px;height:26px;background:#d1fae5;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;">
                                                <i class="bi bi-house-fill" style="font-size:.65rem;color:#065f46;"></i>
                                            </span>
                                            <?php else: ?>
                                            <span style="width:26px;height:26px;background:#f3f4f6;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;">
                                                <i class="bi bi-person" style="font-size:.65rem;color:#9ca3af;"></i>
                                            </span>
                                            <?php endif; ?>
                                            <strong style="font-size:.85rem;"><?php echo htmlspecialchars($w->nama_lengkap); ?></strong>
                                        </div>
                                    </td>
                                    <td class="col-status">
                                        <?php if($is_kk): ?>
                                        <span class="badge-kk"><i class="bi bi-house-fill"></i><?php echo $status_label; ?></span>
                                        <?php else: ?>
                                        <span class="badge-anggota"><?php echo $status_label; ?></span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="col-nik text-muted" style="font-size:.8rem;"><?php echo $w->nik; ?></td>
                                    <td class="col-alamat text-muted" style="font-size:.8rem;">
                                        <?php echo isset($w->no_kk_kk) ? $w->no_kk_kk : (isset($w->no_kk) ? $w->no_kk : '-'); ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Legend -->
                <div class="d-flex align-items-center gap-3 mt-2" style="font-size:.75rem; color:#6b7280;">
                    <span class="d-flex align-items-center gap-1">
                        <span class="badge-kk"><i class="bi bi-house-fill"></i>Kepala KK</span>
                        &nbsp;= Kepala Keluarga
                    </span>
                    <span class="d-flex align-items-center gap-1">
                        <span class="badge-anggota">Anggota</span>
                        &nbsp;= Anggota keluarga lainnya
                    </span>
                </div>

            </div>
        </div>

        <!-- ===== Summary ===== -->
        <div class="summary-bar mb-4">
            <div class="summary-cell">
                <div class="s-label"><i class="bi bi-person-check me-1"></i>Terpilih</div>
                <div class="s-value" id="selectedCount">0</div>
            </div>
            <div class="summary-cell">
                <div class="s-label"><i class="bi bi-house me-1"></i>Kepala KK Terpilih</div>
                <div class="s-value blue" id="selectedKKCount">0</div>
            </div>
            <div class="summary-cell">
                <div class="s-label"><i class="bi bi-cash-stack me-1"></i>Estimasi Total</div>
                <div class="s-value green" id="estimasiTotal">Rp 0</div>
            </div>
        </div>

        <!-- ===== Action Bar ===== -->
        <div class="action-bar">
            <a href="<?php echo base_url('iuran'); ?>" class="btn-back btn">
                <i class="bi bi-arrow-left"></i>Kembali
            </a>
           <button type="button" class="btn-generate btn" id="btnSubmit" disabled
        onclick="showModalGenerate()">
    <i class="bi bi-file-earmark-check"></i>
    Generate <span id="countSubmit">0</span> Tagihan
</button>
        </div>

    </form>
<!-- Modal Konfirmasi Generate -->
<div class="modal fade" id="modalConfirmGenerate" 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;font-family:inherit;">
      <div class="modal-header" style="background:linear-gradient(135deg,#0b7a6e,#20c997);border:none;padding:18px 20px;">
        <div class="d-flex align-items-center gap-2">
          <div style="width:36px;height:36px;background:rgba(255,255,255,.2);border-radius:10px;display:flex;align-items:center;justify-content:center;">
            <i class="bi bi-file-earmark-check-fill" style="color:#fff;font-size:1rem;"></i>
          </div>
          <h6 class="modal-title mb-0" style="color:#fff;font-weight:700;font-size:.95rem;">Konfirmasi Generate Tagihan</h6>
        </div>
        <button type="button" class="btn-close btn-close-white btn-sm" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" style="padding:20px;">
        <p style="font-size:.85rem;color:#334155;margin-bottom:12px;">Tagihan akan digenerate untuk:</p>
        <div style="background:#f0fdf9;border:1.5px solid #a7f3d0;border-radius:10px;padding:12px 16px;display:flex;flex-direction:column;gap:8px;">
          <div style="display:flex;justify-content:space-between;align-items:center;font-size:.83rem;">
            <span style="color:#6b7280;"><i class="bi bi-person-check me-1"></i>Warga dipilih</span>
            <strong style="color:#065f46;" id="modalCountWarga">0 orang</strong>
          </div>
          <div style="display:flex;justify-content:space-between;align-items:center;font-size:.83rem;">
            <span style="color:#6b7280;"><i class="bi bi-house me-1"></i>Kepala KK</span>
            <strong style="color:#1d4ed8;" id="modalCountKK">0 KK</strong>
          </div>
          <div style="border-top:1px solid #d1fae5;padding-top:8px;display:flex;justify-content:space-between;align-items:center;font-size:.85rem;">
            <span style="color:#6b7280;"><i class="bi bi-cash-stack me-1"></i>Estimasi Total</span>
            <strong style="color:#20c997;font-size:.95rem;" id="modalEstimasi">Rp 0</strong>
          </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>
          Tagihan akan berstatus <strong>PENDING</strong> dan tidak dapat dibatalkan massal.
        </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>
        <button type="button" id="btnKonfirmasiGenerate"
          style="border-radius:8px;border:none;font-size:.82rem;font-weight:700;color:#fff;padding:7px 18px;flex:1;background:linear-gradient(135deg,#0b7a6e,#20c997);box-shadow:0 4px 12px rgba(32,201,151,.28);cursor:pointer;">
          <i class="bi bi-file-earmark-check me-1"></i>Ya, Generate
        </button>
      </div>
    </div>
  </div>
</div>

</div>

<script>
// ===== AUTO-FILL NOMINAL =====
document.getElementById('jenisIuran').addEventListener('change', function() {
    var nominal = this.options[this.selectedIndex].getAttribute('data-nominal');
    if (nominal) {
        document.getElementById('nominal').value = nominal;
        updateEstimasi();
    }
});

// ===== TOGGLE ALL =====
function toggleAll(src) {
    var visibleRows = document.querySelectorAll('.warga-row:not([style*="display: none"]):not([style*="display:none"])');
    visibleRows.forEach(function(row) {
        var cb = row.querySelector('.warga-check');
        if(cb) {
            cb.checked = src.checked;
            row.classList.toggle('selected', src.checked);
        }
    });
    updateCount();
}

function checkAll(checked) {
    document.getElementById('checkAllBox').checked = checked;
    var visibleRows = document.querySelectorAll('.warga-row:not([style*="display: none"]):not([style*="display:none"])');
    visibleRows.forEach(function(row) {
        var cb = row.querySelector('.warga-check');
        if(cb) {
            cb.checked = checked;
            row.classList.toggle('selected', checked);
        }
    });
    updateCount();
}

// ===== PILIH KEPALA KK (TOMBOL UTAMA BARU) =====
function checkKepalaKK() {
    // Reset semua dulu
    document.querySelectorAll('.warga-check').forEach(function(cb) {
        cb.checked = false;
        cb.closest('tr').classList.remove('selected');
    });

    // Centang semua kepala KK (termasuk yang tersembunyi oleh filter)
    document.querySelectorAll('.check-kk').forEach(function(cb) {
        cb.checked = true;
        cb.closest('tr').classList.add('selected');
    });

    // Reset filter ke "semua" supaya kepala KK yang dipilih terlihat
    filterWarga('all', document.querySelector('.filter-tab'));

    document.getElementById('checkAllBox').checked = false;
    updateCount();
}

// ===== FILTER TAMPILAN =====
function filterWarga(type, btn) {
    // Update active tab
    document.querySelectorAll('.filter-tab').forEach(function(t) {
        t.classList.remove('active', 'active-kk', 'active-all');
        t.style.background = '';
        t.style.borderColor = '';
        t.style.color = '';
    });
    if(type === 'kk') {
        btn.classList.add('active', 'active-kk');
    } else {
        btn.classList.add('active', 'active-all');
    }

    // Tampil/sembunyikan baris
    document.querySelectorAll('.warga-row').forEach(function(row) {
        var rowType = row.getAttribute('data-type');
        if(type === 'all') {
            row.style.display = '';
        } else if(type === 'kk' && rowType === 'kk') {
            row.style.display = '';
        } else if(type === 'anggota' && rowType === 'anggota') {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });

    document.getElementById('checkAllBox').checked = false;
    updateCount();
}

// ===== UPDATE COUNT & ESTIMASI =====
function updateCount() {
    var allChecked = document.querySelectorAll('.warga-check:checked');
    var kkChecked  = document.querySelectorAll('.check-kk:checked');
    var count  = allChecked.length;
    var kkCount = kkChecked.length;

    document.getElementById('selectedCount').textContent = count;
    document.getElementById('selectedKKCount').textContent = kkCount;
    document.getElementById('countSubmit').textContent = count;
    document.getElementById('btnSubmit').disabled = (count === 0);
    updateEstimasi(count);
}

function updateEstimasi(count) {
    if(count === undefined) {
        count = document.querySelectorAll('.warga-check:checked').length;
    }
    
    var b1 = parseInt(document.getElementById('bulanMulai').value, 10);
    var t1 = parseInt(document.getElementById('tahunMulai').value, 10);
    var b2 = parseInt(document.getElementById('bulanSelesai').value, 10);
    var t2 = parseInt(document.getElementById('tahunSelesai').value, 10);
    
    // Hitung jumlah bulan (t2*12 + b2) - (t1*12 + b1) + 1
    var totalMonths = ((t2 * 12) + b2) - ((t1 * 12) + b1) + 1;
    if (totalMonths < 1) totalMonths = 0;

    var nominal = parseInt(document.getElementById('nominal').value) || 0;
    var totalTagihan = count * totalMonths;
    var totalNominal = totalTagihan * nominal;

    document.getElementById('estimasiTotal').textContent = 'Rp ' + totalNominal.toLocaleString('id-ID');
    document.getElementById('selectedCount').textContent = count;
    document.getElementById('countSubmit').textContent = totalTagihan;
    
    // Tombol aktif jika ada tagihan yang akan dibuat dan range valid
    var btnSubmit = document.getElementById('btnSubmit');
    if(btnSubmit) {
        btnSubmit.disabled = (totalTagihan === 0 || totalMonths < 1);
    }
}

// ===== ROW CLICK TOGGLE =====
document.querySelectorAll('.warga-row').forEach(function(row) {
    row.addEventListener('click', function(e) {
        if (e.target.type === 'checkbox') return;
        var cb = this.querySelector('.warga-check');
        cb.checked = !cb.checked;
        this.classList.toggle('selected', cb.checked);
        updateCount();
    });
});

document.querySelectorAll('.warga-check').forEach(function(cb) {
    cb.addEventListener('change', function() {
        this.closest('tr').classList.toggle('selected', this.checked);
        updateCount();
    });
});

document.getElementById('nominal').addEventListener('input', function() { updateEstimasi(); });

// Init
updateCount();


// ===== MODAL GENERATE =====
var _bsModalGenerate = null;

function showModalGenerate() {
  var count    = document.querySelectorAll('.warga-check:checked').length;
  var kkCount  = document.querySelectorAll('.check-kk:checked').length;
  var nominal  = parseInt(document.getElementById('nominal').value) || 0;
  var total    = count * nominal;

  document.getElementById('modalCountWarga').textContent = count + ' orang';
  document.getElementById('modalCountKK').textContent    = kkCount + ' KK';
  document.getElementById('modalEstimasi').textContent   = 'Rp ' + total.toLocaleString('id-ID');

  var modalEl = document.getElementById('modalConfirmGenerate');
  if(!_bsModalGenerate) _bsModalGenerate = new bootstrap.Modal(modalEl);
  _bsModalGenerate.show();
}

document.addEventListener('DOMContentLoaded', function() {
  var btnKonfirmasi = document.getElementById('btnKonfirmasiGenerate');
  if(btnKonfirmasi) {
    btnKonfirmasi.addEventListener('click', function() {
      if(_bsModalGenerate) _bsModalGenerate.hide();
      document.querySelector('form').submit();
    });
  }
});
</script>