<?php
/**
 * Simpanan (Savings) Management
 * Koperasi Management System
 */

$pageTitle = 'Simpanan';
$pageSubtitle = 'Kelola simpanan anggota koperasi';

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

// Safe migration: add dana_pensiun to ENUM
try {
    $db->exec("ALTER TABLE simpanan MODIFY COLUMN jenis ENUM('pokok','wajib','sukarela','dana_pensiun') NOT NULL");
} catch (Exception $e) { /* already done */ }

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

    if ($action === 'add') {
        $stmt = $db->prepare("INSERT INTO simpanan (anggota_id, jenis, tipe, jumlah, tanggal, keterangan, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $_POST['anggota_id'],
            $_POST['jenis'],
            $_POST['tipe'],
            str_replace('.', '', $_POST['jumlah']),
            $_POST['tanggal'],
            sanitize($_POST['keterangan'] ?? ''),
            $_SESSION['user_id']
        ]);
        setFlash('success', 'Transaksi simpanan berhasil dicatat.');
        header('Location: simpanan.php');
        exit;
    }

    if ($action === 'edit') {
        $stmt = $db->prepare("UPDATE simpanan SET anggota_id=?, jenis=?, tipe=?, jumlah=?, tanggal=?, keterangan=? WHERE id=?");
        $stmt->execute([
            $_POST['anggota_id'],
            $_POST['jenis'],
            $_POST['tipe'],
            str_replace('.', '', $_POST['jumlah']),
            $_POST['tanggal'],
            sanitize($_POST['keterangan'] ?? ''),
            $_POST['id']
        ]);
        setFlash('success', 'Transaksi simpanan berhasil diperbarui.');
        header('Location: simpanan.php');
        exit;
    }

    if ($action === 'delete') {
        $stmt = $db->prepare("DELETE FROM simpanan WHERE id=?");
        $stmt->execute([$_POST['id']]);
        setFlash('success', 'Transaksi berhasil dihapus.');
        header('Location: simpanan.php');
        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)");
            $stmt->execute($ids);
            setFlash('success', count($ids) . ' transaksi berhasil dihapus.');
        } else {
            setFlash('warning', 'Pilih setidaknya satu transaksi untuk dihapus.');
        }
        header('Location: simpanan.php');
        exit;
    }

    // Per-anggota balance adjustment (for sukarela / dana_pensiun)
    if ($action === 'edit_saldo') {
        $anggota_id  = intval($_POST['anggota_id']);
        $jenis_post  = $_POST['jenis'];
        $jumlah_baru = floatval(str_replace('.', '', $_POST['jumlah_baru']));
        $keterangan  = sanitize($_POST['keterangan'] ?? 'Penyesuaian saldo');
        $tanggal     = $_POST['tanggal'] ?? date('Y-m-d');

        $balStmt = $db->prepare("SELECT COALESCE(SUM(CASE WHEN tipe='setoran' THEN jumlah ELSE -jumlah END),0) FROM simpanan WHERE anggota_id=? AND jenis=?");
        $balStmt->execute([$anggota_id, $jenis_post]);
        $currentSaldo = floatval($balStmt->fetchColumn());
        $selisih = $jumlah_baru - $currentSaldo;

        if (abs($selisih) > 0.01) {
            $tipeAdj = $selisih > 0 ? 'setoran' : 'penarikan';
            $stmt = $db->prepare("INSERT INTO simpanan (anggota_id, jenis, tipe, jumlah, tanggal, keterangan, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$anggota_id, $jenis_post, $tipeAdj, abs($selisih), $tanggal, $keterangan, $_SESSION['user_id']]);
        }

        setFlash('success', 'Saldo simpanan berhasil diperbarui.');
        header('Location: simpanan.php');
        exit;
    }

    // Global set for Simpanan Pokok / Wajib → bulk-insert for all members
    if ($action === 'set_global') {
        $jenis_global      = $_POST['jenis_global'];  // 'pokok' or 'wajib'
        $jumlah_global     = floatval(str_replace('.', '', $_POST['jumlah_global']));
        $tanggal_global    = $_POST['tanggal_global'] ?? date('Y-m-d');
        $keterangan_global = sanitize($_POST['keterangan_global'] ?? '');
        $only_unpaid       = isset($_POST['only_unpaid']);

        // Update pengaturan
        $settingKey = $jenis_global === 'pokok' ? 'simpanan_pokok' : 'simpanan_wajib';
        $db->prepare("UPDATE pengaturan SET nilai=? WHERE kunci=?")->execute([$jumlah_global, $settingKey]);

        $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 (?, ?, 'setoran', ?, ?, ?, ?)");
        $skipped = 0; $inserted = 0;

        foreach ($allAnggota as $aid) {
            // Pokok: skip if already paid (when checkbox is checked)
            if ($jenis_global === 'pokok' && $only_unpaid) {
                $chk = $db->prepare("SELECT COUNT(*) FROM simpanan WHERE anggota_id=? AND jenis='pokok'");
                $chk->execute([$aid]);
                if ($chk->fetchColumn() > 0) { $skipped++; continue; }
            }
            // Wajib: skip if already paid this month
            if ($jenis_global === 'wajib') {
                $ym = substr($tanggal_global, 0, 7);
                $chk = $db->prepare("SELECT COUNT(*) FROM simpanan WHERE anggota_id=? AND jenis='wajib' AND tipe='setoran' AND DATE_FORMAT(tanggal,'%Y-%m')=?");
                $chk->execute([$aid, $ym]);
                if ($chk->fetchColumn() > 0) { $skipped++; continue; }
            }

            $ket = $keterangan_global ?: ($jenis_global === 'pokok' ? 'Simpanan pokok (global)' : 'Simpanan wajib ' . date('M Y', strtotime($tanggal_global)));
            $insertStmt->execute([$aid, $jenis_global, $jumlah_global, $tanggal_global, $ket, $_SESSION['user_id']]);
            $inserted++;
        }

        $jenisName = $jenis_global === 'pokok' ? 'pokok' : 'wajib';
        $msg = "Simpanan {$jenisName} berhasil dicatat untuk {$inserted} anggota.";
        if ($skipped) $msg .= " ({$skipped} anggota dilewati karena sudah ada.)";
        setFlash('success', $msg);
        header('Location: simpanan.php');
        exit;
    }
}

