<style>
.bpw-card { border-radius:14px; border:none; box-shadow:0 1px 6px rgba(0,0,0,.08); overflow:hidden; margin-bottom:20px; }
.bpw-card-header {
    padding:14px 20px; display:flex; align-items:center; justify-content:space-between;
    border-bottom:1.5px solid #f1f3f5; background:#fff;
}
.bpw-card-header .title { font-size:.87rem; font-weight:700; color:#374151; display:flex; align-items:center; gap:7px; }

.bpw-table th {
    font-size:.73rem; text-transform:uppercase; letter-spacing:.04em;
    color:#6b7280; font-weight:700; padding:10px 14px;
    background:#f8fffe; border-bottom:1.5px solid #e5e7eb; white-space:nowrap;
}
.bpw-table td { padding:10px 14px; vertical-align:middle; font-size:.85rem; border-bottom:1px solid #f3f4f6; }
.bpw-table tbody tr:last-child td { border-bottom:none; }
.bpw-table tbody tr:hover { background:#f8fffe; }
.bpw-table tbody tr.selected-row td { background:#ecfdf5 !important; }

.total-strip {
    background: linear-gradient(135deg,#0d9488,#14b8a6);
    border-radius:12px; padding:14px 20px;
    color:#fff; margin-bottom:20px;
}
.total-strip .label { font-size:.8rem; opacity:.85; }
.total-strip .amount { font-size:1.45rem; font-weight:800; letter-spacing:-.5px; }

/* Checkbox styling */
.check-all-btn { cursor:pointer; }
.form-check-input:checked { background-color:#0d9488; border-color:#0d9488; }
.form-check-input:focus { box-shadow:0 0 0 3px rgba(13,148,136,.15); border-color:#0d9488; }

.btn-pay {
    display:inline-flex; align-items:center; gap:7px;
    padding:11px 28px; border-radius:50px; border:none;
    background:linear-gradient(135deg,#0d9488,#14b8a6); color:#fff;
    font-size:.88rem; font-weight:700;
    box-shadow:0 3px 12px rgba(13,148,136,.28);
    transition:all .2s; cursor:pointer; width:100%;
    justify-content:center;
}
.btn-pay:hover { background:linear-gradient(135deg,#0b7a6e,#0d9488); transform:translateY(-1px); color:#fff; }
.btn-pay:disabled { opacity:.6; transform:none; cursor:not-allowed; }

.btn-back {
    display:inline-flex; align-items:center; gap:6px;
    padding:10px 20px; border-radius:50px; border:2px solid #e5e7eb;
    background:#fff; color:#6b7280; font-size:.85rem; font-weight:600;
    text-decoration:none; transition:all .2s;
}
.btn-back:hover { border-color:#0d9488; color:#0d9488; background:#f0fdfb; }

.warga-info-card {
    background:linear-gradient(135deg,#f0fdfb,#e6faf7);
    border:1.5px solid #99f6e4; border-radius:14px; padding:16px 20px;
    display:flex; align-items:center; gap:16px; margin-bottom:20px;
}
.warga-avatar {
    width:50px; height:50px; border-radius:50%;
    background:linear-gradient(135deg,#0d9488,#14b8a6);
    display:flex; align-items:center; justify-content:center;
    color:#fff; font-size:1.3rem; flex-shrink:0;
    box-shadow:0 3px 10px rgba(13,148,136,.3);
}
.warga-name { font-size:1rem; font-weight:700; color:#0b5a52; }
.warga-nik  { font-size:.78rem; color:#6b7280; }

/* Mobile */
.bpw-mobile-list { display:none; }
@media(max-width:767.98px) {
    .bpw-desktop-table { display:none !important; }
    .bpw-mobile-list { display:flex; flex-direction:column; gap:10px; padding:12px; }
    .bpw-mobile-item {
        border-radius:11px; border:1.5px solid #e5e7eb;
        background:#fff; padding:12px 14px;
        display:flex; align-items:flex-start; gap:10px;
    }
    .bpw-mobile-item.item-rt     { border-left:4px solid #0d9488; }
    .bpw-mobile-item.item-arisan { border-left:4px solid #8b5cf6; }
    .total-strip .amount { font-size:1.15rem; }
}
</style>

<!-- ===== PAGE HEADER ===== -->
<div class="ar-page-header">
    <div class="ar-header-left">
        <h4>
            <span class="hi"><i class="bi bi-person-check"></i></span>
            <?php echo htmlspecialchars($title); ?>
        </h4>
        <div class="ar-breadcrumb">
            <a href="<?php echo base_url('dashboard'); ?>">Dashboard</a>
            <span class="sep">/</span>
            <a href="<?php echo base_url('iuran'); ?>">Iuran</a>
            <span class="sep">/</span>
            <a href="<?php echo base_url('iuran/bayar_massal'); ?>">Bayar Massal</a>
            <span class="sep">/</span>
            <span>Bayar Per Warga</span>
        </div>
    </div>
    <a href="<?php echo base_url('iuran/bayar_massal'); ?>" class="btn-back">
        <i class="bi bi-arrow-left"></i> Kembali
    </a>
</div>

<?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'];
?>

<!-- ===== INFO WARGA ===== -->
<div class="warga-info-card">
    <div class="warga-avatar"><i class="bi bi-person-fill"></i></div>
    <div>
        <div class="warga-name"><?php echo htmlspecialchars($warga->nama_lengkap); ?></div>
        <div class="warga-nik"><i class="bi bi-credit-card-2-front me-1"></i>NIK: <?php echo htmlspecialchars($warga->nik); ?></div>
    </div>
</div>

<!-- ===== FLASH MESSAGES ===== -->
<?php if($this->session->flashdata('error')): ?>
<div class="alert alert-danger d-flex align-items-center gap-2 rounded-3 border-0 mb-3" style="background:#fee2e2; color:#991b1b;">
    <i class="bi bi-exclamation-circle-fill"></i>
    <?php echo $this->session->flashdata('error'); ?>
</div>
<?php endif; ?>

<!-- ===== FORM ===== -->
<form action="<?php echo base_url('iuran/proses_bayar_per_warga'); ?>" method="POST" id="formBayarPerWarga">
    <input type="hidden" name="warga_id" value="<?php echo $warga->id; ?>">

    <!-- === TOTAL STRIP (live update via JS) === -->
    <div class="total-strip">
        <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
            <div>
                <div class="label"><i class="bi bi-check2-square me-1"></i>Total Tagihan Dipilih</div>
                <div class="amount" id="totalNominalDisplay">Rp 0</div>
            </div>
            <div class="text-end">
                <div class="label">Tagihan Dipilih</div>
                <div class="amount" id="totalCountDisplay">0 item</div>
            </div>
        </div>
    </div>

    <!-- ===== TABEL IURAN RT ===== -->
    <?php if(!empty($tagihan_rt)): ?>
    <div class="bpw-card">
        <div class="bpw-card-header" style="background:#f0fdfb;">
            <div class="title">
                <i class="bi bi-house-fill" style="color:#0d9488;"></i>
                Iuran RT / Reguler
                <span class="badge rounded-pill" style="background:#d1fae5; color:#065f46; border:1px solid #6ee7b7; font-size:.73rem;">
                    <?php echo count($tagihan_rt); ?> tagihan
                </span>
            </div>
            <button type="button" class="btn btn-sm fw-semibold check-all-btn" style="background:#d1fae5; border:1px solid #6ee7b7; color:#065f46; border-radius:8px; font-size:.78rem; padding:5px 12px;"
                onclick="toggleCheckAll('rt')">
                <i class="bi bi-check-all"></i> Pilih Semua
            </button>
        </div>

        <!-- Desktop -->
        <div class="bpw-desktop-table table-responsive">
            <table class="table bpw-table mb-0">
                <thead><tr>
                    <th style="width:44px;"><input type="checkbox" class="form-check-input check-all-rt" onchange="checkAllGroup('rt', this.checked)"></th>
                    <th>Jenis Iuran</th>
                    <th>Periode</th>
                    <th class="text-end">Nominal</th>
                </tr></thead>
                <tbody>
                <?php foreach($tagihan_rt as $t): ?>
                <tr class="item-row" data-nominal="<?php echo $t->nominal; ?>">
                    <td>
                        <input type="checkbox" name="tagihan_ids[]" value="<?php echo $t->id; ?>"
                            id="tagihan_ids_<?php echo $t->id; ?>"
                            class="form-check-input chk-rt chk-item" data-nominal="<?php echo $t->nominal; ?>"
                            onchange="updateTotal(); toggleRowHighlight(this); syncMobile(this)">
                    </td>
                    <td><?php echo htmlspecialchars($t->nama_iuran); ?></td>
                    <td><?php echo $bulan_names[(int)$t->periode_bulan].' '.$t->periode_tahun; ?></td>
                    <td class="text-end fw-bold" style="color:#0d9488;">Rp <?php echo number_format($t->nominal,0,',','.'); ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Mobile -->
        <div class="bpw-mobile-list">
            <?php foreach($tagihan_rt as $t): ?>
            <div class="bpw-mobile-item item-rt">
                <input type="checkbox"
                    class="form-check-input chk-item-mobile flex-shrink-0 mt-1"
                    data-mirror="tagihan_ids_<?php echo $t->id; ?>"
                    onchange="mirrorToDesktop(this)">
                <div class="flex-grow-1">
                    <div class="fw-semibold" style="font-size:.85rem;"><?php echo htmlspecialchars($t->nama_iuran); ?></div>
                    <div style="font-size:.78rem; color:#6b7280;">
                        <?php echo $bulan_names[(int)$t->periode_bulan].' '.$t->periode_tahun; ?>
                    </div>
                </div>
                <div class="fw-bold flex-shrink-0" style="color:#0d9488; font-size:.88rem;">
                    Rp <?php echo number_format($t->nominal,0,',','.'); ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- ===== TABEL IURAN ARISAN ===== -->
    <?php if(!empty($tagihan_arisan)): ?>
    <div class="bpw-card">
        <div class="bpw-card-header" style="background:#faf5ff;">
            <div class="title">
                <i class="bi bi-people-fill" style="color:#8b5cf6;"></i>
                Iuran Arisan
                <span class="badge rounded-pill" style="background:#ede9fe; color:#5b21b6; border:1px solid #c4b5fd; font-size:.73rem;">
                    <?php echo count($tagihan_arisan); ?> tagihan
                </span>
            </div>
            <button type="button" class="btn btn-sm fw-semibold check-all-btn" style="background:#ede9fe; border:1px solid #c4b5fd; color:#5b21b6; border-radius:8px; font-size:.78rem; padding:5px 12px;"
                onclick="toggleCheckAll('arisan')">
                <i class="bi bi-check-all"></i> Pilih Semua
            </button>
        </div>

        <!-- Desktop -->
        <div class="bpw-desktop-table table-responsive">
            <table class="table bpw-table mb-0">
                <thead><tr>
                    <th style="width:44px;"><input type="checkbox" class="form-check-input check-all-arisan" onchange="checkAllGroup('arisan', this.checked)"></th>
                    <th>Nama Arisan</th>
                    <th>Pertemuan Ke</th>
                    <th>Tgl Pertemuan</th>
                    <th class="text-end">Nominal</th>
                </tr></thead>
                <tbody>
                <?php foreach($tagihan_arisan as $a): ?>
                <tr class="item-row" data-nominal="<?php echo $a->nominal; ?>">
                    <td>
                        <input type="checkbox" name="arisan_ids[]" value="<?php echo $a->id; ?>"
                            id="arisan_ids_<?php echo $a->id; ?>"
                            class="form-check-input chk-arisan chk-item" data-nominal="<?php echo $a->nominal; ?>"
                            onchange="updateTotal(); toggleRowHighlight(this); syncMobile(this)">
                    </td>
                    <td><?php echo htmlspecialchars($a->nama_iuran); ?></td>
                    <td class="text-center">
                        <span class="badge rounded-pill" style="background:#ede9fe; color:#5b21b6; font-size:.75rem;">
                            Ke-<?php echo $a->pertemuan_ke; ?>
                        </span>
                    </td>
                    <td><?php echo date('d/m/Y', strtotime($a->tanggal_pertemuan)); ?></td>
                    <td class="text-end fw-bold" style="color:#8b5cf6;">Rp <?php echo number_format($a->nominal,0,',','.'); ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Mobile -->
        <div class="bpw-mobile-list">
            <?php foreach($tagihan_arisan as $a): ?>
            <div class="bpw-mobile-item item-arisan">
                <input type="checkbox"
                    class="form-check-input chk-item-mobile flex-shrink-0 mt-1"
                    data-mirror="arisan_ids_<?php echo $a->id; ?>"
                    onchange="mirrorToDesktop(this)">
                <div class="flex-grow-1">
                    <div class="fw-semibold" style="font-size:.85rem;"><?php echo htmlspecialchars($a->nama_iuran); ?></div>
                    <div style="font-size:.78rem; color:#6b7280;">
                        Pertemuan Ke-<?php echo $a->pertemuan_ke; ?> &nbsp;·&nbsp;
                        <?php echo date('d/m/Y', strtotime($a->tanggal_pertemuan)); ?>
                    </div>
                </div>
                <div class="fw-bold flex-shrink-0" style="color:#8b5cf6; font-size:.88rem;">
                    Rp <?php echo number_format($a->nominal,0,',','.'); ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- ===== FORM PEMBAYARAN ===== -->
    <div class="bpw-card">
        <div class="bpw-card-header">
            <div class="title"><i class="bi bi-credit-card"></i> Detail Pembayaran</div>
        </div>
        <div class="card-body p-4">
            <div class="row g-3">
                <div class="col-md-6">
                    <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" required>
                        <option value="">-- Pilih Metode --</option>
                        <option value="Tunai">Tunai / Cash</option>
                        <option value="Transfer Bank">Transfer Bank</option>
                        <option value="QRIS">QRIS</option>
                        <option value="Dompet Digital">Dompet Digital (GoPay/OVO/Dana)</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label small fw-semibold text-muted mb-1">
                        Kas Tujuan <span class="text-danger">*</span>
                    </label>
                    <select name="master_kas_id" class="form-select" required>
                        <option value="">— Pilih Kas —</option>
                        <?php foreach($kas_list as $kas):
                            // Emoji berdasarkan jenis/nama kas
                            $nm  = strtolower($kas->nama ?? '');
                            $kode = strtoupper($kas->kode ?? '');
                            if(strpos($nm,'tunai') !== false || strpos($nm,'cash') !== false)
                                $ico = '💵';
                            elseif(strpos($nm,'dana') !== false)
                                $ico = '💜';
                            elseif(strpos($nm,'ovo') !== false)
                                $ico = '💜';
                            elseif(strpos($nm,'gopay') !== false || strpos($nm,'go-pay') !== false)
                                $ico = '💚';
                            elseif(strpos($nm,'tabungan') !== false || strpos($nm,'tab') !== false)
                                $ico = '🏦';
                            else
                                $ico = '🏧';

                            // Bangun label: Nama (KODE) — nomor_rekening
                            $label = $ico . ' ' . $kas->nama;
                            if(!empty($kode))           $label .= ' (' . $kode . ')';
                            if(!empty($kas->no_rekening)) $label .= ' — ' . $kas->no_rekening;
                        ?>
                        <option value="<?php echo $kas->id; ?>">
                            <?php echo htmlspecialchars($label); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-12">
                    <label class="form-label small fw-semibold text-muted mb-1">Keterangan (opsional)</label>
                    <textarea name="keterangan" class="form-control" rows="2"
                        placeholder="Catatan pembayaran..."></textarea>
                </div>
            </div>
        </div>
    </div>

    <!-- ===== TOMBOL SUBMIT ===== -->
    <div class="d-flex gap-3 flex-wrap mb-4">
        <a href="<?php echo base_url('iuran/bayar_massal'); ?>" class="btn-back" style="flex:0 0 auto;">
            <i class="bi bi-arrow-left"></i> Batal
        </a>
        <button type="submit" class="btn-pay" id="btnSubmit" disabled>
            <i class="bi bi-check-circle-fill"></i>
            Proses Pembayaran (<span id="btnCountLabel">0 item</span>)
        </button>
    </div>
</form>

<script>
function formatRupiah(n) {
    return 'Rp ' + parseInt(n).toLocaleString('id-ID');
}

// Hanya hitung checkbox DESKTOP (chk-item), bukan mobile mirror
function updateTotal() {
    var total = 0, count = 0;
    document.querySelectorAll('.chk-item:checked').forEach(function(el) {
        total += parseInt(el.dataset.nominal) || 0;
        count++;
    });
    document.getElementById('totalNominalDisplay').textContent = formatRupiah(total);
    document.getElementById('totalCountDisplay').textContent   = count + ' item';
    document.getElementById('btnCountLabel').textContent       = count + ' item';
    document.getElementById('btnSubmit').disabled              = (count === 0);
}

function toggleRowHighlight(chk) {
    var row = chk.closest('tr');
    if(row) row.classList.toggle('selected-row', chk.checked);
}

// Mobile checkbox → mirror ke desktop checkbox yg sesuai
function mirrorToDesktop(mobileChk) {
    var targetId = mobileChk.dataset.mirror;
    var desktop  = document.getElementById(targetId);
    if(desktop) {
        desktop.checked = mobileChk.checked;
        toggleRowHighlight(desktop);
        updateTotal();
    }
}

// Desktop checkbox → mirror ke mobile checkbox yg sesuai
function syncMobile(desktopChk) {
    var mirrorEl = document.querySelector('.chk-item-mobile[data-mirror="' + desktopChk.id + '"]');
    if(mirrorEl) mirrorEl.checked = desktopChk.checked;
}

function checkAllGroup(group, checked) {
    // Centang semua desktop
    document.querySelectorAll('.chk-' + group).forEach(function(el) {
        el.checked = checked;
        toggleRowHighlight(el);
        syncMobile(el);
    });
    updateTotal();
}

function toggleCheckAll(group) {
    var all        = document.querySelectorAll('.chk-' + group);
    var allChecked = Array.from(all).every(function(el){ return el.checked; });
    checkAllGroup(group, !allChecked);
}

// Select all by default on load
window.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.chk-item').forEach(function(el) {
        el.checked = true;
        toggleRowHighlight(el);
        syncMobile(el);
    });
    ['rt', 'arisan'].forEach(function(g) {
        var hdr = document.querySelector('.check-all-' + g);
        if(hdr) hdr.checked = true;
    });
    updateTotal();
});

</script>

<!-- ===== MODAL KONFIRMASI PEMBAYARAN (BOOTSTRAP 5) ===== -->
<div class="modal fade" id="modalConfirmBayar" 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;">
      <!-- Header Gradient -->
      <div class="modal-header" style="background:linear-gradient(135deg,#0d9488,#14b8a6); border:none; padding: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-shield-check" style="color:#fff; font-size:1rem;"></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>
      
      <!-- Body -->
      <div class="modal-body text-center" style="padding:25px 20px;">
        <div class="mb-3">
            <i class="bi bi-question-circle" style="font-size:3rem; color:#14b8a6; opacity:.3;"></i>
        </div>
        <h5 style="font-size:1.05rem; font-weight:700; color:#111827; margin-bottom:8px;">Proses Pembayaran <span id="modalCountLabel">0 tagihan</span>?</h5>
        <p style="font-size:.85rem; color:#6b7280; line-height:1.5;">
            Pembayaran yang diproses akan langsung dicatat sebagai <strong style="color:#059669;">LUNAS</strong> dan tidak dapat dibatalkan secara massal.
        </p>
        
        <div style="background:#f0fdfa; border:1.5px dashed #99f6e4; border-radius:12px; padding:12px; margin-top:15px; font-size:.78rem; color:#0d9488;">
            <i class="bi bi-info-circle-fill me-1"></i> Data akan tercatat di Laporan Keuangan secara otomatis.
        </div>
      </div>
      
      <!-- Footer Actions -->
      <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="btnConfirmPay"
                style="flex:1; border-radius:10px; border:none; background:linear-gradient(135deg,#0d9488,#14b8a6); color:#fff; font-size:.82rem; padding:8px; box-shadow:0 4px 12px rgba(13,148,136,.25);">
            Ya, Bayar Sekarang
        </button>
      </div>
    </div>
  </div>
</div>

<script>
// Modal Konfirmasi (Bootstrap 5)
var _bsModalConfirm = null;

document.addEventListener('DOMContentLoaded', function() {
    var form = document.getElementById('formBayarPerWarga');
    var btnConfirm = document.getElementById('btnConfirmPay');
    
    if(form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            var count = document.querySelectorAll('.chk-item:checked').length;
            if(count === 0) { alert('Pilih minimal 1 tagihan!'); return; }
            document.getElementById('modalCountLabel').textContent = count + ' tagihan';
            var modalEl = document.getElementById('modalConfirmBayar');
            if(!_bsModalConfirm) _bsModalConfirm = new bootstrap.Modal(modalEl);
            _bsModalConfirm.show();
        });
    }
    
    if(btnConfirm) {
        btnConfirm.addEventListener('click', function() {
            if(_bsModalConfirm) _bsModalConfirm.hide();
            if(form) form.submit();
        });
    }
});
</script>