<?php
/**
 * Simpanan Wajib Management
 * Koperasi Management System
 */

$pageTitle = 'Simpanan Wajib';
$pageSubtitle = 'Kelola simpanan wajib anggota per bulan';

require_once __DIR__ . '/../config/database.php';
$db = getDB();

// ── Handle POST Actions ──────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Save/Update Monthly Setting
    if ($action === 'save_setting') {
        $bulan = $_POST['bulan']; // YYYY-MM
        $nominal = str_replace('.', '', $_POST['nominal']);
        
        $stmt = $db->prepare("INSERT INTO simpanan_wajib_pengaturan (bulan, nominal) VALUES (?, ?) ON DUPLICATE KEY UPDATE nominal = ?");
        $stmt->execute([$bulan, $nominal, $nominal]);
        
        setFlash('success', 'Pengaturan simpanan wajib bulan ' . $bulan . ' berhasil disimpan.');
        header('Location: simpanan_wajib.php');
        exit;
    }

    // Add/Update Payment
    if ($action === 'add_payment') {
        $anggota_id = $_POST['anggota_id'];
        $bulan = $_POST['bulan']; // YYYY-MM
        $tanggal = $_POST['tanggal'] ?: $bulan . '-' . date('d');
        $keterangan = sanitize($_POST['keterangan'] ?? 'Simpanan wajib bulan ' . $bulan);
        
        // Get nominal for this month
        $stmt = $db->prepare("SELECT nominal FROM simpanan_wajib_pengaturan WHERE bulan = ?");
        $stmt->execute([$bulan]);
        $nominal = $stmt->fetchColumn() ?: getSetting('simpanan_wajib', 50000);

        // Check if already paid for this month
        $chk = $db->prepare("SELECT id FROM simpanan WHERE anggota_id = ? AND jenis = 'wajib' AND DATE_FORMAT(tanggal, '%Y-%m') = ?");
        $chk->execute([$anggota_id, $bulan]);
        $existing = $chk->fetch();

        if ($existing) {
            $stmt = $db->prepare("UPDATE simpanan SET jumlah = ?, tanggal = ?, keterangan = ? WHERE id = ?");
            $stmt->execute([$nominal, $tanggal, $keterangan, $existing['id']]);
            setFlash('success', 'Data simpanan wajib berhasil diperbarui.');
        } else {
            $stmt = $db->prepare("INSERT INTO simpanan (anggota_id, jenis, tipe, jumlah, tanggal, keterangan, created_by) VALUES (?, 'wajib', 'setoran', ?, ?, ?, ?)");
            $stmt->execute([$anggota_id, $nominal, $tanggal, $keterangan, $_SESSION['user_id']]);
            setFlash('success', 'Simpanan wajib berhasil dicatat.');
        }
        
        header('Location: simpanan_wajib.php?bulan=' . $bulan);
        exit;
    }

    if ($action === 'delete') {
        $stmt = $db->prepare("DELETE FROM simpanan WHERE id = ? AND jenis = 'wajib'");
        $stmt->execute([$_POST['id']]);
        setFlash('success', 'Data berhasil dihapus.');
        header('Location: ' . $_SERVER['HTTP_REFERER']);
        exit;
    }

    if ($action === 'delete_bulk') {
        $ids = $_POST['ids'] ?? [];
        if (!empty($ids) && is_array($ids)) {
            $in = str_repeat('?,', count($ids) - 1) . '?';
            $stmt = $db->prepare("DELETE FROM simpanan WHERE id IN ($in) AND jenis='wajib'");
            $stmt->execute($ids);
            setFlash('success', count($ids) . ' data pembayaran berhasil dihapus.');
        } else {
            setFlash('warning', 'Pilih setidaknya satu data untuk dihapus.');
        }
        header('Location: simpanan_wajib.php?bulan=' . $_POST['bulan']);
        exit;
    }

    if ($action === 'bulk_payment') {
        $bulan = $_POST['bulan'];
        $nominal = (float)$_POST['nominal'];
        $tanggal = $bulan . '-01';
        $keterangan = sanitize($_POST['keterangan'] ?: 'Simpanan wajib bulan ' . date('F Y', strtotime($bulan)));

        $allAnggota = $db->query("SELECT id FROM anggota WHERE status='aktif'")->fetchAll(PDO::FETCH_COLUMN);
        $insertStmt = $db->prepare("INSERT INTO simpanan (anggota_id, jenis, tipe, jumlah, tanggal, keterangan, created_by) VALUES (?, 'wajib', 'setoran', ?, ?, ?, ?)");
        
        $inserted = 0;
        $skipped = 0;

        foreach ($allAnggota as $aid) {
            // Check if already paid
            $chk = $db->prepare("SELECT COUNT(*) FROM simpanan WHERE anggota_id=? AND jenis='wajib' AND DATE_FORMAT(tanggal,'%Y-%m')=?");
            $chk->execute([$aid, $bulan]);
            if ($chk->fetchColumn() > 0) {
                $skipped++;
                continue;
            }

            $insertStmt->execute([$aid, $nominal, $tanggal, $keterangan, $_SESSION['user_id']]);
            $inserted++;
        }

        setFlash('success', "Berhasil mencatat $inserted anggota. ($skipped anggota sudah membayar sebelumnya)");
        header('Location: simpanan_wajib.php?bulan=' . $bulan);
        exit;
    }
}