// ── GET: load edit / view data ───────────────────────────────────────────────
$editData = null;
$viewData = null;
if (isset($_GET['edit'])) {
    $stmt = $db->prepare("SELECT s.*, a.nama, a.no_anggota FROM simpanan s JOIN anggota a ON s.anggota_id=a.id WHERE s.id=?");
    $stmt->execute([$_GET['edit']]);
    $editData = $stmt->fetch();
}
if (isset($_GET['view'])) {
    $stmt = $db->prepare("SELECT s.*, a.nama, a.no_anggota FROM simpanan s JOIN anggota a ON s.anggota_id=a.id WHERE s.id=?");
    $stmt->execute([$_GET['view']]);
    $viewData = $stmt->fetch();
}

// Card-level edit
$editCardJenis = $_GET['edit_card'] ?? '';
if (!in_array($editCardJenis, ['pokok', 'sukarela', 'dana_pensiun'])) $editCardJenis = '';

// ── Filters ──────────────────────────────────────────────────────────────────
$search  = $_GET['search'] ?? '';
$jenis   = $_GET['jenis']  ?? '';
$tipe    = $_GET['tipe']   ?? '';
$page    = max(1, intval($_GET['page'] ?? 1));
$perPage = 15;
$offset  = ($page - 1) * $perPage;

