<?php
/**
 * Dana Pensiun Management
 * Koperasi Management System
 */

$pageTitle = 'Dana Pensiun';
$pageSubtitle = 'Kelola dana pensiun anggota koperasi';

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

// Debug endpoint - check data status
if (isset($_GET['check_data'])) {
    header('Content-Type: application/json; charset=utf-8');
    try {
        $count = $db->query("SELECT COUNT(*) as total FROM simpanan WHERE jenis='dana_pensiun'")->fetch();
        $allJenis = $db->query("SELECT DISTINCT jenis FROM simpanan")->fetchAll();
        $sample = $db->query("SELECT id, anggota_id, jenis, tipe, jumlah, tanggal FROM simpanan WHERE jenis='dana_pensiun' LIMIT 5")->fetchAll();
        
        echo json_encode([
            'status' => 'ok',
            'total_dana_pensiun' => $count['total'],
            'all_jenis_available' => $allJenis,
            'sample_records' => $sample ?: []
        ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

$JENIS = 'dana_pensiun';
$PAGE_FILE = 'simpanan_dana_pensiun.php';

// ── 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'],
            $JENIS,
            $_POST['tipe'],
            str_replace('.', '', $_POST['jumlah']),
            $_POST['tanggal'],
            sanitize($_POST['keterangan'] ?? ''),
            $_SESSION['user_id']
        ]);
        setFlash('success', 'Transaksi dana pensiun berhasil dicatat.');
        header("Location: $PAGE_FILE");
        exit;
    }

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

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

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

    if ($action === 'edit_saldo') {
        $anggota_id  = intval($_POST['anggota_id']);
        $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]);
        $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, $tipeAdj, abs($selisih), $tanggal, $keterangan, $_SESSION['user_id']]);
        }

        setFlash('success', 'Saldo dana pensiun berhasil diperbarui.');
        header("Location: $PAGE_FILE");
        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=? AND s.jenis=?");
    $stmt->execute([$_GET['edit'], $JENIS]);
    $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=? AND s.jenis=?");
    $stmt->execute([$_GET['view'], $JENIS]);
    $viewData = $stmt->fetch();
}

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

$where  = "WHERE s.jenis = ?";
$params = [$JENIS];

if ($selectedBulan) {
    $where .= " AND DATE_FORMAT(s.tanggal, '%Y-%m') = ?";
    $params[] = $selectedBulan;
}

if ($search) {
    $where   .= " AND (a.nama LIKE ? OR a.no_anggota LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}
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();

// 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.tipe, s.tanggal, s.keterangan
        FROM simpanan s
        WHERE s.anggota_id = ? AND s.jenis = 'dana_pensiun'
        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]);
    $info = $nameStmt->fetch();
    
    $totalSetor = 0; $totalTarik = 0;
    foreach ($rows as &$r) {
        if ($r['tipe'] === 'setoran') $totalSetor += $r['jumlah'];
        else $totalTarik += $r['jumlah'];
    }
    
    echo json_encode(['nama' => $info['nama'], 'no_anggota' => $info['no_anggota'], 'rows' => $rows, 'total_setor' => $totalSetor, 'total_tarik' => $totalTarik, 'saldo' => $totalSetor - $totalTarik]);
    exit;
}

