<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:.88rem;padding:9px 12px}
.bm-header{margin-bottom:24px}
.bm-header h4{font-size:1.15rem;font-weight:800;color:#111827;margin:0}
.bm-header p{font-size:.82rem;color:#6b7280;margin:3px 0 0}
.section-card{border-radius:14px;border:none;box-shadow:0 1px 6px rgba(0,0,0,.07);overflow:hidden;margin-bottom:16px}
.sc-hdr{padding:13px 20px;display:flex;align-items:center;gap:8px;border-bottom:1px solid #f1f3f5;background:#fff}
.sc-hdr .ttl{font-size:.82rem;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#6b7280}
.sc-hdr i{color:#20c997;font-size:.9rem}
.sc-body{padding:20px;background:#fff}
.sgrid{display:grid;grid-template-columns:1fr 1fr;gap:16px}
.sbar-wrap{background:linear-gradient(135deg,#f0fdf9,#ecfdf5);border:1.5px solid #a7f3d0;border-radius:12px;padding:14px 18px;display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:16px;flex-wrap:wrap}
.sbar-lbl{font-size:.8rem;font-weight:600;color:#065f46}
.sbar-amt{font-size:1.15rem;font-weight:800;color:#059669}
.sbar-cnt{font-size:.78rem;color:#6b7280;margin-top:2px}
.sbar-det{display:flex;gap:14px;margin-top:3px}
.sbar-det span{font-size:.74rem;color:#6b7280}
.sbar-det b{color:#374151}
.srch-bar{padding:12px 16px;background:#f8fffe;border-bottom:1.5px solid #e5e7eb;display:flex;align-items:center;gap:10px;flex-wrap:wrap}
.srch-wrap{position:relative;flex:1;min-width:220px;max-width:360px}
.srch-wrap i{position:absolute;left:10px;top:50%;transform:translateY(-50%);color:#9ca3af;font-size:.85rem;pointer-events:none}
.srch-wrap input{padding-left:32px!important;border:1.5px solid #e5e7eb;border-radius:8px;font-size:.85rem;width:100%;height:37px;outline:none}
.srch-wrap input:focus{border-color:#20c997;box-shadow:0 0 0 3px rgba(32,201,151,.12)}
.srch-hint{font-size:.74rem;color:#9ca3af}
.chips-row{padding:10px 16px;background:#fff;border-bottom:1px solid #f1f3f5;display:flex;flex-wrap:wrap;gap:6px}
.chip{display:inline-flex;align-items:center;gap:4px;padding:4px 12px;border-radius:999px;font-size:.76rem;font-weight:700;border:1.5px solid #e5e7eb;background:#fff;color:#374151;cursor:pointer;transition:all .15s;white-space:nowrap}
.chip:hover{border-color:#20c997;color:#0d9488;background:#f0fdf9}
.chip.on{background:#20c997;border-color:#20c997;color:#fff}
.chip .cn{background:rgba(0,0,0,.1);border-radius:999px;padding:1px 6px;font-size:.68rem}
.chip.on .cn{background:rgba(255,255,255,.25)}
.tg-rt{font-size:.58rem;background:#dbeafe;color:#1d4ed8;border-radius:3px;padding:1px 4px}
.tg-ar{font-size:.58rem;background:#fef3c7;color:#b45309;border-radius:3px;padding:1px 4px}
.tab-nav{display:flex;border-bottom:2px solid #e5e7eb;padding:0 20px;background:#fff}
.tbtn{display:inline-flex;align-items:center;gap:6px;padding:11px 18px;font-size:.82rem;font-weight:700;border:none;background:none;color:#6b7280;cursor:pointer;border-bottom:2.5px solid transparent;margin-bottom:-2px;transition:all .2s;white-space:nowrap}
.tbtn:hover{color:#0d9488}
.tbtn.on{color:#20c997;border-bottom-color:#20c997}
.tbtn .tb{display:inline-flex;align-items:center;justify-content:center;min-width:19px;height:19px;border-radius:999px;font-size:.67rem;font-weight:800;background:#e5e7eb;color:#6b7280;padding:0 5px}
.tbtn.on .tb{background:#20c997;color:#fff}
.tpane{display:none}
.tpane.show{display:block}
.itable th{font-size:.72rem;text-transform:uppercase;letter-spacing:.04em;color:#6b7280;font-weight:700;padding:9px 16px;background:#f8fffe;border-bottom:1.5px solid #e5e7eb;white-space:nowrap}
.itable td{padding:9px 16px;vertical-align:middle;font-size:.84rem;border-bottom:1px solid #f3f4f6}
.itable tbody tr:last-child td{border-bottom:none}
.itable tbody tr:hover{background:#f8fffe}
.itable tr.ck{background:#f0fdf9!important}
.itable tr.shRT td{background:#eff6ff!important;font-size:.71rem;font-weight:800;text-transform:uppercase;letter-spacing:.06em;color:#1d4ed8;padding:7px 16px!important;border-bottom:1px solid #bfdbfe!important}
.itable tr.shAR td{background:#fffbeb!important;font-size:.71rem;font-weight:800;text-transform:uppercase;letter-spacing:.06em;color:#b45309;padding:7px 16px!important;border-bottom:1px solid #fde68a!important}
.bdg-rt{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:999px;font-size:.69rem;font-weight:700;background:#dbeafe;color:#1d4ed8;border:1px solid #bfdbfe}
.bdg-ar{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:999px;font-size:.69rem;font-weight:700;background:#fef3c7;color:#b45309;border:1px solid #fde68a}
.form-check-input{width:17px;height:17px;border:1.5px solid #d1d5db;border-radius:4px;cursor:pointer}
.form-check-input:checked{background-color:#20c997;border-color:#20c997}
.form-check-input:focus{box-shadow:0 0 0 3px rgba(32,201,151,.15);border-color:#20c997}
.wrh{display:flex;align-items:center;justify-content:space-between;padding:10px 16px;background:linear-gradient(135deg,#f0fdf9,#ecfdf5);border-bottom:1.5px solid #a7f3d0;flex-wrap:wrap;gap:8px}
.wrh-name{font-size:.88rem;font-weight:800;color:#065f46}
.wrh-meta{font-size:.74rem;color:#6b7280}
.btn-pa{display:inline-flex;align-items:center;gap:5px;padding:6px 14px;border-radius:8px;font-size:.78rem;font-weight:700;border:1.5px solid #20c997;background:#fff;color:#20c997;cursor:pointer;transition:all .2s;white-space:nowrap}
.btn-pa:hover,.btn-pa.on{background:#20c997;color:#fff}
.act-bar{display:flex;gap:10px;padding:14px 20px;border-top:1.5px solid #f1f3f5;background:#f9fafb;align-items:center;justify-content:space-between;flex-wrap:wrap}
.btn-bk{display:inline-flex;align-items:center;gap:6px;padding:9px 18px;border-radius:8px;font-size:.85rem;font-weight:700;border:1.5px solid #e5e7eb;background:#fff;color:#6b7280;text-decoration:none;transition:all .2s}
.btn-bk:hover{border-color:#9ca3af;color:#374151}
.btn-pr{display:inline-flex;align-items:center;gap:7px;padding:9px 22px;border-radius:8px;font-size:.88rem;font-weight:700;border:none;background:#20c997;color:#fff;cursor:pointer;transition:all .2s;box-shadow:0 2px 8px rgba(32,201,151,.28)}
.btn-pr:hover:not(:disabled){background:#0fa37f;transform:translateY(-1px)}
.btn-pr:disabled{background:#d1d5db;color:#9ca3af;box-shadow:none;cursor:not-allowed}
.btn-sa{display:inline-flex;align-items:center;gap:5px;padding:7px 13px;border-radius:8px;font-size:.8rem;font-weight:700;border:1.5px solid #20c997;background:#fff;color:#20c997;cursor:pointer;transition:all .2s}
.btn-sa:hover{background:#f0fdf9}
.empty-st{text-align:center;padding:36px 20px;color:#9ca3af}
.empty-st i{font-size:1.8rem;display:block;margin-bottom:8px;opacity:.5}
.empty-st p{font-size:.82rem;margin:0}
@media(max-width:767px){.sgrid{grid-template-columns:1fr}.act-bar{flex-direction:column}.btn-bk,.btn-pr{width:100%;justify-content:center}.sbar-wrap{flex-direction:column}}
</style>

<div class="container-fluid px-0 px-md-3 py-3">
<div class="bm-header">
  <div class="d-flex align-items-center gap-2 mb-1">
    <div style="width:36px;height:36px;background:#d1fae5;border-radius:9px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
      <i class="bi bi-cash-stack" style="color:#059669;font-size:1rem"></i>
    </div>
    <h4>Pembayaran Iuran Massal</h4>
  </div>
  <p>Pilih tagihan iuran RT dan/atau arisan — cari nama warga untuk bayar semua tagihannya sekaligus</p>
</div>

<?php $ada_rt=!empty($tagihan); $ada_ar=!empty($tagihan_arisan);
if(!$ada_rt && !$ada_ar): ?>
<div class="section-card"><div class="empty-st"><i class="bi bi-inbox"></i><p>Tidak ada tagihan pending</p></div></div>
<?php else: ?>

<form id="fMassal" action="<?php echo base_url('iuran/proses_bayar_massal') ?>" method="post">

<div class="section-card">
  <div class="sc-hdr"><i class="bi bi-gear-fill"></i><span class="ttl">Pengaturan Pembayaran</span></div>
  <div class="sc-body">
    <div class="sgrid">
      <div>
        <label class="form-label small fw-semibold text-muted mb-1">Metode Pembayaran <span class="text-danger">*</span></label>
        <select name="metode_pembayaran" class="form-select" id="selM" required>
          <option value="Tunai">💵 Tunai</option>
          <option value="Transfer Bank">🏦 Transfer Bank</option>
          <option value="E-Wallet">📱 E-Wallet</option>
        </select>
      </div>
      <div>
        <label class="form-label small fw-semibold text-muted mb-1">Masuk ke Kas <span class="text-danger">*</span></label>
        <select name="master_kas_id" class="form-select" id="selK" required>
          <option value="">— Pilih Kas Tujuan —</option>
          <?php foreach($kas_list as $mk):
            $ic=$mk->jenis==='bank'?'🏦':($mk->jenis==='ewallet'?'📱':'💵'); ?>
          <option value="<?php echo $mk->id ?>" data-jenis="<?php echo $mk->jenis ?>"><?php echo $ic.' '.$mk->nama.' ('.$mk->kode.')' ?></option>
          <?php endforeach ?>
        </select>
      </div>
    </div>
  </div>
</div>

<div class="sbar-wrap">
  <div>
    <div class="sbar-lbl"><i class="bi bi-receipt me-1"></i>Total Terpilih</div>
    <div class="sbar-cnt" id="elCnt">0 tagihan dipilih</div>
    <div class="sbar-det">
      <span>Iuran RT: <b id="elCntR">0</b></span>
      <span>Arisan: <b id="elCntA">0</b></span>
    </div>
  </div>
  <div><div class="sbar-amt" id="elTot">Rp 0</div></div>
</div>

<div class="section-card">
  <div class="sc-hdr">
    <i class="bi bi-list-check"></i>
    <span class="ttl">Daftar Tagihan Pending</span>
    <button type="button" class="btn-sa ms-auto" id="btnSA"><i class="bi bi-check-all"></i> Pilih Semua</button>
  </div>

  <div class="srch-bar">
    <div class="srch-wrap">
      <i class="bi bi-search"></i>
      <input type="text" id="inpS" placeholder="Ketik nama warga…" autocomplete="off">
    </div>
    <span class="srch-hint"><i class="bi bi-lightbulb me-1"></i>Saat mencari, tagihan RT &amp; arisan warga tampil bersama</span>
  </div>

  <div class="chips-row" id="chipsRow">
    <button type="button" class="chip on" data-wid="all">
      <i class="bi bi-people-fill"></i> Semua <span class="cn"><?php echo count($tagihan)+count($tagihan_arisan) ?></span>
    </button>
    <?php foreach($warga_map as $wid=>$wn):
      $cr=0; foreach($tagihan as $t){ if($t->warga_id==$wid) $cr++; }
      $ca=0; foreach($tagihan_arisan as $t){ if($t->warga_id==$wid) $ca++; }
    ?>
    <button type="button" class="chip" data-wid="<?php echo $wid ?>" data-nama="<?php echo strtolower(htmlspecialchars($wn)) ?>">
      <?php echo htmlspecialchars(explode(' ',$wn)[0]) ?> <span class="cn"><?php echo $cr+$ca ?></span>
      <?php if($cr): ?><span class="tg-rt">RT</span><?php endif ?>
      <?php if($ca): ?><span class="tg-ar">A</span><?php endif ?>
    </button>
    <?php endforeach ?>
  </div>

  <!-- UNIFIED VIEW -->
  <div id="divU" style="display:none">
    <div id="divWRH" class="wrh" style="display:none">
      <div>
        <div class="wrh-name" id="wrhN"></div>
        <div class="wrh-meta" id="wrhM"></div>
      </div>
      <button type="button" class="btn-pa" id="btnPA"><i class="bi bi-check-all"></i> Pilih Semua Tagihan Ini</button>
    </div>
    <div class="table-responsive">
      <table class="table itable mb-0">
        <thead><tr>
          <th style="width:44px"><input type="checkbox" class="form-check-input" id="saU"></th>
          <th>Nama Warga</th><th>Jenis / Keterangan</th><th>Periode</th><th class="text-end">Nominal</th>
        </tr></thead>
        <tbody id="tbU"></tbody>
        <tfoot><tr style="background:#f8fffe">
          <td colspan="4" class="text-end fw-bold" style="font-size:.83rem;color:#374151;padding:10px 16px">Total tampilan ini:</td>
          <td class="text-end fw-bold" style="color:#059669;padding:10px 16px" id="elTU">Rp 0</td>
        </tr></tfoot>
      </table>
    </div>
  </div>

  <!-- TABBED VIEW -->
  <div id="divT">
    <div class="tab-nav">
      <button type="button" class="tbtn on" data-tab="pRT"><i class="bi bi-house-fill"></i> Iuran RT <span class="tb"><?php echo count($tagihan) ?></span></button>
      <button type="button" class="tbtn" data-tab="pAR"><i class="bi bi-people-fill"></i> Iuran Arisan <span class="tb"><?php echo count($tagihan_arisan) ?></span></button>
    </div>

    <div class="tpane show" id="pRT">
      <?php if(!$ada_rt): ?>
      <div class="empty-st"><i class="bi bi-check-circle"></i><p>Semua iuran RT sudah lunas</p></div>
      <?php else: ?>
      <div class="table-responsive">
        <table class="table itable mb-0">
          <thead><tr>
            <th style="width:44px"><input type="checkbox" class="form-check-input" id="saRT"></th>
            <th>Nama Warga</th><th>Jenis Iuran</th><th>Periode</th><th class="text-end">Nominal</th>
          </tr></thead>
          <tbody>
            <?php $bl=['','Jan','Feb','Mar','Apr','Mei','Jun','Jul','Ags','Sep','Okt','Nov','Des'];
            foreach($tagihan as $t): ?>
            <tr class="trR" data-wid="<?php echo $t->warga_id ?>" data-nama="<?php echo strtolower(htmlspecialchars($t->nama_lengkap)) ?>">
              <td><input type="checkbox" class="form-check-input cbR" name="tagihan_ids[]" value="<?php echo $t->id ?>" data-nom="<?php echo $t->nominal ?>" data-id="<?php echo $t->id ?>"></td>
              <td><div class="fw-semibold"><?php echo htmlspecialchars($t->nama_lengkap) ?></div><div style="font-size:.72rem;color:#9ca3af"><?php echo $t->nik ?></div></td>
              <td><span class="bdg-rt"><i class="bi bi-house"></i> <?php echo htmlspecialchars($t->nama_iuran) ?></span></td>
              <td><?php echo $bl[(int)$t->periode_bulan].' '.$t->periode_tahun ?></td>
              <td class="text-end fw-bold" style="color:#20c997">Rp <?php echo number_format($t->nominal,0,',','.') ?></td>
            </tr>
            <?php endforeach ?>
          </tbody>
          <tfoot><tr style="background:#f8fffe">
            <td colspan="4" class="text-end fw-bold" style="font-size:.83rem;color:#374151;padding:10px 16px">Total RT Terpilih:</td>
            <td class="text-end fw-bold" style="color:#059669;padding:10px 16px" id="elTR">Rp 0</td>
          </tr></tfoot>
        </table>
      </div>
      <?php endif ?>
    </div>

    <div class="tpane" id="pAR">
      <?php if(!$ada_ar): ?>
      <div class="empty-st"><i class="bi bi-check-circle"></i><p>Tidak ada iuran arisan belum bayar</p></div>
      <?php else: ?>
      <div class="table-responsive">
        <table class="table itable mb-0">
          <thead><tr>
            <th style="width:44px"><input type="checkbox" class="form-check-input" id="saAR"></th>
            <th>Nama Warga</th><th>Nama Arisan</th><th>Pertemuan</th><th class="text-end">Nominal</th>
          </tr></thead>
          <tbody>
            <?php foreach($tagihan_arisan as $t): ?>
            <tr class="trA" data-wid="<?php echo $t->warga_id ?>" data-nama="<?php echo strtolower(htmlspecialchars($t->nama_lengkap)) ?>">
              <td><input type="checkbox" class="form-check-input cbA" name="arisan_ids[]" value="<?php echo $t->id ?>" data-nom="<?php echo $t->nominal ?>" data-id="<?php echo $t->id ?>"></td>
              <td><div class="fw-semibold"><?php echo htmlspecialchars($t->nama_lengkap) ?></div><div style="font-size:.72rem;color:#9ca3af"><?php echo $t->nik ?></div></td>
              <td><span class="bdg-ar"><i class="bi bi-people"></i> <?php echo htmlspecialchars($t->nama_iuran) ?></span></td>
              <td>Ke-<?php echo $t->pertemuan_ke ?> <span style="font-size:.76rem;color:#9ca3af"><?php echo date('d/m/Y',strtotime($t->tanggal_pertemuan)) ?></span></td>
              <td class="text-end fw-bold" style="color:#20c997">Rp <?php echo number_format($t->nominal,0,',','.') ?></td>
            </tr>
            <?php endforeach ?>
          </tbody>
          <tfoot><tr style="background:#f8fffe">
            <td colspan="4" class="text-end fw-bold" style="font-size:.83rem;color:#374151;padding:10px 16px">Total Arisan Terpilih:</td>
            <td class="text-end fw-bold" style="color:#059669;padding:10px 16px" id="elTA">Rp 0</td>
          </tr></tfoot>
        </table>
      </div>
      <?php endif ?>
    </div>
  </div>

  <div class="act-bar">
    <a href="<?php echo base_url('iuran') ?>" class="btn-bk"><i class="bi bi-arrow-left"></i> Kembali</a>
    <button type="submit" class="btn-pr" id="btnPr" disabled>
      <i class="bi bi-check-circle-fill"></i> <span id="btnLbl">Proses Pembayaran</span>
    </button>
  </div>
</div>

</form>
<?php endif ?>
</div>

<script>
(function(){

/* ─── DATA PHP ─────────────────────────────────────────────────────────── */
var DRT=<?php
  $o=[];$bl=['','Jan','Feb','Mar','Apr','Mei','Jun','Jul','Ags','Sep','Okt','Nov','Des'];
  foreach($tagihan as $t){$o[]=['id'=>(int)$t->id,'wid'=>(int)$t->warga_id,'nama'=>$t->nama_lengkap,'nik'=>$t->nik,'lbl'=>$t->nama_iuran,'sub'=>$bl[(int)$t->periode_bulan].' '.$t->periode_tahun,'nom'=>(int)$t->nominal];}
  echo json_encode($o);
?>;
var DAR=<?php
  $o2=[];
  foreach($tagihan_arisan as $t){$o2[]=['id'=>(int)$t->id,'wid'=>(int)$t->warga_id,'nama'=>$t->nama_lengkap,'nik'=>$t->nik,'lbl'=>$t->nama_iuran,'sub'=>'Ke-'.$t->pertemuan_ke.' '.date('d/m/Y',strtotime($t->tanggal_pertemuan)),'nom'=>(int)$t->nominal];}
  echo json_encode($o2);
?>;

/* ─── WAIT DOM ─────────────────────────────────────────────────────────── */
function ready(fn){ if(document.readyState!=='loading'){fn();}else{document.addEventListener('DOMContentLoaded',fn);} }

ready(function(){

/* ─── STATE ──────────────────────────────────────────────────────────── */
var sR=new Set(), sA=new Set(), mode='tab', curWid=null, curKw='', curTab='pRT';

/* ─── REFS ───────────────────────────────────────────────────────────── */
var divU  = document.getElementById('divU');
var divT  = document.getElementById('divT');
var tbU   = document.getElementById('tbU');
var divWRH= document.getElementById('divWRH');
var inpS  = document.getElementById('inpS');
var saU   = document.getElementById('saU');
var saRT  = document.getElementById('saRT');
var saAR  = document.getElementById('saAR');
var btnPA = document.getElementById('btnPA');
var btnSA = document.getElementById('btnSA');
var selM  = document.getElementById('selM');
var selK  = document.getElementById('selK');
var chips = document.querySelectorAll('.chip');

/* ─── UTIL ───────────────────────────────────────────────────────────── */
function rp(n){return 'Rp '+parseInt(n||0).toLocaleString('id-ID');}
function esc(s){return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');}

function getFiltRT(){
  if(curWid) return DRT.filter(function(d){return d.wid===parseInt(curWid);});
  return DRT.filter(function(d){return d.nama.toLowerCase().indexOf(curKw)>=0;});
}
function getFiltAR(){
  if(curWid) return DAR.filter(function(d){return d.wid===parseInt(curWid);});
  return DAR.filter(function(d){return d.nama.toLowerCase().indexOf(curKw)>=0;});
}

/* ─── RECALC ─────────────────────────────────────────────────────────── */
function recalc(){
  var tR=0,tA=0;
  sR.forEach(function(id){var d=DRT.find(function(x){return x.id===id;});if(d)tR+=d.nom;});
  sA.forEach(function(id){var d=DAR.find(function(x){return x.id===id;});if(d)tA+=d.nom;});
  var tot=tR+tA, cnt=sR.size+sA.size;
  document.getElementById('elTot').textContent=rp(tot);
  document.getElementById('elCnt').textContent=cnt+' tagihan dipilih';
  document.getElementById('elCntR').textContent=sR.size;
  document.getElementById('elCntA').textContent=sA.size;
  var eR=document.getElementById('elTR'),eA=document.getElementById('elTA');
  if(eR)eR.textContent=rp(tR); if(eA)eA.textContent=rp(tA);
  var bp=document.getElementById('btnPr');
  bp.disabled=cnt===0;
  document.getElementById('btnLbl').textContent=cnt>0?'Proses '+cnt+' Pembayaran ('+rp(tot)+')':'Proses Pembayaran';

  // unified footer
  var uT=0;
  if(tbU){tbU.querySelectorAll('.uCB:checked').forEach(function(cb){uT+=parseInt(cb.dataset.nom)||0;});}
  var eu=document.getElementById('elTU');if(eu)eu.textContent=rp(uT);

  // sync header cb tabbed
  hdrSync(saRT,'.trR .cbR'); hdrSync(saAR,'.trA .cbA');
}

function hdrSync(el,sel){
  if(!el)return;
  var all=document.querySelectorAll(sel);
  if(!all.length){el.checked=false;el.indeterminate=false;return;}
  var n=Array.from(all).filter(function(i){return i.checked;}).length;
  el.checked=n===all.length; el.indeterminate=n>0&&n<all.length;
}

/* ─── RENDER UNIFIED ─────────────────────────────────────────────────── */
function renderUnified(){
  var fR=getFiltRT(), fA=getFiltAR();
  tbU.innerHTML='';

  if(curWid){
    var s=fR[0]||fA[0]||{};
    document.getElementById('wrhN').textContent=s.nama||'';
    document.getElementById('wrhM').textContent='NIK: '+(s.nik||'')+' · '+fR.length+' iuran RT · '+fA.length+' arisan';
    divWRH.style.display='flex';
    refreshPA(fR,fA);
  } else {
    divWRH.style.display='none';
  }

  if(fR.length){
    var h=document.createElement('tr');
    h.className='shRT';
    h.innerHTML='<td colspan="5"><i class="bi bi-house me-1"></i>Iuran RT ('+fR.length+')</td>';
    tbU.appendChild(h);
    fR.forEach(function(d){tbU.appendChild(mkRow(d,'R'));});
  }
  if(fA.length){
    var h2=document.createElement('tr');
    h2.className='shAR';
    h2.innerHTML='<td colspan="5"><i class="bi bi-people me-1"></i>Iuran Arisan ('+fA.length+')</td>';
    tbU.appendChild(h2);
    fA.forEach(function(d){tbU.appendChild(mkRow(d,'A'));});
  }
  if(!fR.length&&!fA.length){
    var nr=document.createElement('tr');
    nr.innerHTML='<td colspan="5" style="text-align:center;color:#9ca3af;padding:28px;font-size:.83rem"><i class="bi bi-search me-1"></i>Tidak ada tagihan ditemukan</td>';
    tbU.appendChild(nr);
  }

  syncSaU(fR,fA);
  recalc();
}

function mkRow(d,type){
  var isR=type==='R';
  var ck=isR?sR.has(d.id):sA.has(d.id);
  var tr=document.createElement('tr');
  if(ck)tr.classList.add('ck');
  tr.innerHTML=
    '<td><input type="checkbox" class="form-check-input uCB" data-t="'+type+'" data-id="'+d.id+'" data-nom="'+d.nom+'"'+(ck?' checked':'')+'></td>'+
    '<td><div class="fw-semibold">'+esc(d.nama)+'</div><div style="font-size:.72rem;color:#9ca3af">'+esc(d.nik)+'</div></td>'+
    '<td><span class="bdg-'+(isR?'rt':'ar')+'"><i class="bi bi-'+(isR?'house':'people')+'"></i> '+esc(d.lbl)+'</span></td>'+
    '<td>'+esc(d.sub)+'</td>'+
    '<td class="text-end fw-bold" style="color:#20c997">'+rp(d.nom)+'</td>';
  tr.querySelector('.uCB').addEventListener('change',function(){
    var id=parseInt(this.dataset.id),isRt=this.dataset.t==='R';
    if(this.checked){isRt?sR.add(id):sA.add(id);}else{isRt?sR.delete(id):sA.delete(id);}
    tr.classList.toggle('ck',this.checked);
    var tw=document.querySelector('.'+(isRt?'cbR':'cbA')+'[value="'+id+'"]');
    if(tw){tw.checked=this.checked;var row=tw.closest('tr');if(row)row.classList.toggle('ck',this.checked);}
    if(curWid)refreshPA(getFiltRT(),getFiltAR());
    syncSaU(getFiltRT(),getFiltAR());
    recalc();
  });
  return tr;
}

function syncSaU(fR,fA){
  if(!saU)return;
  var aR=fR.every(function(d){return sR.has(d.id);}),aA=fA.every(function(d){return sA.has(d.id);});
  var yR=fR.some(function(d){return sR.has(d.id);}),yA=fA.some(function(d){return sA.has(d.id);});
  var tot=fR.length+fA.length,allOk=tot>0&&aR&&aA,anyOk=yR||yA;
  saU.checked=allOk; saU.indeterminate=anyOk&&!allOk;
}

function refreshPA(fR,fA){
  if(!btnPA)return;
  var ac=fR.every(function(d){return sR.has(d.id);})&&fA.every(function(d){return sA.has(d.id);})&&(fR.length+fA.length>0);
  btnPA.classList.toggle('on',ac);
  btnPA.innerHTML=ac?'<i class="bi bi-x-circle"></i> Batal Semua':'<i class="bi bi-check-all"></i> Pilih Semua Tagihan Ini';
}

function syncTabbed(){
  document.querySelectorAll('.cbR').forEach(function(cb){
    var id=parseInt(cb.value);cb.checked=sR.has(id);
    var row=cb.closest('tr');if(row)row.classList.toggle('ck',cb.checked);
  });
  document.querySelectorAll('.cbA').forEach(function(cb){
    var id=parseInt(cb.value);cb.checked=sA.has(id);
    var row=cb.closest('tr');if(row)row.classList.toggle('ck',cb.checked);
  });
}

/* ─── SHOW UNIFIED / TABBED ──────────────────────────────────────────── */
function showUnified(){
  mode='unified';
  divU.style.display='block';
  divT.style.display='none';
  renderUnified();
}
function showTabbed(){
  mode='tab'; curWid=null; curKw='';
  divU.style.display='none';
  divT.style.display='block';
  divWRH.style.display='none';
  syncTabbed();
  recalc();
}

/* ─── EVENTS ─────────────────────────────────────────────────────────── */
// Search
inpS.addEventListener('input',function(){
  var kw=this.value.trim().toLowerCase();
  chips.forEach(function(c){c.classList.remove('on');});
  document.querySelector('.chip[data-wid="all"]').classList.add('on');
  curWid=null;
  if(kw.length>0){curKw=kw; showUnified();}
  else{showTabbed();}
});

// Chips
chips.forEach(function(chip){
  chip.addEventListener('click',function(){
    chips.forEach(function(c){c.classList.remove('on');}); this.classList.add('on');
    inpS.value=''; curKw='';
    var wid=this.dataset.wid;
    if(wid==='all'){curWid=null;showTabbed();}
    else{curWid=wid; showUnified();}
  });
});

// Select-all unified
if(saU){
  saU.addEventListener('change',function(){
    var fR=getFiltRT(),fA=getFiltAR();
    fR.forEach(function(d){saU.checked?sR.add(d.id):sR.delete(d.id);});
    fA.forEach(function(d){saU.checked?sA.add(d.id):sA.delete(d.id);});
    tbU.querySelectorAll('.uCB').forEach(function(cb){
      cb.checked=saU.checked; var row=cb.closest('tr');if(row)row.classList.toggle('ck',cb.checked);
    });
    syncTabbed(); if(curWid)refreshPA(fR,fA); recalc();
  });
}

// Pick-all warga
if(btnPA){
  btnPA.addEventListener('click',function(){
    var fR=getFiltRT(),fA=getFiltAR();
    var ac=fR.every(function(d){return sR.has(d.id);})&&fA.every(function(d){return sA.has(d.id);});
    fR.forEach(function(d){ac?sR.delete(d.id):sR.add(d.id);});
    fA.forEach(function(d){ac?sA.delete(d.id):sA.add(d.id);});
    renderUnified(); syncTabbed();
  });
}

// Pilih Semua header
if(btnSA){
  btnSA.addEventListener('click',function(){
    if(mode==='unified'){if(btnPA)btnPA.click();return;}
    var sel=curTab==='pRT'?'.cbR':'.cbA';
    var items=document.querySelectorAll(sel);
    var ac=Array.from(items).every(function(i){return i.checked;});
    items.forEach(function(cb){
      cb.checked=!ac; var id=parseInt(cb.value);
      if(curTab==='pRT'){!ac?sR.add(id):sR.delete(id);}else{!ac?sA.add(id):sA.delete(id);}
      var row=cb.closest('tr');if(row)row.classList.toggle('ck',!ac);
    });
    recalc();
  });
}

// saRT saAR
if(saRT){saRT.addEventListener('change',function(){
  document.querySelectorAll('.cbR').forEach(function(cb){
    cb.checked=saRT.checked; var id=parseInt(cb.value);saRT.checked?sR.add(id):sR.delete(id);
    var row=cb.closest('tr');if(row)row.classList.toggle('ck',cb.checked);
  });recalc();
});}
if(saAR){saAR.addEventListener('change',function(){
  document.querySelectorAll('.cbA').forEach(function(cb){
    cb.checked=saAR.checked; var id=parseInt(cb.value);saAR.checked?sA.add(id):sA.delete(id);
    var row=cb.closest('tr');if(row)row.classList.toggle('ck',cb.checked);
  });recalc();
});}

// Individual cbR cbA
document.querySelectorAll('.cbR').forEach(function(cb){
  cb.addEventListener('change',function(){
    var id=parseInt(this.value);this.checked?sR.add(id):sR.delete(id);
    var row=this.closest('tr');if(row)row.classList.toggle('ck',this.checked);recalc();
  });
});
document.querySelectorAll('.cbA').forEach(function(cb){
  cb.addEventListener('change',function(){
    var id=parseInt(this.value);this.checked?sA.add(id):sA.delete(id);
    var row=this.closest('tr');if(row)row.classList.toggle('ck',this.checked);recalc();
  });
});

// Tab switcher
document.querySelectorAll('.tbtn').forEach(function(btn){
  btn.addEventListener('click',function(){
    document.querySelectorAll('.tbtn').forEach(function(b){b.classList.remove('on');});
    document.querySelectorAll('.tpane').forEach(function(p){p.classList.remove('show');});
    this.classList.add('on'); curTab=this.dataset.tab;
    var pane=document.getElementById(curTab);if(pane)pane.classList.add('show');
  });
});

// Auto-kas
if(selM&&selK){selM.addEventListener('change',function(){
  var m=this.value.toLowerCase();
  selK.querySelectorAll('option[data-jenis]').forEach(function(o){
    var j=o.dataset.jenis;
    if((m.includes('tunai')&&j==='tunai')||(m.includes('transfer')&&j==='bank')||(m.includes('e-wallet')&&j==='ewallet'))selK.value=o.value;
  });
});}

// Modal Konfirmasi (Bootstrap 5)
var _bsModalMassal = null;

// Submit
document.getElementById('fMassal').addEventListener('submit', function(e) {
    e.preventDefault(); // Stop default submission
    
    var cnt = sR.size + sA.size;
    if(cnt === 0) { alert('Pilih minimal 1 tagihan!'); return; }
    if(!selK.value) { alert('Pilih kas tujuan!'); selK.focus(); return; }
    
    // Update text di modal
    var totText = document.getElementById('elTot').textContent;
    document.getElementById('modalMassalCount').textContent = cnt + ' tagihan';
    document.getElementById('modalMassalTotal').textContent = totText;
    
    // Show modal
    var modalEl = document.getElementById('modalConfirmMassal');
    if(!_bsModalMassal) _bsModalMassal = new bootstrap.Modal(modalEl);
    _bsModalMassal.show();
});

// Event listener untuk tombol konfirmasi di dalam modal
document.getElementById('btnConfirmMassal').addEventListener('click', function() {
    if(_bsModalMassal) _bsModalMassal.hide();
    
    var f = document.getElementById('fMassal');
    f.querySelectorAll('.hInp').forEach(function(el){el.remove();});
    document.querySelectorAll('.cbR,.cbA').forEach(function(cb){cb.checked=false;});
    
    sR.forEach(function(id){
        var cb=document.querySelector('.cbR[value="'+id+'"]');
        if(cb){cb.checked=true;}else{var inp=document.createElement('input');inp.type='hidden';inp.name='tagihan_ids[]';inp.value=id;inp.className='hInp';f.appendChild(inp);}
    });
    sA.forEach(function(id){
        var cb=document.querySelector('.cbA[value="'+id+'"]');
        if(cb){cb.checked=true;}else{var inp=document.createElement('input');inp.type='hidden';inp.name='arisan_ids[]';inp.value=id;inp.className='hInp';f.appendChild(inp);}
    });
    
    f.submit(); // Submit form asli
});

recalc();
}); // ready

})(); // IIFE
</script>

<!-- ===== MODAL KONFIRMASI PEMBAYARAN MASSAL (BOOTSTRAP 5) ===== -->
<div class="modal fade" id="modalConfirmMassal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" style="max-width:400px;">
    <div class="modal-content" style="border-radius:18px; border:none; box-shadow:0 10px 30px rgba(0,0,0,.15); overflow:hidden;">
      <div class="modal-header" style="background:linear-gradient(135deg,#059669,#10b981); border:none; padding:18px 20px;">
        <div class="d-flex align-items-center gap-2">
            <div style="width:34px; height:34px; background:rgba(255,255,255,.2); border-radius:10px; display:flex; align-items:center; justify-content:center;">
                <i class="bi bi-check-all" style="color:#fff; font-size:1.2rem;"></i>
            </div>
            <h6 class="modal-title mb-0" style="color:#fff; font-weight:700;">Konfirmasi Pembayaran</h6>
        </div>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close" style="font-size:.8rem; opacity:.8;"></button>
      </div>
      
      <div class="modal-body text-center" style="padding:25px 20px;">
        <div class="mb-3">
            <i class="bi bi-cash-coin" style="font-size:3rem; color:#10b981; opacity:.3;"></i>
        </div>
        <h5 style="font-size:1.05rem; font-weight:700; color:#111827; margin-bottom:8px;">Proses <span id="modalMassalCount">0 tagihan</span>?</h5>
        <div class="mb-3">
            <span style="font-size:.85rem; color:#6b7280;">Total yang akan dibayarkan:</span>
            <div style="font-size:1.5rem; font-weight:800; color:#059669;" id="modalMassalTotal">Rp 0</div>
        </div>
        <p style="font-size:.82rem; color:#6b7280; line-height:1.5;">
            Pastikan uang telah diterima sesuai nominal di atas. Pembayaran akan langsung dicatat sebagai <strong>LUNAS</strong>.
        </p>
      </div>
      
      <div class="modal-footer" style="border:none; padding:0 20px 20px; gap:10px;">
        <button type="button" class="btn fw-semibold" data-bs-dismiss="modal" 
                style="flex:1; border-radius:10px; border:1.5px solid #e5e7eb; color:#6b7280; font-size:.82rem; padding:8px;">
            Batal
        </button>
        <button type="button" class="btn fw-bold" id="btnConfirmMassal"
                style="flex:1; border-radius:10px; border:none; background:linear-gradient(135deg,#059669,#10b981); color:#fff; font-size:.82rem; padding:8px; box-shadow:0 4px 12px rgba(5,150,105,.25);">
            Ya, Proses Sekarang
        </button>
      </div>
    </div>
  </div>
</div>