$where  = "WHERE s.jenis NOT IN ('wajib')";
$params = [];
if ($search) {
    $where   .= " AND (a.nama LIKE ? OR a.no_anggota LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}
if ($jenis) { $where .= " AND s.jenis=?"; $params[] = $jenis; }
if ($tipe)  { $where .= " AND s.tipe=?";  $params[] = $tipe; }

$countStmt = $db->prepare("SELECT COUNT(*) FROM simpanan s JOIN anggota a ON s.anggota_id=a.id $where");
$countStmt->execute($params);
$totalRows  = $countStmt->fetchColumn();
$totalPages = ceil($totalRows / $perPage);

$stmt = $db->prepare("
    SELECT s.*, a.nama, a.no_anggota, a.foto as anggota_foto
    FROM simpanan s JOIN anggota a ON s.anggota_id=a.id
    $where ORDER BY s.tanggal DESC, s.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$simpananList = $stmt->fetchAll();

// ── Summary totals ────────────────────────────────────────────────────────────
$summaryStmt = $db->query("
    SELECT
        COALESCE(SUM(CASE WHEN jenis='pokok'        AND tipe='setoran' THEN jumlah WHEN jenis='pokok'        AND tipe='penarikan' THEN -jumlah ELSE 0 END),0) as total_pokok,
        COALESCE(SUM(CASE WHEN jenis='sukarela'     AND tipe='setoran' THEN jumlah WHEN jenis='sukarela'     AND tipe='penarikan' THEN -jumlah ELSE 0 END),0) as total_sukarela,
        COALESCE(SUM(CASE WHEN jenis='dana_pensiun' AND tipe='setoran' THEN jumlah WHEN jenis='dana_pensiun' AND tipe='penarikan' THEN -jumlah ELSE 0 END),0) as total_dana_pensiun
    FROM simpanan
    WHERE jenis NOT IN ('wajib')
");
$summary = $summaryStmt->fetch();

$cardTotals = [
    'pokok'        => $summary['total_pokok'],
    'sukarela'     => $summary['total_sukarela'],
    'dana_pensiun' => $summary['total_dana_pensiun'],
];

// ── Member lists ──────────────────────────────────────────────────────────────
$anggotaList       = $db->query("SELECT id, no_anggota, nama FROM anggota WHERE status='aktif' ORDER BY nama")->fetchAll();
$globalPokok       = floatval(getSetting('simpanan_pokok', 100000));
$globalWajib       = floatval(getSetting('simpanan_wajib',  50000));
$totalAnggotaAktif = (int)$db->query("SELECT COUNT(*) FROM anggota WHERE status='aktif'")->fetchColumn();

// Per-anggota saldo for modal (all jenis)
$anggotaSaldoCard = [];
$sudahBayarPokok = $belumBayarPokok = 0;
$sudahBayarWajibBulanIni = $belumBayarWajibBulanIni = 0;

if ($editCardJenis) {
    $cj = $editCardJenis;
    $anggotaSaldoCard = $db->query("
        SELECT a.id, a.no_anggota, a.nama, a.foto as anggota_foto,
            COALESCE(SUM(CASE WHEN s.tipe='setoran' THEN s.jumlah ELSE -s.jumlah END),0) as saldo
        FROM anggota a
        LEFT JOIN simpanan s ON s.anggota_id=a.id AND s.jenis='$cj'
        WHERE a.status='aktif'
        GROUP BY a.id, a.no_anggota, a.nama, a.foto ORDER BY a.nama
    ")->fetchAll();

    if ($cj === 'pokok') {
        $sudahBayarPokok = (int)$db->query("SELECT COUNT(DISTINCT anggota_id) FROM simpanan WHERE jenis='pokok'")->fetchColumn();
        $belumBayarPokok = $totalAnggotaAktif - $sudahBayarPokok;
    }
}

// ── Helper config ─────────────────────────────────────────────────────────────
$jenisConfig = [
    'pokok'        => ['label'=>'Simpanan Pokok',    'icon'=>'fa-coins',             'color'=>'primary', 'css'=>'var(--primary-500)'],
    'sukarela'     => ['label'=>'Simpanan Sukarela', 'icon'=>'fa-hand-holding-heart','color'=>'info',    'css'=>'var(--info-500)'],
    'dana_pensiun' => ['label'=>'Dana Pensiun',      'icon'=>'fa-umbrella',          'color'=>'warning', 'css'=>'var(--warning-500)'],
];

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

<!-- ═══════════════════════════════════════════════════════════════════════════
     SUMMARY CARDS
     ═══════════════════════════════════════════════════════════════════════════ -->
<div class="stats-grid" style="grid-template-columns:repeat(3,1fr);">
    <?php foreach ($cardTotals as $jenisKey => $total):
        $cfg = $jenisConfig[$jenisKey]; ?>
    <div class="stat-card <?=$cfg['color']?>" style="position:relative;overflow:visible;">
        <div class="stat-info">
            <h3><?=$cfg['label']?></h3>
            <div class="stat-value"><?=formatRupiah($total)?></div>
        </div>
        <div class="stat-icon <?=$cfg['color']?>"><i class="fas <?=$cfg['icon']?>"></i></div>
        <?php if ($jenisKey === 'pokok'): ?>
        <!-- Management link -->
        <a href="simpanan_pokok.php"
           title="Kelola Simpanan Pokok"
           style="position:absolute;top:10px;right:45px;width:28px;height:28px;background:rgba(255,255,255,0.85);border:1px solid rgba(0,0,0,0.08);border-radius:50%;display:flex;align-items:center;justify-content:center;text-decoration:none;box-shadow:0 1px 4px rgba(0,0,0,0.12);transition:all .2s;"
           onmouseover="this.style.background='white';this.style.boxShadow='0 2px 8px rgba(0,0,0,0.18)';"
           onmouseout="this.style.background='rgba(255,255,255,0.85)';this.style.boxShadow='0 1px 4px rgba(0,0,0,0.12)';">
            <i class="fas fa-tasks" style="font-size:0.65rem;color:<?=$cfg['css']?>;"></i>
        </a>
        <?php endif; ?>
        <!-- Edit button -->
        <a href="simpanan.php?edit_card=<?=$jenisKey?>"
           title="Edit <?=$cfg['label']?>"
           style="position:absolute;top:10px;right:10px;width:28px;height:28px;background:rgba(255,255,255,0.85);border:1px solid rgba(0,0,0,0.08);border-radius:50%;display:flex;align-items:center;justify-content:center;text-decoration:none;box-shadow:0 1px 4px rgba(0,0,0,0.12);transition:all .2s;"
           onmouseover="this.style.background='white';this.style.boxShadow='0 2px 8px rgba(0,0,0,0.18)';"
           onmouseout="this.style.background='rgba(255,255,255,0.85)';this.style.boxShadow='0 1px 4px rgba(0,0,0,0.12)';">
            <i class="fas fa-pen" style="font-size:0.65rem;color:<?=$cfg['css']?>;"></i>
        </a>
    </div>
    <?php endforeach; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     TRANSACTION TABLE
     ═══════════════════════════════════════════════════════════════════════════ -->
<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.php?search='+encodeURIComponent(this.value);">
            </div>
            <div class="filter-group">
                <select onchange="window.location='simpanan.php?jenis='+this.value+'&tipe=<?=urlencode($tipe)?>&search=<?=urlencode($search)?>'">
                    <option value="">Semua Jenis</option>
                    <option value="pokok"        <?=$jenis==='pokok'       ?'selected':''?>>Pokok</option>
                    <option value="sukarela"     <?=$jenis==='sukarela'    ?'selected':''?>>Sukarela</option>
                    <option value="dana_pensiun" <?=$jenis==='dana_pensiun'?'selected':''?>>Dana Pensiun</option>
                </select>
                <select onchange="window.location='simpanan.php?tipe='+this.value+'&jenis=<?=urlencode($jenis)?>&search=<?=urlencode($search)?>'">
                    <option value="">Semua Tipe</option>
                    <option value="setoran"   <?=$tipe==='setoran'  ?'selected':''?>>Setoran</option>
                    <option value="penarikan" <?=$tipe==='penarikan'?'selected':''?>>Penarikan</option>
                </select>
            </div>
            <div style="margin-left:auto; display:flex; gap:10px; align-items:center;">
                <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="../imports/import_simpanan_excel.php" class="btn btn-outline">
                    <i class="fas fa-file-import"></i> Import
                </a>
                <button class="btn btn-primary" onclick="openModal('addSimpananModal')">
                    <i class="fas fa-plus"></i> Tambah Transaksi
                </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>Tanggal</th><th>Anggota</th><th>Jenis</th>
                    <th>Tipe</th><th>Jumlah</th><th>Keterangan</th><th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($simpananList)): ?>
                    <tr><td colspan="9" class="text-center text-muted" style="padding:40px;">
                        <i class="fas fa-piggy-bank" style="font-size:2rem;display:block;margin-bottom:10px;color:var(--gray-300);"></i>
                        Tidak ada data simpanan
                    </td></tr>
                <?php else: ?>
                    <?php $nomor = 1; foreach ($simpananList as $s):
                        $jenisBadge = match($s['jenis']) { 'pokok'=>'badge-primary','sukarela'=>'badge-info','dana_pensiun'=>'badge-warning',default=>'badge-secondary' };
                        $jenisLabel = match($s['jenis']) { 'pokok'=>'Pokok','sukarela'=>'Sukarela','dana_pensiun'=>'Dana Pensiun',default=>ucfirst($s['jenis']) };
                    ?>
                    <tr>
                        <td style="text-align: center;">
                            <input type="checkbox" class="rowCheckbox" value="<?=$s['id']?>" onchange="updateBulkDeleteBtn()">
                        </td>
                        <td style="text-align: center; font-weight: bold;"><?=$nomor++?></td>
                        <td><?=formatTanggal($s['tanggal'])?></td>
                        <td>
                            <div class="member-cell">
                                <div class="member-avatar <?= !empty($s['anggota_foto']) ? '' : 'avatar-'.(($s['anggota_id']%6)+1) ?>" style="width:32px;height:32px;min-width:32px;font-size:0.7rem;<?= !empty($s['anggota_foto']) ? 'padding:0;overflow:hidden;' : '' ?>">
                                    <?php if (!empty($s['anggota_foto'])): ?>
                                        <img src="../uploads/anggota/<?=htmlspecialchars($s['anggota_foto'])?>" style="width:100%;height:100%;object-fit:cover;border-radius:50%;" alt="">
                                    <?php else: ?>
                                        <?=strtoupper(substr($s['nama'],0,2))?>
                                    <?php endif; ?>
                                </div>
                                <div class="member-details">
                                    <div class="member-name"><?=htmlspecialchars($s['nama'])?></div>
                                    <div class="member-id"><?=htmlspecialchars($s['no_anggota'])?></div>
                                </div>
                            </div>
                        </td>
                        <td><span class="badge <?=$jenisBadge?>"><?=$jenisLabel?></span></td>
                        <td>
                            <span class="badge <?=$s['tipe']==='setoran'?'badge-success':'badge-danger'?>">
                                <i class="fas fa-<?=$s['tipe']==='setoran'?'arrow-down':'arrow-up'?>"></i>
                                <?=ucfirst($s['tipe'])?>
                            </span>
                        </td>
                        <td class="<?=$s['tipe']==='setoran'?'text-success':'text-danger'?> fw-bold">
                            <?=$s['tipe']==='setoran'?'+':'-'?><?=formatRupiah($s['jumlah'])?>
                        </td>
                        <td><?=htmlspecialchars($s['keterangan']??'-')?></td>
                        <td>
                            <div class="action-buttons">
                                <a href="simpanan.php?view=<?=$s['id']?>" class="btn btn-icon btn-outline" title="Lihat">
                                    <i class="fas fa-eye" style="color:var(--info-500);"></i>
                                </a>
                                <a href="simpanan.php?edit=<?=$s['id']?>" class="btn btn-icon btn-outline" title="Edit">
                                    <i class="fas fa-pen" style="color:var(--warning-500);"></i>
                                </a>
                                <form method="POST" style="display:inline;" onsubmit="return confirm('Hapus transaksi ini?');">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?=$s['id']?>">
                                    <button type="submit" class="btn btn-icon btn-outline" title="Hapus">
                                        <i class="fas fa-trash" style="color:var(--danger-500);"></i>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPages > 1): ?>
    <div class="card-footer">
        <div class="pagination">
            <?php if ($page>1): ?><a href="simpanan.php?page=<?=$page-1?>&search=<?=urlencode($search)?>&jenis=<?=urlencode($jenis)?>&tipe=<?=urlencode($tipe)?>"><i class="fas fa-chevron-left"></i></a><?php endif; ?>
            <?php for($p=1;$p<=$totalPages;$p++): ?>
                <a href="simpanan.php?page=<?=$p?>&search=<?=urlencode($search)?>&jenis=<?=urlencode($jenis)?>&tipe=<?=urlencode($tipe)?>" class="<?=$p===$page?'active':''?>"><?=$p?></a>
            <?php endfor; ?>
            <?php if ($page<$totalPages): ?><a href="simpanan.php?page=<?=$page+1?>&search=<?=urlencode($search)?>&jenis=<?=urlencode($jenis)?>&tipe=<?=urlencode($tipe)?>"><i class="fas fa-chevron-right"></i></a><?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     MODAL: Add Transaction
     ═══════════════════════════════════════════════════════════════════════════ -->
<div class="modal" id="addSimpananModal">
    <div class="modal-header">
        <h3><i class="fas fa-piggy-bank" style="color:var(--success-500);margin-right:8px;"></i>Tambah Transaksi Simpanan</h3>
        <button class="modal-close" onclick="closeModal('addSimpananModal')"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="add">
        <div class="modal-body">
            <div class="form-group">
                <label>Anggota <span class="required">*</span></label>
                <select name="anggota_id" class="form-control" required>
                    <option value="">-- Pilih Anggota --</option>
                    <?php foreach ($anggotaList as $a): ?>
                        <option value="<?=$a['id']?>"><?=htmlspecialchars($a['no_anggota'].' - '.$a['nama'])?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Jenis Simpanan <span class="required">*</span></label>
                    <select name="jenis" class="form-control" required>
                        <option value="pokok">Pokok</option>
                        <option value="sukarela">Sukarela</option>
                        <option value="dana_pensiun">Dana Pensiun</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Tipe <span class="required">*</span></label>
                    <select name="tipe" class="form-control" required>
                        <option value="setoran">Setoran</option>
                        <option value="penarikan">Penarikan</option>
                    </select>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Jumlah (Rp) <span class="required">*</span></label>
                    <input type="text" name="jumlah" class="form-control" required placeholder="0" oninput="formatCurrencyInput(this)">
                </div>
                <div class="form-group">
                    <label>Tanggal <span class="required">*</span></label>
                    <input type="date" name="tanggal" class="form-control" required value="<?=date('Y-m-d')?>">
                </div>
            </div>
            <div class="form-group">
                <label>Keterangan</label>
                <textarea name="keterangan" class="form-control" rows="2" placeholder="Catatan tambahan (opsional)"></textarea>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('addSimpananModal')">Batal</button>
            <button type="submit" class="btn btn-success"><i class="fas fa-save"></i> Simpan</button>
        </div>
    </form>
</div>

<script>
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 + ' transaksi terpilih?')) {
        e.preventDefault();
        return false;
    }
    const form = document.getElementById('bulkDeleteForm');
    form.innerHTML = '<input type="hidden" name="action" value="delete_bulk">';
    checkboxes.forEach(cb => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'ids[]';
        input.value = cb.value;
        form.appendChild(input);
    });
    return true;
}
</script>