// ── GET Parameters ────────────────────────────────────────────────────────────
$selectedBulan = $_GET['bulan'] ?? date('Y-m');
$search = $_GET['search'] ?? '';

// Get nominal for selected bulan
$stmt = $db->prepare("SELECT nominal FROM simpanan_wajib_pengaturan WHERE bulan = ?");
$stmt->execute([$selectedBulan]);
$currentNominal = $stmt->fetchColumn();
if (!$currentNominal) {
    // Try to get the latest setting if not set for this month
    $stmt = $db->prepare("SELECT nominal FROM simpanan_wajib_pengaturan ORDER BY bulan DESC LIMIT 1");
    $stmt->execute();
    $currentNominal = $stmt->fetchColumn() ?: getSetting('simpanan_wajib', 50000);
}

// ── Member Payment Status for current month ───────────────────────────────────
$where = $search ? "AND (nama LIKE ? OR no_anggota LIKE ?)" : "";
$params = $search ? ["%$search%", "%$search%"] : [];

$query = "
    SELECT 
        a.id as anggota_id, 
        a.no_anggota, 
        a.nama,
        s.id as simpanan_id,
        s.jumlah,
        s.tanggal,
        s.keterangan,
        CASE WHEN s.id IS NOT NULL THEN 1 ELSE 0 END as is_paid,
        COALESCE((SELECT SUM(s2.jumlah) FROM simpanan s2 WHERE s2.anggota_id = a.id AND s2.jenis = 'wajib' AND s2.tipe = 'setoran'), 0) as total_wajib
    FROM anggota a
    LEFT JOIN simpanan s ON a.id = s.anggota_id 
        AND s.jenis = 'wajib' 
        AND DATE_FORMAT(s.tanggal, '%Y-%m') = ?
    WHERE a.status = 'aktif' $where
    ORDER BY a.nama ASC
";

$stmt = $db->prepare($query);
$stmt->execute(array_merge([$selectedBulan], $params));
$members = $stmt->fetchAll();