// ── Summary Bulan Ini (or all if no bulan selected) ──────────────────────────
if ($selectedBulan) {
    $summaryBulanStmt = $db->prepare("
        SELECT
            COALESCE(SUM(CASE WHEN s.tipe='setoran' THEN s.jumlah ELSE 0 END),0) as total_setoran,
            COALESCE(SUM(CASE WHEN s.tipe='penarikan' THEN s.jumlah ELSE 0 END),0) as total_penarikan
        FROM simpanan s JOIN anggota a ON s.anggota_id = a.id
        WHERE s.jenis = ? AND DATE_FORMAT(s.tanggal, '%Y-%m') = ?
    ");
    $summaryBulanStmt->execute([$JENIS, $selectedBulan]);
} else {
    $summaryBulanStmt = $db->prepare("
        SELECT
            COALESCE(SUM(CASE WHEN s.tipe='setoran' THEN s.jumlah ELSE 0 END),0) as total_setoran,
            COALESCE(SUM(CASE WHEN s.tipe='penarikan' THEN s.jumlah ELSE 0 END),0) as total_penarikan
        FROM simpanan s JOIN anggota a ON s.anggota_id = a.id
        WHERE s.jenis = ?
    ");
    $summaryBulanStmt->execute([$JENIS]);
}
$summaryBulan = $summaryBulanStmt->fetch();

// ── Summary Keseluruhan ──────────────────────────────────────────────────────
$summaryStmt = $db->prepare("
    SELECT
        COALESCE(SUM(CASE WHEN s.tipe='setoran' THEN s.jumlah ELSE 0 END),0) as total_setoran,
        COALESCE(SUM(CASE WHEN s.tipe='penarikan' THEN s.jumlah ELSE 0 END),0) as total_penarikan,
        COALESCE(SUM(CASE WHEN s.tipe='setoran' THEN s.jumlah ELSE -s.jumlah END),0) as saldo
    FROM simpanan s JOIN anggota a ON s.anggota_id = a.id
    WHERE s.jenis = ?
");
$summaryStmt->execute([$JENIS]);
$summary = $summaryStmt->fetch();

// ── Member lists ─────────────────────────────────────────────────────────────
$anggotaList = $db->query("SELECT id, no_anggota, nama FROM anggota WHERE status='aktif' ORDER BY nama")->fetchAll();

// Per-anggota saldo
$editCard = isset($_GET['edit_card']);
$anggotaSaldoCard = [];
if ($editCard) {
    $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='$JENIS'
        WHERE a.status='aktif'
        GROUP BY a.id, a.no_anggota, a.nama, a.foto ORDER BY a.nama
    ")->fetchAll();
}

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

<!-- Summary Cards -->
<div class="stats-grid" style="grid-template-columns:repeat(3,1fr);">
    <div class="stat-card warning" style="position:relative;">
        <div class="stat-info">
            <h3>Total Setoran</h3>
            <div class="stat-value"><?=formatRupiah($summary['total_setoran'])?></div>
        </div>
        <div class="stat-icon warning"><i class="fas fa-arrow-down"></i></div>
    </div>
    <div class="stat-card danger" style="position:relative;">
        <div class="stat-info">
            <h3>Total Penarikan</h3>
            <div class="stat-value"><?=formatRupiah($summary['total_penarikan'])?></div>
        </div>
        <div class="stat-icon danger"><i class="fas fa-arrow-up"></i></div>
    </div>
    <div class="stat-card primary" style="position:relative;overflow:visible;">
        <div class="stat-info">
            <h3>Saldo Dana Pensiun</h3>
            <div class="stat-value"><?=formatRupiah($summary['saldo'])?></div>
        </div>
        <div class="stat-icon primary"><i class="fas fa-umbrella"></i></div>
        <a href="<?=$PAGE_FILE?>?edit_card=1"
           title="Edit Per Anggota"
           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:var(--warning-500);"></i>
        </a>
    </div>
</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='<?=$PAGE_FILE?>?search='+encodeURIComponent(this.value);">
            </div>
            <div class="filter-group" style="display:flex; align-items:center; gap:8px;">
                <label style="font-size:0.85rem; font-weight:600; color:var(--gray-700); margin:0;">Bulan:</label>
                <input type="month" value="<?=$selectedBulan?>" class="form-control"
                       onchange="window.location='<?=$PAGE_FILE?>?bulan='+this.value+'&tipe=<?=urlencode($tipe)?>&search=<?=urlencode($search)?>'"
                       style="padding:6px 10px; width:auto; height:38px;">
                <?php if($selectedBulan): ?>
                    <a href="<?=$PAGE_FILE?>?tipe=<?=urlencode($tipe)?>&search=<?=urlencode($search)?>" class="btn btn-outline" style="padding:6px 10px; height:38px; display:flex; align-items:center;" title="Tampilkan Semua Bulan">
                        <i class="fas fa-times"></i>
                    </a>
                <?php endif; ?>
            </div>
            <div class="filter-group">
                <select onchange="window.location='<?=$PAGE_FILE?>?bulan=<?=urlencode($selectedBulan)?>&tipe='+this.value+'&search=<?=urlencode($search)?>'" style="height:38px;">
                    <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?return=dana_pensiun" class="btn btn-success">
                    <i class="fas fa-file-import"></i> Import Excel
                </a>
                <a href="simpanan_dana_pensiun_rekap_umum.php" class="btn btn-outline-info">
                    <i class="fas fa-file-invoice"></i> Rekap Dana Pensiun
                </a>
                <button class="btn btn-primary" onclick="openModal('addModal')">
                    <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;">No</th>
                    <th>Tanggal</th><th>Anggota</th>
                    <th>Tipe</th><th>Jumlah</th><th>Keterangan</th><th>Saldo</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-umbrella" style="font-size:2rem;display:block;margin-bottom:10px;color:var(--gray-300);"></i>
                        Tidak ada data dana pensiun
                    </td></tr>
                <?php else: ?>
                    <?php $nomor = $offset + 1; foreach ($simpananList as $s): ?>
                    <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 <?=$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>
                            <?php
                            $saldoStmt = $db->prepare("SELECT COALESCE(SUM(CASE WHEN tipe='setoran' THEN jumlah ELSE -jumlah END),0) FROM simpanan WHERE anggota_id=? AND jenis='dana_pensiun'");
                            $saldoStmt->execute([$s['anggota_id']]);
                            $saldoAnggota = $saldoStmt->fetchColumn();
                            ?>
                            <a href="javascript:void(0)" onclick="showDetailDanaPensiun(<?=$s['anggota_id']?>)"
                               style="color:var(--warning-600);font-weight:700;text-decoration:none;cursor:pointer;white-space:nowrap;"
                               title="Klik untuk lihat rincian">
                                <?=formatRupiah($saldoAnggota)?>
                            </a>
                        </td>
                        <td>
                            <div class="action-buttons">
                                <a href="<?=$PAGE_FILE?>?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="<?=$PAGE_FILE?>?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>
            <tfoot style="background: var(--gray-50);">
                <tr style="border-top: 2px solid var(--gray-200); font-weight: 700;">
                    <td colspan="5" style="padding: 16px; text-align: right; color: var(--gray-700);">
                        <strong>
                            TOTAL SETORAN 
                            <?= $selectedBulan ? 'BULAN ' . strtoupper(date('F Y', strtotime($selectedBulan.'-01'))) : '(SEMUA DATA)' ?>
                        </strong>
                    </td>
                    <td style="padding: 16px; text-align: left; background: var(--success-50); color: var(--success-700); font-weight: 800; border-radius: 0;">
                        <?=formatRupiah($summaryBulan['total_setoran'])?>
                    </td>
                    <td colspan="3"></td>
                </tr>
                <tr style="border-top: 1px solid var(--gray-200); font-weight: 700;">
                    <td colspan="5" style="padding: 16px; text-align: right; color: var(--gray-700);">
                        <strong>TOTAL KESELURUHAN SETORAN</strong>
                    </td>
                    <td style="padding: 16px; text-align: left; background: var(--primary-50); color: var(--primary-700); font-weight: 800; border-radius: 0;">
                        <?=formatRupiah($summary['total_setoran'])?>
                    </td>
                    <td colspan="3"></td>
                </tr>
                <tr style="border-top: 1px solid var(--gray-200); font-weight: 700;">
                    <td colspan="5" style="padding: 16px; text-align: right; color: var(--gray-700);">
                        <strong>TOTAL KESELURUHAN PENARIKAN</strong>
                    </td>
                    <td style="padding: 16px; text-align: left; background: var(--danger-50); color: var(--danger-700); font-weight: 800; border-radius: 0;">
                        <?=formatRupiah($summary['total_penarikan'])?>
                    </td>
                    <td colspan="3"></td>
                </tr>
            </tfoot>
        </table>
    </div>

    <?php if ($totalPages > 1): ?>
    <div class="card-footer">
        <div class="pagination">
            <?php if ($page>1): ?><a href="<?=$PAGE_FILE?>?page=<?=$page-1?>&bulan=<?=urlencode($selectedBulan)?>&search=<?=urlencode($search)?>&tipe=<?=urlencode($tipe)?>"><i class="fas fa-chevron-left"></i></a><?php endif; ?>
            <?php for($p=1;$p<=$totalPages;$p++): ?>
                <a href="<?=$PAGE_FILE?>?page=<?=$p?>&bulan=<?=urlencode($selectedBulan)?>&search=<?=urlencode($search)?>&tipe=<?=urlencode($tipe)?>" class="<?=$p===$page?'active':''?>"><?=$p?></a>
            <?php endfor; ?>
            <?php if ($page<$totalPages): ?><a href="<?=$PAGE_FILE?>?page=<?=$page+1?>&bulan=<?=urlencode($selectedBulan)?>&search=<?=urlencode($search)?>&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="addModal">
    <div class="modal-header">
        <h3><i class="fas fa-umbrella" style="color:var(--warning-500);margin-right:8px;"></i>Tambah Dana Pensiun</h3>
        <button class="modal-close" onclick="closeModal('addModal')"><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" style="position:relative;">
                <label>Anggota <span class="required">*</span></label>
                <input type="hidden" name="anggota_id" id="add_anggota_id" required>
                <input type="text" id="add_anggota_search" class="form-control" placeholder="Ketik nama anggota..." autocomplete="off" required
                       onfocus="showSuggestions('add')" oninput="filterAnggota('add')">
                <div id="add_suggestions" class="autocomplete-suggestions" style="display:none;"></div>
            </div>
            <div class="form-row">
                <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 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>
            <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 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('addModal')">Batal</button>
            <button type="submit" class="btn btn-success"><i class="fas fa-save"></i> Simpan</button>
        </div>
    </form>
</div>

<!-- MODAL: Edit Transaction -->
<?php if ($editData): ?>
<script>document.addEventListener('DOMContentLoaded', () => openModal('editModal'));</script>
<div class="modal" id="editModal">
    <div class="modal-header">
        <h3><i class="fas fa-pen" style="color:var(--warning-500);margin-right:8px;"></i>Edit Dana Pensiun</h3>
        <button class="modal-close" onclick="window.location='<?=$PAGE_FILE?>'"><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" style="position:relative;">
                <label>Anggota <span class="required">*</span></label>
                <input type="hidden" name="anggota_id" id="edit_anggota_id" value="<?=$editData['anggota_id']?>" required>
                <input type="text" id="edit_anggota_search" class="form-control" autocomplete="off" required
                       value="<?=htmlspecialchars($editData['no_anggota'].' - '.$editData['nama'])?>"
                       onfocus="showSuggestions('edit')" oninput="filterAnggota('edit')">
                <div id="edit_suggestions" class="autocomplete-suggestions" style="display:none;"></div>
            </div>
            <div class="form-row">
                <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 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>
            <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 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='<?=$PAGE_FILE?>'">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('viewModal'));</script>
<div class="modal" id="viewModal">
    <div class="modal-header">
        <h3><i class="fas fa-eye" style="color:var(--info-500);margin-right:8px;"></i>Detail Dana Pensiun</h3>
        <button class="modal-close" onclick="window.location='<?=$PAGE_FILE?>'"><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">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='<?=$PAGE_FILE?>'">Tutup</button>
    </div>
</div>
<?php endif; ?>

<!-- MODAL: Edit Saldo Per Anggota -->
<?php if ($editCard): ?>
<script>document.addEventListener('DOMContentLoaded', () => openModal('editCardModal'));</script>
<div class="modal" id="editCardModal" style="max-width:640px;">
    <div class="modal-header">
        <h3><i class="fas fa-umbrella" style="color:var(--warning-500);margin-right:8px;"></i>Edit Saldo Dana Pensiun Per Anggota</h3>
        <button class="modal-close" onclick="window.location='<?=$PAGE_FILE?>'"><i class="fas fa-times"></i></button>
    </div>
    <div class="modal-body" style="padding-bottom:0;">
        <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:var(--warning-500)20;display:flex;align-items:center;justify-content:center;">
                <i class="fas fa-umbrella" style="color:var(--warning-500);font-size:1rem;"></i>
            </div>
            <div>
                <div style="font-size:0.73rem;color:var(--gray-500);">Total Dana Pensiun</div>
                <div class="fw-bold" style="color:var(--warning-500);"><?=formatRupiah($summary['saldo'])?></div>
            </div>
            <div style="margin-left:auto;font-size:0.8rem;color:var(--gray-400);"><?=count($anggotaSaldoCard)?> anggota</div>
        </div>

        <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 id="row_<?=$ag['id']?>">
                        <td>
                            <div class="member-cell">
                                <div class="member-avatar <?= !empty($ag['anggota_foto']) ? '' : 'avatar-'.(($ag['id']%6)+1) ?>" style="width:28px;height:28px;min-width:28px;font-size:0.6rem;<?= !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.82rem;"><?=htmlspecialchars($ag['nama'])?></div>
                                    <div class="member-id"><?=$ag['no_anggota']?></div>
                                </div>
                            </div>
                        </td>
                        <td class="text-right fw-bold" style="color:var(--warning-500);"><?=formatRupiah($ag['saldo'])?></td>
                        <td class="text-center">
                            <button type="button" class="btn btn-icon btn-outline" onclick="editSaldoRow(<?=$ag['id']?>, '<?=htmlspecialchars($ag['nama'])?>', <?=$ag['saldo']?>)" title="Edit Saldo">
                                <i class="fas fa-pen" style="font-size:0.7rem;color:var(--warning-500);"></i>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-primary" onclick="window.location='<?=$PAGE_FILE?>'">Tutup</button>
    </div>
</div>

<!-- Inline Edit Saldo Modal -->
<div class="modal" id="editSaldoModal" style="max-width:400px;">
    <div class="modal-header">
        <h3><i class="fas fa-pen" style="color:var(--warning-500);margin-right:8px;"></i>Edit Saldo</h3>
        <button class="modal-close" onclick="closeModal('editSaldoModal')"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="edit_saldo">
        <input type="hidden" name="anggota_id" id="saldo_anggota_id">
        <div class="modal-body">
            <p style="margin-bottom:12px;font-size:0.9rem;">Anggota: <strong id="saldo_nama"></strong></p>
            <div class="form-group">
                <label>Saldo Baru (Rp) <span class="required">*</span></label>
                <input type="text" name="jumlah_baru" id="saldo_jumlah" class="form-control" required oninput="formatCurrencyInput(this)" style="font-size:1.1rem;font-weight:700;">
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Tanggal</label>
                    <input type="date" name="tanggal" class="form-control" value="<?=date('Y-m-d')?>">
                </div>
                <div class="form-group">
                    <label>Keterangan</label>
                    <input type="text" name="keterangan" class="form-control" value="Penyesuaian saldo">
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('editSaldoModal')">Batal</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Simpan</button>
        </div>
    </form>
</div>
<?php endif; ?>

<!-- MODAL: Detail Dana Pensiun Per Anggota -->
<div class="modal" id="detailDanaPensiunModal" style="max-width:650px;">
    <div class="modal-header">
        <h3><i class="fas fa-list" style="color:var(--warning-500);margin-right:8px;"></i>Rincian Dana Pensiun</h3>
        <button class="modal-close" onclick="closeModal('detailDanaPensiunModal')"><i class="fas fa-times"></i></button>
    </div>
    <div class="modal-body">
        <div id="detailDPInfo" 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(--warning-500)20;display:flex;align-items:center;justify-content:center;">
                <i class="fas fa-umbrella" style="color:var(--warning-500);font-size:1rem;"></i>
            </div>
            <div>
                <div id="detDPNama" style="font-weight:700;color:var(--gray-800);">-</div>
                <div id="detDPNoAnggota" 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;">Saldo Saat Ini</div>
                <div id="detDPSaldo" style="font-weight:800;color:var(--warning-600);font-size:1.1rem;">-</div>
            </div>
        </div>
        
        <div class="row mb-3" style="display: flex; gap: 10px;">
            <div style="flex: 1; background: #ecfdf5; padding: 10px; border-radius: 8px; border-left: 4px solid #10b981;">
                <div style="font-size: 0.75rem; color: #059669; font-weight: 600;">Total Setoran</div>
                <div id="detDPTotalSetor" style="font-weight: 700; color: #065f46;">Rp 0</div>
            </div>
            <div style="flex: 1; background: #fef2f2; padding: 10px; border-radius: 8px; border-left: 4px solid #ef4444;">
                <div style="font-size: 0.75rem; color: #dc2626; font-weight: 600;">Total Penarikan</div>
                <div id="detDPTotalTarik" style="font-weight: 700; color: #991b1b;">Rp 0</div>
            </div>
        </div>

        <div id="detailDPLoading" 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="detailDPContent" style="max-height:300px;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>Tanggal</th>
                        <th>Tipe</th>
                        <th class="text-right">Jumlah</th>
                    </tr>
                </thead>
                <tbody id="detailDPBody"></tbody>
            </table>
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-primary" onclick="closeModal('detailDanaPensiunModal')">Tutup</button>
    </div>
</div>

<style>
.autocomplete-suggestions {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    border: 1px solid var(--gray-200);
    border-top: none;
    border-radius: 0 0 var(--radius-md) var(--radius-md);
    max-height: 200px;
    overflow-y: auto;
    z-index: 1000;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
.autocomplete-suggestions .sug-item {
    padding: 10px 14px;
    cursor: pointer;
    font-size: 0.88rem;
    border-bottom: 1px solid var(--gray-100);
    display: flex;
    align-items: center;
    gap: 10px;
    transition: background 0.15s;
}
.autocomplete-suggestions .sug-item:last-child { border-bottom: none; }
.autocomplete-suggestions .sug-item:hover,
.autocomplete-suggestions .sug-item.active {
    background: var(--primary-50, #eff6ff);
}
.autocomplete-suggestions .sug-item .sug-avatar {
    width: 28px; height: 28px; min-width: 28px;
    border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    font-size: 0.6rem; font-weight: 700; color: white;
    background: var(--primary-500);
}
.autocomplete-suggestions .sug-item .sug-name { font-weight: 600; color: var(--gray-800); }
.autocomplete-suggestions .sug-item .sug-id { font-size: 0.75rem; color: var(--gray-400); }
.autocomplete-suggestions .sug-empty {
    padding: 16px; text-align: center; color: var(--gray-400); font-size: 0.85rem;
}
</style>

<script>
// Anggota data for autocomplete
const anggotaData = [
<?php foreach ($anggotaList as $a): ?>
    { id: <?=$a['id']?>, no: '<?=addslashes($a['no_anggota'])?>', nama: '<?=addslashes($a['nama'])?>'},
<?php endforeach; ?>
];

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

function showDetailDanaPensiun(anggotaId) {
    const loading = document.getElementById('detailDPLoading');
    const content = document.getElementById('detailDPContent');
    const body = document.getElementById('detailDPBody');
    
    loading.style.display = 'block';
    content.style.display = 'none';
    
    openModal('detailDanaPensiunModal');
    
    fetch('simpanan_dana_pensiun.php?ajax_detail=' + anggotaId)
        .then(r => r.json())
        .then(data => {
            loading.style.display = 'none';
            content.style.display = 'block';
            
            document.getElementById('detDPNama').textContent = data.nama;
            document.getElementById('detDPNoAnggota').textContent = data.no_anggota;
            document.getElementById('detDPSaldo').textContent = formatRupiahJS(data.saldo);
            document.getElementById('detDPTotalSetor').textContent = formatRupiahJS(data.total_setor);
            document.getElementById('detDPTotalTarik').textContent = formatRupiahJS(data.total_tarik);
            
            if (data.rows.length === 0) {
                body.innerHTML = '<tr><td colspan="4" class="text-center text-muted" style="padding:20px;">Belum ada data</td></tr>';
            } else {
                let html = '';
                data.rows.forEach((row, i) => {
                    const tgl = new Date(row.tanggal).toLocaleDateString('id-ID', {day:'2-digit', month:'short', year:'numeric'});
                    const color = row.tipe === 'setoran' ? 'text-success' : 'text-danger';
                    const prefix = row.tipe === 'setoran' ? '+' : '-';
                    html += `<tr>
                        <td style="text-align:center;">${i+1}</td>
                        <td>${tgl}</td>
                        <td><span class="badge ${row.tipe === 'setoran' ? 'badge-success' : 'badge-danger'}">${row.tipe}</span></td>
                        <td class="text-right fw-bold ${color}">${prefix}${formatRupiahJS(row.jumlah)}</td>
                    </tr>`;
                });
                body.innerHTML = html;
            }
        });
}

function filterAnggota(prefix) {
    const input = document.getElementById(prefix + '_anggota_search');
    const sugBox = document.getElementById(prefix + '_suggestions');
    const hiddenInput = document.getElementById(prefix + '_anggota_id');
    const query = input.value.toLowerCase().trim();

    hiddenInput.value = '';

    if (query.length === 0) {
        showSuggestions(prefix);
        return;
    }

    const filtered = anggotaData.filter(a =>
        a.nama.toLowerCase().includes(query) || a.no.toLowerCase().includes(query)
    );

    renderSuggestions(prefix, filtered);
}

function showSuggestions(prefix) {
    renderSuggestions(prefix, anggotaData);
}

function renderSuggestions(prefix, list) {
    const sugBox = document.getElementById(prefix + '_suggestions');
    
    if (list.length === 0) {
        sugBox.innerHTML = '<div class="sug-empty"><i class="fas fa-search" style="margin-right:6px;"></i>Anggota tidak ditemukan</div>';
        sugBox.style.display = 'block';
        return;
    }

    const colors = ['#3b82f6','#10b981','#f59e0b','#ef4444','#8b5cf6','#ec4899'];
    let html = '';
    list.forEach(a => {
        const bg = colors[a.id % colors.length];
        const initials = a.nama.substring(0,2).toUpperCase();
        html += `<div class="sug-item" onclick="selectAnggota('${prefix}', ${a.id}, '${a.no.replace(/'/g, "\\'")  }', '${a.nama.replace(/'/g, "\\'")}')">
            <div class="sug-avatar" style="background:${bg}">${initials}</div>
            <div>
                <div class="sug-name">${a.nama}</div>
                <div class="sug-id">${a.no}</div>
            </div>
        </div>`;
    });
    sugBox.innerHTML = html;
    sugBox.style.display = 'block';
}

function selectAnggota(prefix, id, no, nama) {
    document.getElementById(prefix + '_anggota_id').value = id;
    document.getElementById(prefix + '_anggota_search').value = no + ' - ' + nama;
    document.getElementById(prefix + '_suggestions').style.display = 'none';
}

document.addEventListener('click', function(e) {
    ['add', 'edit'].forEach(prefix => {
        const input = document.getElementById(prefix + '_anggota_search');
        const sugBox = document.getElementById(prefix + '_suggestions');
        if (input && sugBox && !input.contains(e.target) && !sugBox.contains(e.target)) {
            sugBox.style.display = 'none';
        }
    });
});

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

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

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

function editSaldoRow(id, nama, saldo) {
    document.getElementById('saldo_anggota_id').value = id;
    document.getElementById('saldo_nama').textContent = nama;
    document.getElementById('saldo_jumlah').value = saldo > 0 ? new Intl.NumberFormat('id-ID').format(saldo) : '0';
    openModal('editSaldoModal');
}
</script>

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