<!-- ═══════════════════════════════════════════════════════════════════════════
     MODAL: Edit Transaction (row-level)
     ═══════════════════════════════════════════════════════════════════════════ -->
<?php if ($editData): ?>
<script>document.addEventListener('DOMContentLoaded', () => openModal('editSimpananModal'));</script>
<div class="modal" id="editSimpananModal">
    <div class="modal-header">
        <h3><i class="fas fa-pen" style="color:var(--warning-500);margin-right:8px;"></i>Edit Transaksi Simpanan</h3>
        <button class="modal-close" onclick="window.location='simpanan.php'"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="edit">
        <input type="hidden" name="id" value="<?=$editData['id']?>">
        <div class="modal-body">
            <div class="form-group">
                <label>Anggota <span class="required">*</span></label>
                <select name="anggota_id" class="form-control" required>
                    <?php foreach ($anggotaList as $a): ?>
                        <option value="<?=$a['id']?>" <?=$editData['anggota_id']==$a['id']?'selected':''?>>
                            <?=htmlspecialchars($a['no_anggota'].' - '.$a['nama'])?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Jenis Simpanan <span class="required">*</span></label>
                    <select name="jenis" class="form-control" required>
                        <option value="pokok"        <?=$editData['jenis']==='pokok'       ?'selected':''?>>Pokok</option>
                        <option value="sukarela"     <?=$editData['jenis']==='sukarela'    ?'selected':''?>>Sukarela</option>
                        <option value="dana_pensiun" <?=$editData['jenis']==='dana_pensiun'?'selected':''?>>Dana Pensiun</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Tipe <span class="required">*</span></label>
                    <select name="tipe" class="form-control" required>
                        <option value="setoran"   <?=$editData['tipe']==='setoran'  ?'selected':''?>>Setoran</option>
                        <option value="penarikan" <?=$editData['tipe']==='penarikan'?'selected':''?>>Penarikan</option>
                    </select>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Jumlah (Rp) <span class="required">*</span></label>
                    <input type="text" name="jumlah" class="form-control" required
                           value="<?=number_format($editData['jumlah'],0,'','.')?>"
                           oninput="formatCurrencyInput(this)">
                </div>
                <div class="form-group">
                    <label>Tanggal <span class="required">*</span></label>
                    <input type="date" name="tanggal" class="form-control" required value="<?=$editData['tanggal']?>">
                </div>
            </div>
            <div class="form-group">
                <label>Keterangan</label>
                <textarea name="keterangan" class="form-control" rows="2"><?=htmlspecialchars($editData['keterangan']??'')?></textarea>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="window.location='simpanan.php'">Batal</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Perbarui</button>
        </div>
    </form>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
     MODAL: View Transaction
     ═══════════════════════════════════════════════════════════════════════════ -->