// Handle AJAX request for member detail
if (isset($_GET['ajax_detail'])) {
    header('Content-Type: application/json');
    $aid = intval($_GET['ajax_detail']);
    $detailStmt = $db->prepare("
        SELECT s.jumlah, s.tanggal, s.keterangan, DATE_FORMAT(s.tanggal, '%Y-%m') as bulan
        FROM simpanan s 
        WHERE s.anggota_id = ? AND s.jenis = 'wajib' AND s.tipe = 'setoran'
        ORDER BY s.tanggal ASC
    ");
    $detailStmt->execute([$aid]);
    $rows = $detailStmt->fetchAll();
    
    $nameStmt = $db->prepare("SELECT nama, no_anggota FROM anggota WHERE id = ?");
    $nameStmt->execute([$aid]);
    $anggotaInfo = $nameStmt->fetch();
    
    $total = 0;
    foreach ($rows as &$r) { $total += $r['jumlah']; }
    
    echo json_encode(['nama' => $anggotaInfo['nama'], 'no_anggota' => $anggotaInfo['no_anggota'], 'rows' => $rows, 'total' => $total]);
    exit;
}

// Statistics
$totalPaid = 0;
$totalAmountMonth = 0; // Amount for CURRENT month
foreach ($members as $m) {
    if ($m['is_paid']) {
        $totalPaid++;
        $totalAmountMonth += $m['jumlah'];
    }
}
$totalMembers = count($members);
$percent = $totalMembers > 0 ? round(($totalPaid / $totalMembers) * 100) : 0;

// Grand Total (All months)
$stmtGrand = $db->query("SELECT SUM(jumlah) FROM simpanan WHERE jenis = 'wajib' AND tipe = 'setoran'");
$totalAmountGrand = $stmtGrand->fetchColumn() ?: 0;

include __DIR__ . '/../includes/header.php';
?>

<div class="row mb-4">
    <div class="col-md-8">
        <div class="stats-grid" style="grid-template-columns: repeat(3, 1fr); gap: 15px;">
            <div class="stat-card primary">
                <div class="stat-info">
                    <h3>Total Anggota</h3>
                    <div class="stat-value"><?= $totalMembers ?></div>
                </div>
                <div class="stat-icon primary"><i class="fas fa-users"></i></div>
            </div>
            <div class="stat-card success">
                <div class="stat-info">
                    <h3>Sudah Bayar</h3>
                    <div class="stat-value"><?= $totalPaid ?></div>
                    <span class="stat-change up"><?= $percent ?>% dari total</span>
                </div>
                <div class="stat-icon success"><i class="fas fa-check-circle"></i></div>
            </div>
            <div class="stat-card info">
                <div class="stat-info">
                    <h3>Total Terkumpul (Semua)</h3>
                    <div class="stat-value"><?= formatRupiah($totalAmountGrand) ?></div>
                    <span class="stat-change info">Bulan ini: <?= formatRupiah($totalAmountMonth) ?></span>
                </div>
                <div class="stat-icon info"><i class="fas fa-money-bill-wave"></i></div>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card h-100">
            <div class="card-header">
                <h3><i class="fas fa-cog"></i> Pengaturan Bulan</h3>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="save_setting">
                    <div class="form-group mb-2">
                        <label>Bulan Pilih</label>
                        <input type="month" name="bulan" class="form-control" value="<?= $selectedBulan ?>" onchange="window.location='simpanan_wajib.php?bulan='+this.value">
                    </div>
                    <div class="form-group mb-2">
                        <label>Nominal Wajib (Rp)</label>
                        <input type="text" name="nominal" class="form-control" value="<?= number_format($currentNominal, 0, ',', '.') ?>" oninput="formatCurrencyInput(this)">
                    </div>
                    <button type="submit" class="btn btn-primary btn-block mt-2">Simpan Nominal</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <div class="toolbar" style="width: 100%;">
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input type="text" placeholder="Cari anggota..." value="<?= htmlspecialchars($search) ?>" 
                       onkeydown="if(event.key==='Enter') window.location='simpanan_wajib.php?bulan=<?= $selectedBulan ?>&search='+encodeURIComponent(this.value);">
            </div>
            <div style="margin-left: auto; display: flex; gap: 10px;">
                <form id="bulkDeleteForm" method="POST" style="display:none;" onsubmit="return submitBulkDelete(event);">
                    <button type="submit" class="btn" style="background:var(--danger-500); color:white; border-color:var(--danger-600);">
                        <i class="fas fa-trash-alt"></i> Hapus Terpilih (<span id="selectedCount">0</span>)
                    </button>
                </form>
                <a href="simpanan_wajib_rekap_umum.php" class="btn btn-outline-info">
                    <i class="fas fa-file-invoice"></i> Rekap Simpanan Wajib
                </a>
                <button class="btn btn-success" onclick="openModal('addBulkModal')">
                    <i class="fas fa-users-cog"></i> Bayar Masal
                </button>
            </div>
        </div>
    </div>
    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th style="width: 40px; text-align: center;"><input type="checkbox" onchange="toggleAllCheckboxes(this)"></th>
                    <th style="width: 50px; text-align: center;">Nomor</th>
                    <th>No. Anggota</th>
                    <th>Nama Anggota</th>
                    <th>Status</th>
                    <th>Nominal</th>
                    <th>Tanggal Bayar</th>
                    <th>Keterangan</th>
                    <th>Total S. Wajib</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php $nomor = 1; foreach ($members as $m): ?>
                <tr>
                    <td style="text-align: center;">
                        <?php if ($m['is_paid']): ?>
                            <input type="checkbox" class="rowCheckbox" value="<?= $m['simpanan_id'] ?>" onchange="updateBulkDeleteBtn()">
                        <?php else: ?>
                            <input type="checkbox" disabled title="Belum bayar">
                        <?php endif; ?>
                    </td>
                    <td style="text-align: center; font-weight: bold;"><?=$nomor++?></td>
                    <td><?= htmlspecialchars($m['no_anggota']) ?></td>
                    <td>
                        <div class="fw-bold"><?= htmlspecialchars($m['nama']) ?></div>
                    </td>
                    <td>
                        <?php if ($m['is_paid']): ?>
                            <span class="badge badge-success"><i class="fas fa-check"></i> Sudah Bayar</span>
                        <?php else: ?>
                            <span class="badge badge-danger"><i class="fas fa-times"></i> Belum Bayar</span>
                        <?php endif; ?>
                    </td>
                    <td><?= $m['is_paid'] ? formatRupiah($m['jumlah']) : '-' ?></td>
                    <td><?= $m['is_paid'] ? formatTanggal($m['tanggal']) : '-' ?></td>
                    <td style="font-size: 0.85rem; color: #666;"><?= htmlspecialchars($m['keterangan'] ?: '-') ?></td>
                    <td>
                        <a href="javascript:void(0)" onclick="showDetailWajib(<?= $m['anggota_id'] ?>)" 
                           style="color: var(--primary-600); font-weight: 700; text-decoration: none; cursor: pointer; white-space: nowrap;"
                           title="Klik untuk lihat rincian">
                            <?= formatRupiah($m['total_wajib']) ?>
                        </a>
                    </td>
                    <td>
                        <div class="action-buttons">
                            <?php if (!$m['is_paid']): ?>
                                <button class="btn btn-sm btn-primary" onclick="payMember(<?= $m['anggota_id'] ?>, '<?= addslashes($m['nama']) ?>')">
                                    <i class="fas fa-hand-holding-usd"></i> Bayar
                                </button>
                            <?php else: ?>
                                <button class="btn btn-icon btn-outline" onclick="payMember(<?= $m['anggota_id'] ?>, '<?= addslashes($m['nama']) ?>', '<?= $m['tanggal'] ?>', '<?= addslashes($m['keterangan']) ?>')" title="Edit">
                                    <i class="fas fa-pen text-warning"></i>
                                </button>
                                <form method="POST" style="display:inline;" onsubmit="return confirm('Hapus data pembayaran ini?')">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= $m['simpanan_id'] ?>">
                                    <button type="submit" class="btn btn-icon btn-outline" title="Hapus">
                                        <i class="fas fa-trash text-danger"></i>
                                    </button>
                                </form>
                            <?php endif; ?>
                            <a href="simpanan_wajib_rekap.php?id=<?= $m['anggota_id'] ?>" class="btn btn-icon btn-outline" title="View Rekap">
                                <i class="fas fa-list text-info"></i>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr style="background: #f8fafc; font-weight: bold;">
                    <td colspan="4" class="text-end" style="padding: 15px; border-top: 2px solid var(--gray-200);">
                        TOTAL BULAN INI (<?= date('F Y', strtotime($selectedBulan)) ?>):
                    </td>
                    <td colspan="6" class="text-start" style="padding: 15px; color: var(--primary-600); font-size: 1.1rem; border-top: 2px solid var(--gray-200);">
                        <?= formatRupiah($totalAmountMonth) ?>
                    </td>
                </tr>
                <tr style="background: var(--primary-50); font-weight: 800;">
                    <td colspan="4" class="text-end" style="padding: 15px; border-top: 1px solid var(--primary-100);">
                        TOTAL KESELURUHAN (SEMUA BULAN):
                    </td>
                    <td colspan="6" class="text-start" style="padding: 15px; color: var(--success-700); font-size: 1.25rem; border-top: 1px solid var(--primary-100);">
                        <?= formatRupiah($totalAmountGrand) ?>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

<!-- Modal Bayar -->
<div class="modal" id="payModal">
    <div class="modal-header">
        <h3><i class="fas fa-money-bill-wave"></i> Pembayaran Simpanan Wajib</h3>
        <button class="modal-close" onclick="closeModal('payModal')"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="add_payment">
        <input type="hidden" name="anggota_id" id="pay_anggota_id">
        <input type="hidden" name="bulan" value="<?= $selectedBulan ?>">
        <div class="modal-body">
            <div class="form-group mb-3">
                <label>Nama Anggota</label>
                <input type="text" id="pay_nama" class="form-control" readonly>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Bulan</label>
                    <input type="text" class="form-control" value="<?= date('F Y', strtotime($selectedBulan)) ?>" readonly>
                </div>
                <div class="form-group">
                    <label>Tanggal Bayar</label>
                    <input type="date" name="tanggal" id="pay_tanggal" class="form-control" value="<?= date('Y-m-d') ?>">
                </div>
            </div>
            <div class="form-group">
                <label>Nominal</label>
                <div class="form-control bg-light fw-bold"><?= formatRupiah($currentNominal) ?></div>
            </div>
            <div class="form-group">
                <label>Keterangan</label>
                <textarea name="keterangan" id="pay_keterangan" class="form-control" rows="2">Simpanan wajib bulan <?= date('F Y', strtotime($selectedBulan)) ?></textarea>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('payModal')">Batal</button>
            <button type="submit" class="btn btn-primary">Simpan Pembayaran</button>
        </div>
    </form>
</div>

<!-- Modal Bulk -->
<div class="modal" id="addBulkModal">
    <div class="modal-header">
        <h3><i class="fas fa-users-cog"></i> Pembayaran Masal</h3>
        <button class="modal-close" onclick="closeModal('addBulkModal')"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="bulk_payment">
        <input type="hidden" name="bulan" value="<?= $selectedBulan ?>">
        <input type="hidden" name="nominal" value="<?= $currentNominal ?>">
        <div class="modal-body">
            <p>Anda akan mencatat simpanan wajib sebesar <strong><?= formatRupiah($currentNominal) ?></strong> untuk <strong>SEMUA</strong> anggota yang belum membayar pada bulan <strong><?= date('F Y', strtotime($selectedBulan)) ?></strong>.</p>
            <div class="form-group">
                <label>Keterangan Masal</label>
                <input type="text" name="keterangan" class="form-control" placeholder="Simpanan wajib <?= date('F Y', strtotime($selectedBulan)) ?>">
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('addBulkModal')">Batal</button>
            <button type="submit" class="btn btn-success">Proses Sekarang</button>
        </div>
    </form>
</div>

<!-- Modal Detail Simpanan Wajib Per Anggota -->
<div class="modal" id="detailWajibModal" style="max-width:650px;">
    <div class="modal-header">
        <h3><i class="fas fa-list" style="color:var(--info-500);margin-right:8px;"></i>Rincian Simpanan Wajib</h3>
        <button class="modal-close" onclick="closeModal('detailWajibModal')"><i class="fas fa-times"></i></button>
    </div>
    <div class="modal-body">
        <div id="detailWajibInfo" style="background:var(--gray-50);border-radius:var(--radius-md);padding:12px 16px;margin-bottom:14px;display:flex;align-items:center;gap:12px;">
            <div style="width:38px;height:38px;border-radius:50%;background:var(--primary-500)20;display:flex;align-items:center;justify-content:center;">
                <i class="fas fa-user" style="color:var(--primary-500);font-size:1rem;"></i>
            </div>
            <div>
                <div id="detailNama" style="font-weight:700;color:var(--gray-800);">-</div>
                <div id="detailNoAnggota" style="font-size:0.78rem;color:var(--gray-500);">-</div>
            </div>
            <div style="margin-left:auto;text-align:right;">
                <div style="font-size:0.7rem;color:var(--gray-400);text-transform:uppercase;">Total</div>
                <div id="detailTotal" style="font-weight:800;color:var(--success-600);font-size:1.1rem;">-</div>
            </div>
        </div>
        <div id="detailWajibLoading" style="text-align:center;padding:30px;display:none;">
            <i class="fas fa-spinner fa-spin" style="font-size:1.5rem;color:var(--gray-400);"></i>
            <p style="color:var(--gray-500);margin-top:8px;">Memuat data...</p>
        </div>
        <div id="detailWajibContent" style="max-height:350px;overflow-y:auto;border-radius:var(--radius-md);border:1px solid var(--gray-200);">
            <table class="data-table" style="margin:0;">
                <thead style="position:sticky;top:0;z-index:1;">
                    <tr>
                        <th style="width:40px;text-align:center;">No</th>
                        <th>Bulan</th>
                        <th>Tanggal Bayar</th>
                        <th class="text-right">Nominal</th>
                    </tr>
                </thead>
                <tbody id="detailWajibBody">
                    <tr><td colspan="4" class="text-center text-muted" style="padding:30px;">Pilih anggota untuk melihat rincian</td></tr>
                </tbody>
                <tfoot id="detailWajibFoot" style="display:none;">
                    <tr style="background:#f0fdf4;font-weight:bold;">
                        <td colspan="3" class="text-end" style="padding:12px;">TOTAL</td>
                        <td class="text-right" style="padding:12px;color:var(--success-600);font-size:1.05rem;" id="detailTotalFoot">-</td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-primary" onclick="closeModal('detailWajibModal')">Tutup</button>
    </div>
</div>

<script>
const bulanNames = ['','Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];

function formatRupiahJS(num) {
    return 'Rp ' + new Intl.NumberFormat('id-ID').format(num);
}

function showDetailWajib(anggotaId) {
    const loading = document.getElementById('detailWajibLoading');
    const content = document.getElementById('detailWajibContent');
    const body = document.getElementById('detailWajibBody');
    const foot = document.getElementById('detailWajibFoot');
    
    loading.style.display = 'block';
    content.style.display = 'none';
    foot.style.display = 'none';
    document.getElementById('detailNama').textContent = 'Memuat...';
    document.getElementById('detailNoAnggota').textContent = '';
    document.getElementById('detailTotal').textContent = '-';
    
    openModal('detailWajibModal');
    
    fetch('simpanan_wajib.php?ajax_detail=' + anggotaId)
        .then(r => r.json())
        .then(data => {
            loading.style.display = 'none';
            content.style.display = 'block';
            
            document.getElementById('detailNama').textContent = data.nama;
            document.getElementById('detailNoAnggota').textContent = data.no_anggota;
            document.getElementById('detailTotal').textContent = formatRupiahJS(data.total);
            document.getElementById('detailTotalFoot').textContent = formatRupiahJS(data.total);
            
            if (data.rows.length === 0) {
                body.innerHTML = '<tr><td colspan="4" class="text-center text-muted" style="padding:30px;"><i class="fas fa-inbox" style="font-size:1.5rem;display:block;margin-bottom:8px;color:var(--gray-300);"></i>Belum ada data simpanan wajib</td></tr>';
                foot.style.display = 'none';
            } else {
                let html = '';
                data.rows.forEach((row, i) => {
                    const parts = row.bulan.split('-');
                    const bulanLabel = bulanNames[parseInt(parts[1])] + ' ' + parts[0];
                    const tglParts = row.tanggal.split('-');
                    const tglFormatted = tglParts[2] + ' ' + bulanNames[parseInt(tglParts[1])] + ' ' + tglParts[0];
                    html += `<tr>
                        <td style="text-align:center;font-weight:bold;">${i+1}</td>
                        <td>${bulanLabel}</td>
                        <td>${tglFormatted}</td>
                        <td class="text-right fw-bold text-success">${formatRupiahJS(row.jumlah)}</td>
                    </tr>`;
                });
                body.innerHTML = html;
                foot.style.display = 'table-footer-group';
            }
        })
        .catch(err => {
            loading.style.display = 'none';
            content.style.display = 'block';
            body.innerHTML = '<tr><td colspan="4" class="text-center text-danger" style="padding:20px;">Gagal memuat data</td></tr>';
        });
}

function toggleAllCheckboxes(source) {
    const checkboxes = document.querySelectorAll('.rowCheckbox');
    checkboxes.forEach(cb => {
        if (!cb.disabled) cb.checked = source.checked;
    });
    updateBulkDeleteBtn();
}

function updateBulkDeleteBtn() {
    const checkboxes = document.querySelectorAll('.rowCheckbox:checked');
    const form = document.getElementById('bulkDeleteForm');
    const countSpan = document.getElementById('selectedCount');
    
    if (checkboxes.length > 0) {
        form.style.display = 'block';
        countSpan.textContent = checkboxes.length;
    } else {
        form.style.display = 'none';
    }
}

function submitBulkDelete(e) {
    const checkboxes = document.querySelectorAll('.rowCheckbox:checked');
    if (checkboxes.length === 0) {
        e.preventDefault();
        return false;
    }
    if (!confirm('Hapus ' + checkboxes.length + ' data simpanan wajib terpilih?')) {
        e.preventDefault();
        return false;
    }
    const form = document.getElementById('bulkDeleteForm');
    form.innerHTML = '<input type="hidden" name="action" value="delete_bulk"><input type="hidden" name="bulan" value="<?= $selectedBulan ?>">';
    checkboxes.forEach(cb => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'ids[]';
        input.value = cb.value;
        form.appendChild(input);
    });
    return true;
}

function payMember(id, nama, tanggal = '', keterangan = '') {
    document.getElementById('pay_anggota_id').value = id;
    document.getElementById('pay_nama').value = nama;
    if (tanggal) document.getElementById('pay_tanggal').value = tanggal;
    if (keterangan) document.getElementById('pay_keterangan').value = keterangan;
    openModal('payModal');
}

function formatCurrencyInput(input) {
    let value = input.value.replace(/\D/g, '');
    input.value = new Intl.NumberFormat('id-ID').format(value);
}
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