<?php if ($viewData): ?>
<script>document.addEventListener('DOMContentLoaded', () => openModal('viewSimpananModal'));</script>
<div class="modal" id="viewSimpananModal">
    <div class="modal-header">
        <h3><i class="fas fa-eye" style="color:var(--info-500);margin-right:8px;"></i>Detail Transaksi Simpanan</h3>
        <button class="modal-close" onclick="window.location='simpanan.php'"><i class="fas fa-times"></i></button>
    </div>
    <div class="modal-body">
        <div class="detail-grid">
            <div class="detail-item">
                <div class="detail-label">Anggota</div>
                <div class="detail-value"><?=htmlspecialchars($viewData['nama'])?> (<?=$viewData['no_anggota']?>)</div>
            </div>
            <div class="detail-item">
                <div class="detail-label">Tipe Transaksi</div>
                <div class="detail-value">
                    <span class="badge <?=$viewData['tipe']==='setoran'?'badge-success':'badge-danger'?>"><?=ucfirst($viewData['tipe'])?></span>
                </div>
            </div>
            <div class="detail-item">
                <div class="detail-label">Jenis Simpanan</div>
                <div class="detail-value">
                    <?php
                        $vLabel = match($viewData['jenis']) { 'pokok'=>'Pokok','wajib'=>'Wajib','sukarela'=>'Sukarela','dana_pensiun'=>'Dana Pensiun',default=>ucfirst($viewData['jenis']) };
                        $vBadge = match($viewData['jenis']) { 'pokok'=>'badge-primary','wajib'=>'badge-success','sukarela'=>'badge-info','dana_pensiun'=>'badge-warning',default=>'badge-secondary' };
                    ?>
                    <span class="badge <?=$vBadge?>"><?=$vLabel?></span>
                </div>
            </div>
            <div class="detail-item">
                <div class="detail-label">Jumlah</div>
                <div class="detail-value fw-bold <?=$viewData['tipe']==='setoran'?'text-success':'text-danger'?>"><?=formatRupiah($viewData['jumlah'])?></div>
            </div>
            <div class="detail-item">
                <div class="detail-label">Tanggal</div>
                <div class="detail-value"><?=formatTanggal($viewData['tanggal'])?></div>
            </div>
            <div class="detail-item">
                <div class="detail-label">Waktu Input</div>
                <div class="detail-value"><?=date('d M Y, H:i',strtotime($viewData['created_at']))?> WIB</div>
            </div>
        </div>
        <div class="form-group mt-3">
            <label>Keterangan</label>
            <div class="p-2 bg-gray-50 rounded" style="min-height:50px;"><?=nl2br(htmlspecialchars($viewData['keterangan']??'-'))?></div>
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-primary" onclick="window.location='simpanan.php'">Tutup</button>
    </div>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
     MODAL: Edit Card
       - Pokok / Wajib  → MODE GLOBAL (set amount, apply to all members)
       - Sukarela / Dana Pensiun → MODE PER-ANGGOTA (inline row editor)
     ═══════════════════════════════════════════════════════════════════════════ -->
<?php if ($editCardJenis):
    $cfg = $jenisConfig[$editCardJenis];
    $cardTotalSaldo = $cardTotals[$editCardJenis];
    $isGlobal = in_array($editCardJenis, ['pokok', 'wajib']);
?>
<script>document.addEventListener('DOMContentLoaded', () => openModal('editCardModal'));</script>
<div class="modal" id="editCardModal" style="max-width:640px;">
    <div class="modal-header">
        <h3>
            <i class="fas <?=$cfg['icon']?>" style="color:<?=$cfg['css']?>;margin-right:8px;"></i>
            <?=$isGlobal ? 'Pengaturan Global ' : 'Edit '?><?=$cfg['label']?>
        </h3>
        <button class="modal-close" onclick="window.location='simpanan.php'"><i class="fas fa-times"></i></button>
    </div>

    <?php if ($isGlobal):
        $currentGlobal = $editCardJenis === 'pokok' ? $globalPokok : $globalWajib;
    ?>
    <!-- ══════════════════════════════════════════
         MODE GLOBAL — Simpanan Pokok & Wajib
         ══════════════════════════════════════════ -->
    <form method="POST" onsubmit="return confirmApply()">
        <input type="hidden" name="action" value="set_global">
        <input type="hidden" name="jenis_global" value="<?=$editCardJenis?>">

    <div class="modal-body">

        <!-- Header stats -->
        <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:16px;">
            <!-- Total -->
            <div style="background:var(--gray-50);border:1px solid var(--gray-200);border-radius:var(--radius-md);padding:13px;text-align:center;">
                <div style="font-size:0.7rem;color:var(--gray-400);margin-bottom:4px;text-transform:uppercase;letter-spacing:.05em;">Total Terkumpul</div>
                <div style="font-size:1rem;font-weight:700;color:<?=$cfg['css']?>;"><?=formatRupiah($cardTotalSaldo)?></div>
            </div>
            <?php if ($editCardJenis === 'pokok'): ?>
            <!-- Sudah bayar -->
            <div style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:var(--radius-md);padding:13px;text-align:center;">
                <div style="font-size:0.7rem;color:#16a34a;margin-bottom:4px;text-transform:uppercase;letter-spacing:.05em;">Sudah Bayar</div>
                <div style="font-size:1.4rem;font-weight:700;color:#15803d;"><?=$sudahBayarPokok?> <span style="font-size:0.75rem;font-weight:400;color:#4ade80;">anggota</span></div>
            </div>
            <!-- Belum bayar -->
            <div style="background:#fffbeb;border:1px solid #fde68a;border-radius:var(--radius-md);padding:13px;text-align:center;">
                <div style="font-size:0.7rem;color:#d97706;margin-bottom:4px;text-transform:uppercase;letter-spacing:.05em;">Belum Bayar</div>
                <div style="font-size:1.4rem;font-weight:700;color:#b45309;"><?=$belumBayarPokok?> <span style="font-size:0.75rem;font-weight:400;color:#f59e0b;">anggota</span></div>
            </div>
            <?php else: ?>
            <!-- Sudah bayar bulan ini -->
            <div style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:var(--radius-md);padding:13px;text-align:center;">
                <div style="font-size:0.7rem;color:#16a34a;margin-bottom:4px;text-transform:uppercase;letter-spacing:.05em;">Sudah Bayar Bln Ini</div>
                <div style="font-size:1.4rem;font-weight:700;color:#15803d;"><?=$sudahBayarWajibBulanIni?> <span style="font-size:0.75rem;font-weight:400;color:#4ade80;">anggota</span></div>
            </div>
            <!-- Belum bayar bulan ini -->
            <div style="background:#fffbeb;border:1px solid #fde68a;border-radius:var(--radius-md);padding:13px;text-align:center;">
                <div style="font-size:0.7rem;color:#d97706;margin-bottom:4px;text-transform:uppercase;letter-spacing:.05em;">Belum Bayar Bln Ini</div>
                <div style="font-size:1.4rem;font-weight:700;color:#b45309;"><?=$belumBayarWajibBulanIni?> <span style="font-size:0.75rem;font-weight:400;color:#f59e0b;">anggota</span></div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Info banner -->
        <div style="background:<?=$cfg['css']?>12;border:1px solid <?=$cfg['css']?>35;border-radius:var(--radius-md);padding:10px 14px;margin-bottom:16px;display:flex;align-items:flex-start;gap:10px;font-size:0.83rem;color:var(--gray-700);line-height:1.5;">
            <i class="fas fa-globe" style="color:<?=$cfg['css']?>;margin-top:2px;flex-shrink:0;"></i>
            <?php if ($editCardJenis === 'pokok'): ?>
                <span><strong>Simpanan Pokok</strong> bersifat satu kali saat anggota mendaftar. Tentukan nominal, lalu klik <em>"Terapkan ke Semua Anggota"</em> — anggota yang belum membayar akan otomatis terisi.</span>
            <?php else: ?>
                <span><strong>Simpanan Wajib</strong> dibayar setiap bulan. Pilih bulan yang akan diisi &amp; masukkan nominal, lalu klik <em>"Terapkan ke Semua Anggota"</em> — anggota yang sudah membayar bulan tersebut akan dilewati.</span>
            <?php endif; ?>
        </div>

        <!-- Form input -->
        <div style="background:var(--gray-50);border:1px solid var(--gray-200);border-radius:var(--radius-md);padding:16px;">
            <div class="form-row">
                <div class="form-group">
                    <label>
                        Nominal <?=$cfg['label']?> (Rp) <span class="required">*</span>
                        <span style="font-size:0.7rem;color:var(--gray-400);font-weight:400;"> Saat ini: <?=formatRupiah($currentGlobal)?></span>
                    </label>
                    <input type="text" name="jumlah_global" id="global_jumlah"
                           class="form-control" required
                           value="<?=number_format($currentGlobal,0,'','.')?>"
                           oninput="formatCurrencyInput(this)"
                           style="font-size:1.15rem;font-weight:700;">
                </div>

                <?php if ($editCardJenis === 'wajib'): ?>
                <div class="form-group">
                    <label>Bulan Setoran <span class="required">*</span></label>
                    <input type="month" id="bulan_input" class="form-control" value="<?=date('Y-m')?>" onchange="syncBulan(this)">
                    <input type="hidden" name="tanggal_global" id="tanggal_hidden" value="<?=date('Y-m').'-01'?>">
                </div>
                <?php else: ?>
                <div class="form-group">
                    <label>Tanggal <span class="required">*</span></label>
                    <input type="date" name="tanggal_global" class="form-control" value="<?=date('Y-m-d')?>" required>
                </div>
                <?php endif; ?>
            </div>

            <div class="form-group" style="margin-bottom:12px;">
                <label>Keterangan</label>
                <input type="text" name="keterangan_global" class="form-control"
                       placeholder="<?=$editCardJenis==='pokok'?'Simpanan pokok pendaftaran':'Simpanan wajib '.date('F Y')?>">
            </div>

            <?php if ($editCardJenis === 'pokok'): ?>
            <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:0.875rem;color:var(--gray-700);margin:0;padding:8px 0;">
                <input type="checkbox" name="only_unpaid" id="only_unpaid_chk" checked style="width:15px;height:15px;accent-color:<?=$cfg['css']?>;">
                Hanya terapkan ke anggota yang <strong style="margin:0 3px;">belum pernah</strong> membayar simpanan pokok
            </label>
            <?php else: ?>
            <div style="font-size:0.8rem;color:var(--gray-500);display:flex;align-items:center;gap:6px;padding-top:4px;">
                <i class="fas fa-shield-alt" style="color:<?=$cfg['css']?>;"></i>
                Anggota yang sudah membayar di bulan yang dipilih akan dilewati otomatis
            </div>
            <?php endif; ?>
        </div>

    </div><!-- /.modal-body -->
    <div class="modal-footer" style="gap:10px;">
        <button type="button" class="btn btn-outline" onclick="window.location='simpanan.php'">Batal</button>
        <button type="submit" class="btn" style="background:<?=$cfg['css']?>;color:#fff;display:flex;align-items:center;gap:8px;">
            <i class="fas fa-users"></i> Terapkan ke Semua Anggota
        </button>
    </div>
    </form>

    <?php else: ?>
    <!-- ══════════════════════════════════════════
         MODE PER-ANGGOTA — Sukarela & Dana Pensiun
         ══════════════════════════════════════════ -->
    <div class="modal-body" style="padding-bottom:0;">

        <!-- Ringkasan card -->
        <div 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:<?=$cfg['css']?>20;display:flex;align-items:center;justify-content:center;">
                <i class="fas <?=$cfg['icon']?>" style="color:<?=$cfg['css']?>;font-size:1rem;"></i>
            </div>
            <div>
                <div style="font-size:0.73rem;color:var(--gray-500);">Total <?=$cfg['label']?></div>
                <div class="fw-bold" style="color:<?=$cfg['css']?>;"><?=formatRupiah($cardTotalSaldo)?></div>
            </div>
            <div style="margin-left:auto;font-size:0.8rem;color:var(--gray-400);"><?=count($anggotaSaldoCard)?> anggota</div>
        </div>

        <!-- Tabel anggota -->
        <div style="max-height:280px;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>Anggota</th>
                        <th class="text-right">Saldo</th>
                        <th class="text-center" style="width:60px;">Edit</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($anggotaSaldoCard)): ?>
                        <tr><td colspan="3" class="text-center text-muted" style="padding:30px;">Tidak ada anggota aktif</td></tr>
                    <?php else: foreach ($anggotaSaldoCard as $ag): ?>
                    <tr>
                        <td>
                            <div class="member-cell">
                                <div class="member-avatar <?= !empty($ag['anggota_foto']) ? '' : 'avatar-'.(($ag['id']%6)+1) ?>" style="width:30px;height:30px;min-width:30px;font-size:0.65rem;<?= !empty($ag['anggota_foto']) ? 'padding:0;overflow:hidden;' : '' ?>">
                                    <?php if (!empty($ag['anggota_foto'])): ?>
                                        <img src="../uploads/anggota/<?=htmlspecialchars($ag['anggota_foto'])?>" style="width:100%;height:100%;object-fit:cover;border-radius:50%;" alt="">
                                    <?php else: ?>
                                        <?=strtoupper(substr($ag['nama'],0,2))?>
                                    <?php endif; ?>
                                </div>
                                <div class="member-details">
                                    <div class="member-name" style="font-size:0.85rem;"><?=htmlspecialchars($ag['nama'])?></div>
                                    <div class="member-id"><?=htmlspecialchars($ag['no_anggota'])?></div>
                                </div>
                            </div>
                        </td>
                        <td class="text-right fw-bold" style="color:<?=$cfg['css']?>;"><?=formatRupiah($ag['saldo'])?></td>
                        <td class="text-center">
                            <button type="button" class="btn btn-icon btn-outline"
                                onclick="openEditRow(<?=$ag['id']?>, '<?=addslashes(htmlspecialchars($ag['nama']))?>', '<?=htmlspecialchars($ag['no_anggota'])?>', <?=floatval($ag['saldo'])?>, <?=($ag['id']%6)+1?>)">
                                <i class="fas fa-pen" style="color:<?=$cfg['css']?>;font-size:0.75rem;"></i>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Inline edit form -->
        <div id="inlineEditForm" style="display:none;margin-top:12px;padding:14px;background:var(--gray-50);border-radius:var(--radius-md);border:1px solid var(--gray-200);">
            <form method="POST">
                <input type="hidden" name="action" value="edit_saldo">
                <input type="hidden" name="jenis" value="<?=$editCardJenis?>">
                <input type="hidden" name="anggota_id" id="ief_anggota_id">

                <div style="display:flex;align-items:center;gap:10px;margin-bottom:12px;padding-bottom:12px;border-bottom:1px solid var(--gray-200);">
                    <div id="ief_avatar" class="member-avatar avatar-1" style="width:36px;height:36px;min-width:36px;"></div>
                    <div>
                        <div id="ief_nama" class="fw-bold" style="font-size:0.9rem;"></div>
                        <div id="ief_no" style="font-size:0.78rem;color:var(--gray-400);"></div>
                    </div>
                    <div style="margin-left:auto;text-align:right;">
                        <div style="font-size:0.7rem;color:var(--gray-400);">Saldo saat ini</div>
                        <div id="ief_current" class="fw-bold" style="color:<?=$cfg['css']?>;"></div>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label>Saldo Baru (Rp) <span class="required">*</span></label>
                        <input type="text" name="jumlah_baru" id="ief_jumlah" class="form-control" required
                               placeholder="0" oninput="formatCurrencyInput(this);previewSelisih();" style="font-weight:600;">
                    </div>
                    <div class="form-group">
                        <label>Tanggal <span class="required">*</span></label>
                        <input type="date" name="tanggal" class="form-control" value="<?=date('Y-m-d')?>" required>
                    </div>
                </div>
                <div id="ief_preview" style="display:none;padding:8px 12px;border-radius:4px;margin-bottom:10px;font-size:0.82rem;"></div>
                <div class="form-group" style="margin-bottom:10px;">
                    <label>Keterangan</label>
                    <input type="text" name="keterangan" id="ief_keterangan" class="form-control"
                           value="Penyesuaian saldo <?=$cfg['label']?>">
                </div>
                <div style="display:flex;gap:8px;justify-content:flex-end;">
                    <button type="button" class="btn btn-outline btn-sm" onclick="closeEditRow()">Batal</button>
                    <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-save"></i> Simpan</button>
                </div>
            </form>
        </div>

    </div><!-- /.modal-body -->
    <div class="modal-footer">
        <button type="button" class="btn btn-outline" onclick="window.location='simpanan.php'">Tutup</button>
    </div>
    <?php endif; ?>
</div><!-- /.modal -->

<script>
(function(){
    // === Global mode (Wajib: sync month picker) ===
    window.syncBulan = function(el) {
        document.getElementById('tanggal_hidden').value = el.value + '-01';
    };

    window.confirmApply = function() {
        var el = document.getElementById('global_jumlah');
        if (!el) return true;
        var nominal = parseInt(el.value.replace(/\./g,'')) || 0;
        if (nominal <= 0) { alert('Masukkan nominal yang valid.'); return false; }
        return confirm('Terapkan nominal Rp ' + nominal.toLocaleString('id-ID') + ' ke semua anggota aktif?\n\nAnggota yang sudah tercatat akan dilewati otomatis.');
    };

    // === Per-anggota inline editor (Sukarela / Dana Pensiun) ===
    var _saldo = 0;
    window.openEditRow = function(id, nama, no, saldo, avNum) {
        _saldo = saldo;
        document.getElementById('ief_anggota_id').value = id;
        var av = document.getElementById('ief_avatar');
        av.textContent  = nama.substring(0, 2).toUpperCase();
        av.className    = 'member-avatar avatar-' + avNum;
        av.style.cssText = 'width:36px;height:36px;min-width:36px;';
        document.getElementById('ief_nama').textContent    = nama;
        document.getElementById('ief_no').textContent      = no;
        document.getElementById('ief_current').textContent = 'Rp ' + saldo.toLocaleString('id-ID');
        document.getElementById('ief_jumlah').value        = saldo > 0 ? saldo.toLocaleString('id-ID').replace(/,/g, '.') : '0';
        document.getElementById('ief_preview').style.display = 'none';
        document.getElementById('inlineEditForm').style.display = 'block';
        document.getElementById('ief_jumlah').focus();
    };
    window.closeEditRow = function() {
        document.getElementById('inlineEditForm').style.display = 'none';
    };
    window.previewSelisih = function() {
        var raw = document.getElementById('ief_jumlah').value.replace(/\./g,'').replace(/,/g,'');
        var newVal  = parseFloat(raw) || 0;
        var selisih = newVal - _saldo;
        var el = document.getElementById('ief_preview');
        if (Math.abs(selisih) < 1) { el.style.display = 'none'; return; }
        el.style.display = 'block';
        if (selisih > 0) {
            el.style.cssText = 'display:block;padding:8px 12px;border-radius:4px;margin-bottom:10px;font-size:0.82rem;background:#f0fdf4;border:1px solid #bbf7d0;color:#166534;';
            el.innerHTML = '<i class="fas fa-arrow-up"></i> Akan dibuat <strong>Setoran Rp ' + Math.abs(selisih).toLocaleString('id-ID') + '</strong>';
        } else {
            el.style.cssText = 'display:block;padding:8px 12px;border-radius:4px;margin-bottom:10px;font-size:0.82rem;background:#fef2f2;border:1px solid #fecaca;color:#991b1b;';
            el.innerHTML = '<i class="fas fa-arrow-down"></i> Akan dibuat <strong>Penarikan Rp ' + Math.abs(selisih).toLocaleString('id-ID') + '</strong>';
        }
    };
})();
</script>
<?php endif; ?>

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