<?php
/**
 * Simpanan Sukarela Management - Monthly Settings Version
 * Koperasi Management System
 */

$pageTitle = 'Simpanan Sukarela';
$pageSubtitle = 'Kelola simpanan sukarela anggota koperasi dengan pengaturan bulanan';

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

// ── TEST: Cek database untuk debug ────────────────────────────────────────────
if (isset($_GET['ajax_test_db'])) {
    header('Content-Type: application/json; charset=utf-8');
    try {
        $count = $db->query("SELECT COUNT(*) as total FROM anggota WHERE status = 'aktif'")->fetch(PDO::FETCH_ASSOC);
        $sample = $db->query("SELECT id, nama, no_anggota FROM anggota WHERE status = 'aktif' LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'status' => 'ok',
            'total_anggota_aktif' => $count['total'],
            'sample_data' => $sample
        ]);
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// ── Handle AJAX request for member search (PRIORITAS TINGGI) ──────────────────
if (isset($_GET['ajax_search_members'])) {
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-cache, no-store, must-revalidate');
    
    try {
        $searchTerm = isset($_GET['q']) ? trim($_GET['q']) : '';
        
        error_log('AJAX Search - Q: ' . $searchTerm);
        
        // Build query
        $where = "WHERE a.status = 'aktif'";
        $params = [];
        
        if ($searchTerm !== '') {
            $where .= " AND (a.nama LIKE ? OR a.no_anggota LIKE ?)";
            $params[] = "%{$searchTerm}%";
            $params[] = "%{$searchTerm}%";
        }
        
        $sql = "SELECT a.id, a.no_anggota, a.nama FROM anggota a {$where} ORDER BY a.nama ASC LIMIT 20";
        
        error_log('SQL: ' . $sql);
        error_log('Params: ' . json_encode($params));
        
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        error_log('Results count: ' . count($results));
        
        // Return JSON
        $response = $results ?? [];
        echo json_encode($response);
        
    } catch (Exception $e) {
        error_log('AJAX Search Error: ' . $e->getMessage());
        http_response_code(500);
        echo json_encode([
            'error' => $e->getMessage(),
            'code' => $e->getCode()
        ]);
    }
    exit;
}

// ── Handle AJAX request for member detail ──────────────────────────────────────
if (isset($_GET['ajax_detail'])) {
    header('Content-Type: application/json; charset=utf-8');
    try {
        $aid = intval($_GET['ajax_detail']);
        $detailStmt = $db->prepare("
            SELECT s.jumlah, s.tanggal, s.keterangan, DATE_FORMAT(s.tanggal, '%Y-%m') as bulan
            FROM simpanan s
            WHERE s.anggota_id = ? AND s.jenis = 'sukarela' AND s.tipe = 'setoran'
            ORDER BY s.tanggal DESC
        ");
        $detailStmt->execute([$aid]);
        $rows = $detailStmt->fetchAll(PDO::FETCH_ASSOC);

        $nameStmt = $db->prepare("SELECT nama, no_anggota FROM anggota WHERE id = ?");
        $nameStmt->execute([$aid]);
        $anggotaInfo = $nameStmt->fetch(PDO::FETCH_ASSOC);

        $total = 0;
        foreach ($rows as &$r) { $total += $r['jumlah']; }

        echo json_encode(['nama' => $anggotaInfo['nama'] ?? '-', 'no_anggota' => $anggotaInfo['no_anggota'] ?? '-', 'rows' => $rows, 'total' => $total]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit;
}

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

    // Save/Update Monthly Setting
    if ($action === 'save_setting') {
        $bulan = $_POST['bulan']; // YYYY-MM
        $nominal = str_replace('.', '', $_POST['nominal']);
        
        // Check if table exists first
        $db->exec("CREATE TABLE IF NOT EXISTS simpanan_sukarela_pengaturan (
            bulan VARCHAR(7) NOT NULL PRIMARY KEY,
            nominal DECIMAL(15,2) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )");
        
        $stmt = $db->prepare("INSERT INTO simpanan_sukarela_pengaturan (bulan, nominal) VALUES (?, ?) ON DUPLICATE KEY UPDATE nominal = ?");
        $stmt->execute([$bulan, $nominal, $nominal]);
        
        setFlash('success', 'Pengaturan simpanan sukarela bulan ' . formatBulan($bulan) . ' berhasil disimpan.');
        header('Location: simpanan_sukarela.php?bulan=' . $bulan);
        exit;
    }

    // Add/Update Payment (from member row) - with custom nominal
    if ($action === 'add_payment') {
        $anggota_id = $_POST['anggota_id'];
        $bulan = $_POST['bulan']; // YYYY-MM
        $tanggal = $_POST['tanggal'] ?? $bulan . '-01';
        $nominal = (float)str_replace('.', '', $_POST['nominal'] ?? 0);
        $keterangan = sanitize($_POST['keterangan'] ?? 'Simpanan sukarela bulan ' . formatBulan($bulan));
        
        if ($nominal <= 0) {
            setFlash('danger', 'Nominal harus lebih dari 0.');
            header('Location: simpanan_sukarela.php?bulan=' . $bulan);
            exit;
        }

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

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

    // Delete single payment
    if ($action === 'delete') {
        $bulan = $_POST['bulan'];
        $stmt = $db->prepare("DELETE FROM simpanan WHERE id = ? AND jenis = 'sukarela'");
        $stmt->execute([$_POST['id']]);
        setFlash('success', 'Data pembayaran berhasil dihapus.');
        header('Location: simpanan_sukarela.php?bulan=' . $bulan);
        exit;
    }


}

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

// Ensure table exists
try {
    $db->exec("CREATE TABLE IF NOT EXISTS simpanan_sukarela_pengaturan (
        bulan VARCHAR(7) NOT NULL PRIMARY KEY,
        nominal DECIMAL(15,2) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )");
} catch (Exception $e) {
    // Table might already exist
}

// Get nominal for selected bulan
$stmt = $db->prepare("SELECT nominal FROM simpanan_sukarela_pengaturan WHERE bulan = ?");
$stmt->execute([$selectedBulan]);
$currentNominal = $stmt->fetchColumn();

if (!$currentNominal) {
    // Try to get the latest setting if not set for this month
    try {
        $stmt = $db->prepare("SELECT nominal FROM simpanan_sukarela_pengaturan ORDER BY bulan DESC LIMIT 1");
        $stmt->execute();
        $currentNominal = $stmt->fetchColumn() ?: 100000;
    } catch (Exception $e) {
        $currentNominal = 100000;
    }
}

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

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

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

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

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

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

<script>
// ═══════════════════════════════════════════════════════════════════════════════
// ALL FUNCTIONS MUST BE DEFINED BEFORE HTML USES THEM (inline onclick handlers)
// ═══════════════════════════════════════════════════════════════════════════════

// State
let selectedMember = null;
let searchTimeout = null;
let listenersSetup = false;

// Helper: Format number
function formatNumberToDisplay(num) {
    if (!num) return '';
    return new Intl.NumberFormat('id-ID').format(num);
}

// Format currency
function formatCurrencyInput(input) {
    let value = input.value.replace(/[^\d]/g, '');
    if (value) {
        value = new Intl.NumberFormat('id-ID').format(value);
    }
    input.value = value;
}

// Open Add Payment Modal
function openAddPaymentModal(memberData) {
    console.log('🔵 openAddPaymentModal called with:', memberData);
    try {
        if (!memberData || !memberData.id) {
            console.error('❌ Invalid member data:', memberData);
            alert('Error: Data anggota tidak valid');
            return false;
        }
        
        const nameEl = document.getElementById('payment_member_name');
        const idEl = document.getElementById('payment_member_id');
        const anggotaIdEl = document.getElementById('payment_anggota_id');
        
        if (nameEl) nameEl.textContent = memberData.nama || '-';
        if (idEl) idEl.textContent = memberData.no_anggota || '-';
        if (anggotaIdEl) anggotaIdEl.value = memberData.id;
        
        const isEditing = memberData.nominal && memberData.nominal > 0;
        const titleEl = document.getElementById('modalTitle');
        if (titleEl) {
            titleEl.textContent = isEditing ? 'Ubah Simpanan Sukarela' : 'Catat Simpanan Sukarela';
        }
        
        const nominalInput = document.querySelector('#addPaymentModal input[name="nominal"]');
        if (nominalInput) {
            const defaultNominal = '<?=formatRupiah($currentNominal, false)?>' || '0';
            const nominalValue = memberData.nominal ? formatNumberToDisplay(memberData.nominal) : defaultNominal;
            nominalInput.value = nominalValue;
            console.log('✅ Nominal set to:', nominalValue);
        }
        
        const tanggalInput = document.querySelector('#addPaymentModal input[name="tanggal"]');
        if (tanggalInput) {
            const urlParams = new URLSearchParams(window.location.search);
            const selectedMonth = urlParams.get('bulan') || new Date().toISOString().slice(0, 7);
            tanggalInput.value = selectedMonth + '-01';
            console.log('✅ Tanggal set to:', tanggalInput.value);
        }
        
        const keteranganInput = document.querySelector('#addPaymentModal textarea[name="keterangan"]');
        if (keteranganInput) {
            keteranganInput.value = '';
        }
        
        console.log('📂 Opening modal...');
        openModal('addPaymentModal');
        console.log('✅ Modal opened');
        
        setTimeout(() => {
            if (nominalInput) {
                nominalInput.focus();
                console.log('✅ Focus set to nominal input');
            }
        }, 150);
        
        return false;
    } catch (error) {
        console.error('❌ Error opening payment modal:', error);
        alert('Error: ' + error.message);
        return false;
    }
}

// Validate payment form
function validatePaymentForm() {
    const nominal = document.querySelector('#addPaymentModal input[name="nominal"]').value;
    const nominalNum = parseFloat(nominal.replace(/[^\d]/g, ''));
    
    if (!nominal || nominalNum <= 0) {
        alert('Nominal harus lebih dari 0.');
        return false;
    }
    
    if (!document.querySelector('#addPaymentModal input[name="tanggal"]').value) {
        alert('Tanggal harus diisi.');
        return false;
    }
    
    return true;
}

// Open bulk payment modal
function openBulkPaymentModal() {
    console.log('🔵 openBulkPaymentModal CALLED');

    // Reset
    const searchInput = document.getElementById('bulk_anggota_search');
    const suggestionsDiv = document.getElementById('bulk_suggestions');
    const hiddenInput = document.getElementById('bulk_anggota_id');

    if (searchInput) {
        searchInput.value = '';
        console.log('✓ searchInput cleared');
    }
    if (suggestionsDiv) {
        suggestionsDiv.innerHTML = '';
        suggestionsDiv.style.display = 'none';
        console.log('✓ suggestionsDiv hidden');
    }
    if (hiddenInput) {
        hiddenInput.value = '';
    }

    selectedMember = null;
    const proceedBtn = document.getElementById('btn_proceed_payment');
    if (proceedBtn) proceedBtn.style.display = 'none';

    // Open modal
    openModal('bulkPaymentModal');
    console.log('✓ Modal opened');

    // Load all anggota data and show suggestions
    loadAnggotaData().then(() => {
        console.log('✓ Anggota data loaded, showing suggestions');
        // Wait a bit for modal animation to complete
        setTimeout(() => {
            showBulkSuggestions();
            if (searchInput) {
                searchInput.focus();
                console.log('✓ Input focused and suggestions shown');
            }
        }, 200);
    }).catch(e => {
        console.error('❌ Error loading anggota:', e);
    });

    return false;
}

// Load anggota data from server
let bulkAnggotaData = [];
function loadAnggotaData() {
    return fetch('?ajax_search_members=1&q=')
        .then(r => r.json())
        .then(data => {
            if (data && Array.isArray(data)) {
                bulkAnggotaData = data.map(m => ({
                    id: m.id,
                    no: m.no_anggota,
                    nama: m.nama
                }));
                console.log('✓ Loaded ' + bulkAnggotaData.length + ' members');
            }
        })
        .catch(e => console.error('❌ Error loading anggota:', e));
}

// Show all suggestions
function showBulkSuggestions() {
    renderBulkSuggestions(bulkAnggotaData);
}

// Filter anggota based on search query
function filterBulkAnggota() {
    const input = document.getElementById('bulk_anggota_search');
    const query = input.value.toLowerCase().trim();
    
    if (query.length === 0) {
        showBulkSuggestions();
        return;
    }

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

    renderBulkSuggestions(filtered);
}

// Render suggestions
function renderBulkSuggestions(list) {
    const sugBox = document.getElementById('bulk_suggestions');
    const hiddenInput = document.getElementById('bulk_anggota_id');
    const proceedBtn = document.getElementById('btn_proceed_payment');

    // Clear selected member when showing suggestions
    if (hiddenInput) hiddenInput.value = '';
    if (proceedBtn) proceedBtn.style.display = 'none';

    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','#06b6d4','#f97316'];
    let html = '';
    list.forEach(a => {
        const bg = colors[a.id % colors.length];
        const initials = a.nama.substring(0,2).toUpperCase();
        const nameEsc = a.nama.replace(/'/g, "\\'");
        const noEsc = a.no.replace(/'/g, "\\'");
        html += `<div class="sug-item" onclick="selectBulkAnggota(${a.id}, '${noEsc}', '${nameEsc}')">
            <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';
}

// Select anggota from suggestions
function selectBulkAnggota(id, no, nama) {
    document.getElementById('bulk_anggota_id').value = id;
    document.getElementById('bulk_anggota_search').value = no + ' - ' + nama;
    document.getElementById('bulk_suggestions').style.display = 'none';
    
    // Store selected member data
    selectedMember = {
        id: id,
        nama: nama,
        no_anggota: no
    };
    
    // Show proceed button
    document.getElementById('btn_proceed_payment').style.display = 'inline-block';
    
    console.log('✓ Selected member:', nama);
}

// Close suggestions when clicking outside
document.addEventListener('click', function(e) {
    const input = document.getElementById('bulk_anggota_search');
    const sugBox = document.getElementById('bulk_suggestions');
    if (input && sugBox && !input.contains(e.target) && !sugBox.contains(e.target)) {
        sugBox.style.display = 'none';
    }
});

// Proceed with selected member
function proceedWithSelectedMember() {
    if (!selectedMember) {
        alert('Silakan pilih anggota terlebih dahulu');
        return;
    }

    closeModal('bulkPaymentModal');
    setTimeout(() => {
        openAddPaymentModal(selectedMember);
    }, 100);
}
</script>

<div class="page-container">

<!-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ MAIN CONTENT ━━━━━━ -->
<div style="width: 100%;">
    <!-- Statistics Cards -->
    <div class="stats-grid" style="grid-template-columns: repeat(3, 1fr); margin-bottom: 20px;">
        <div class="stat-card primary">
            <div class="stat-info">
                <h3>Total Anggota</h3>
                <div class="stat-value"><?=number_format($totalMembers)?></div>
            </div>
            <div class="stat-icon primary"><i class="fas fa-users"></i></div>
        </div>
        <div class="stat-card success">
            <div class="stat-info">
                <h3>Sudah Bayar</h3>
                <div class="stat-value"><?=number_format($totalPaid)?></div>
                <div style="font-size: 0.8rem; color: var(--gray-500); margin-top: 4px;"><?=$percent?>%</div>
            </div>
            <div class="stat-icon success"><i class="fas fa-check-circle"></i></div>
        </div>
        <div class="stat-card info">
            <div class="stat-info">
                <h3>Total Terkumpul</h3>
                <div class="stat-value" style="font-size: 1.1rem;"><?=formatRupiah($totalAmountMonth)?></div>
                <div style="font-size: 0.75rem; color: var(--gray-600);">Bulan ini</div>
            </div>
            <div class="stat-icon info"><i class="fas fa-hand-holding-heart"></i></div>
        </div>
    </div>

    <!-- Month Selector -->
    <div class="card mb-3">
        <div class="card-body">
            <div class="toolbar">
                <div class="form-group" style="margin-bottom: 0; display: flex; align-items: center; gap: 10px;">
                    <label style="font-size: 0.85rem; font-weight: 600; color: var(--gray-700); white-space: nowrap;">
                        <i class="fas fa-calendar-alt"></i> Pilih Bulan:
                    </label>
                    <input type="month" name="bulan_display" value="<?=$selectedBulan?>" class="form-control"
                           onchange="window.location.href = '?bulan=' + this.value"
                           style="width: 200px; font-size: 0.95rem; padding: 8px 12px; border-radius: 6px;">
                </div>
                <div style="display: flex; gap: 10px;">
                    <a href="../imports/import_simpanan_excel.php?return=sukarela" class="btn btn-success">
                        <i class="fas fa-file-import"></i> Import Excel
                    </a>
                    <a href="simpanan_sukarela_rekap_umum.php" class="btn btn-outline-info">
                        <i class="fas fa-file-invoice"></i> Rekap Sukarela
                    </a>
                    <button class="btn btn-primary" onclick="openBulkPaymentModal()">
                        <i class="fas fa-plus"></i> Tambah Simpanan Sukarela
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Member Payment Status Table -->
    <div class="card">
        <div class="card-header">
            <div class="toolbar">
                <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='?bulan=<?=$selectedBulan?>&search='+encodeURIComponent(this.value);">
                </div>
            </div>
        </div>

        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th style="width: 50px; text-align: center;">No</th>
                        <th>Anggota</th>
                        <th style="width: 120px; text-align: center;">Status</th>
                        <th style="width: 140px; text-align: right;">Nominal</th>
                        <th style="width: 100px; text-align: center;">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($members)): ?>
                        <tr><td colspan="5" class="text-center text-muted" style="padding: 40px;">
                            <i class="fas fa-users" style="font-size: 2.5rem; display: block; margin-bottom: 10px; color: var(--gray-300);"></i>
                            Tidak ada data anggota
                        </td></tr>
                    <?php else: ?>
                        <?php $nomor = 1; foreach ($members as $m): ?>
                        <tr style="border-bottom: 1px solid var(--gray-200);">
                            <td style="text-align: center; font-weight: bold; color: var(--gray-600);"><?=$nomor++?></td>
                            <td>
                                <div style="display: flex; align-items: center; gap: 10px;">
                                    <div class="avatar avatar-<?=($m['anggota_id']%6)+1?>" style="width: 36px; height: 36px; font-size: 0.75rem;">
                                        <?=strtoupper(substr($m['nama'], 0, 2))?>
                                    </div>
                                    <div>
                                        <div class="member-name" style="font-weight: 600; color: var(--gray-800);"><?=htmlspecialchars($m['nama'])?></div>
                                        <div class="member-id" style="font-size: 0.85rem; color: var(--gray-500);"><?=htmlspecialchars($m['no_anggota'])?></div>
                                    </div>
                                </div>
                            </td>
                            <td style="text-align: center;">
                                <?php if ($m['is_paid']): ?>
                                    <span class="badge badge-success" style="font-size: 0.85rem;">
                                        <i class="fas fa-check"></i> Bayar
                                    </span>
                                <?php else: ?>
                                    <span class="badge badge-light" style="font-size: 0.85rem; color: var(--gray-600);">
                                        <i class="fas fa-clock"></i> Belum
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td style="text-align: right; color: var(--gray-700); font-weight: 600;">
                                <?php if ($m['is_paid']): ?>
                                    <?=formatRupiah($m['jumlah'])?>
                                <?php else: ?>
                                    <span style="color: var(--gray-400);">-</span>
                                <?php endif; ?>
                            </td>
                            <td style="text-align: center;">
                                <div class="action-buttons" style="display: flex; gap: 4px; justify-content: center; align-items: center;">
                                    <!-- Button Tambah/Edit Setoran (untuk semua anggota) -->
                                    <button type="button" class="btn btn-icon btn-outline" title="<?=$m['is_paid'] ? 'Ubah Setoran' : 'Catat Setoran'?>" onclick="openAddPaymentModal(<?=htmlspecialchars(json_encode(['id' => (int)$m['anggota_id'], 'nama' => $m['nama'], 'no_anggota' => $m['no_anggota'], 'nominal' => (int)($m['jumlah'] ?? 0)]), ENT_QUOTES, 'UTF-8')?>)" style="color: var(--success-500);">
                                        <?php if ($m['is_paid']): ?>
                                            <i class="fas fa-pen-to-square"></i>
                                        <?php else: ?>
                                            <i class="fas fa-plus"></i>
                                        <?php endif; ?>
                                    </button>
                                    
                                    <!-- Button Hapus (hanya untuk yang sudah setor) -->
                                    <?php if ($m['is_paid']): ?>
                                        <form method="POST" style="display: inline;" onsubmit="return confirm('Hapus pembayaran ini?');">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?=$m['simpanan_id']?>">
                                            <input type="hidden" name="bulan" value="<?=$selectedBulan?>">
                                            <button type="submit" class="btn btn-icon btn-outline" title="Hapus" style="color: var(--danger-500);">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                    
                                    <!-- Button Rekap Per Anggota -->
                                    <a href="simpanan_sukarela_rekap.php?id=<?=$m['anggota_id']?>" class="btn btn-icon btn-outline" title="Rekap Simpanan" style="color: var(--warning-500);">
                                        <i class="fas fa-file-invoice-dollar"></i>
                                    </a>
                                    
                                    <!-- Button Lihat Detail -->
                                    <button class="btn btn-icon btn-outline" title="Lihat Detail" onclick="showDetail(<?=$m['anggota_id']?>)" style="color: var(--info-500);">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </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="3" style="padding: 16px; text-align: right; color: var(--gray-700);">
                            <strong>TOTAL BULAN INI (<?=date('F Y', strtotime($selectedBulan.'-01'))?>)</strong>
                        </td>
                        <td style="padding: 16px; text-align: right; background: var(--success-50); color: var(--success-700); font-weight: 800; border-radius: 0;">
                            <?=formatRupiah($totalAmountMonth)?>
                        </td>
                        <td style="padding: 16px;"></td>
                    </tr>
                    <tr style="border-top: 1px solid var(--gray-200); font-weight: 700;">
                        <td colspan="3" style="padding: 16px; text-align: right; color: var(--gray-700);">
                            <strong>TOTAL KESELURUHAN (Semua Bulan)</strong>
                        </td>
                        <td style="padding: 16px; text-align: right; background: var(--primary-50); color: var(--primary-700); font-weight: 800; border-radius: 0;">
                            <?=formatRupiah($totalAmountGrand)?>
                        </td>
                        <td style="padding: 16px;"></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>

</div>



<!-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ MODAL: Add Payment ━━━━━━ -->
<div class="modal" id="addPaymentModal">
    <div class="modal-header">
        <h3><i class="fas fa-plus-circle" style="color: var(--success-500); margin-right: 8px;"></i><span id="modalTitle">Catat Simpanan Sukarela</span></h3>
        <button class="modal-close" onclick="closeModal('addPaymentModal')"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST" id="formPayment" onsubmit="return validatePaymentForm()">
        <input type="hidden" name="action" value="add_payment">
        <input type="hidden" name="anggota_id" id="payment_anggota_id">
        <input type="hidden" name="bulan" value="<?=$selectedBulan?>">
        <div class="modal-body">
            <!-- Member Info -->
            <div style="padding: 12px; background: var(--primary-50); border-left: 4px solid var(--primary-500); border-radius: 4px; margin-bottom: 20px;">
                <div style="font-weight: 600; color: var(--primary-700);" id="payment_member_name">-</div>
                <div style="font-size: 0.85rem; color: var(--primary-600);" id="payment_member_id">-</div>
            </div>

            <!-- Tanggal -->
            <div class="form-group" style="margin-bottom: 16px;">
                <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--gray-700);">Tanggal <span class="required">*</span></label>
                <input type="date" name="tanggal" class="form-control" required value="<?=$selectedBulan?>-01"
                       style="font-size: 1rem; padding: 10px 12px; border-radius: 6px;">
            </div>

            <!-- Nominal -->
            <div class="form-group" style="margin-bottom: 20px;">
                <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--gray-700);">Nominal (Rp) <span class="required">*</span></label>
                <input type="text" name="nominal" class="form-control" required placeholder="0" value="<?=formatRupiah($currentNominal, false)?>" 
                       oninput="formatCurrencyInput(this)"
                       style="font-size: 1.1rem; padding: 12px; font-weight: 600; border-radius: 6px;">
            </div>

            <!-- Keterangan -->
            <div class="form-group" style="margin-bottom: 16px;">
                <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--gray-700);">Keterangan</label>
                <textarea name="keterangan" class="form-control" rows="2" placeholder="Catatan tambahan (opsional)"
                          style="font-size: 0.95rem; padding: 10px 12px; border-radius: 6px;"></textarea>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('addPaymentModal')">Batal</button>
            <button type="submit" class="btn btn-success"><i class="fas fa-save"></i> Simpan</button>
        </div>
    </form>
</div>

<!-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ MODAL: Member Detail ━━━━━━ -->
<div class="modal" id="detailModal">
    <div class="modal-header">
        <h3 id="detailTitle">Detail Simpanan Sukarela</h3>
        <button class="modal-close" onclick="closeModal('detailModal')"><i class="fas fa-times"></i></button>
    </div>
    <div class="modal-body">
        <div id="detailContent" style="min-height: 200px;">
            <div style="text-align: center; padding: 40px 20px;">
                <i class="fas fa-spinner fa-spin" style="font-size: 2rem; color: var(--primary-500);"></i>
                <p style="margin-top: 12px; color: var(--gray-600);">Memuat data...</p>
            </div>
        </div>
    </div>
</div>

<!-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ MODAL: Bulk Payment (Select Member) ━━━━━━ -->
<div class="modal" id="bulkPaymentModal">
    <div class="modal-header">
        <h3><i class="fas fa-plus-circle" style="color: var(--success-500); margin-right: 8px;"></i>Tambah Simpanan Sukarela</h3>
        <button class="modal-close" onclick="closeModal('bulkPaymentModal')"><i class="fas fa-times"></i></button>
    </div>
    <div class="modal-body" style="position: relative;">
        <!-- Member Selection Section -->
        <div class="form-group" style="position:relative; margin-bottom: 20px;">
            <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--gray-700);">
                Anggota <span class="required">*</span>
            </label>
            <input type="hidden" name="anggota_id" id="bulk_anggota_id">
            <input type="text" id="bulk_anggota_search" class="form-control" placeholder="Ketik nama anggota..." autocomplete="off" required
                   onfocus="showBulkSuggestions()" oninput="filterBulkAnggota()">
            <div id="bulk_suggestions" class="autocomplete-suggestions" style="display:none;"></div>
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-outline" onclick="closeModal('bulkPaymentModal')">Batal</button>
        <button type="button" id="btn_proceed_payment" class="btn btn-success" style="display: none;" onclick="proceedWithSelectedMember()">
            <i class="fas fa-arrow-right"></i> Lanjut
        </button>
    </div>
</div>

<!-- Modal Overlay provided by footer.php -->

<script>
function showDetail(anggotaId) {
    const loader = '<div style="text-align: center; padding: 40px 20px;"><i class="fas fa-spinner fa-spin" style="font-size: 2rem; color: var(--primary-500);"></i><p style="margin-top: 12px;">Memuat data...</p></div>';
    document.getElementById('detailContent').innerHTML = loader;
    openModal('detailModal');

    fetch('?ajax_detail=' + anggotaId)
        .then(r => r.json())
        .then(data => {
            let html = `
                <div style="margin-bottom: 20px; padding: 16px; background: var(--gray-50); border-radius: 6px;">
                    <div style="margin-bottom: 6px;"><strong style="color: var(--gray-700);">${data.nama}</strong></div>
                    <div style="font-size: 0.9rem; color: var(--gray-600);">${data.no_anggota}</div>
                </div>
                <div style="margin-bottom: 20px;">
                    <table class="data-table" style="margin: 0;">
                        <thead>
                            <tr>
                                <th>Tanggal</th>
                                <th>Bulan</th>
                                <th style="text-align: right;">Jumlah</th>
                            </tr>
                        </thead>
                        <tbody>
            `;
            
            if (data.rows.length === 0) {
                html += '<tr><td colspan="3" style="text-align: center; padding: 20px; color: var(--gray-500);">Belum ada riwayat simpanan</td></tr>';
            } else {
                data.rows.forEach(row => {
                    const date = new Date(row.tanggal + 'T00:00:00').toLocaleDateString('id-ID');
                    const bulanArray = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des'];
                    const [year, month] = row.bulan.split('-');
                    const bulanStr = bulanArray[parseInt(month)-1] + ' ' + year;
                    html += `
                        <tr>
                            <td>${date}</td>
                            <td>${bulanStr}</td>
                            <td style="text-align: right; font-weight: 600;">${new Intl.NumberFormat('id-ID', {style: 'currency', currency: 'IDR'}).format(row.jumlah)}</td>
                        </tr>
                    `;
                });
            }
            
            html += `
                        </tbody>
                    </table>
                </div>
                <div style="padding: 12px; background: var(--primary-50); border-left: 4px solid var(--primary-500); border-radius: 4px;">
                    <div style="font-size: 0.9rem;">
                        <strong>Total:</strong> ${new Intl.NumberFormat('id-ID', {style: 'currency', currency: 'IDR'}).format(data.total)}
                    </div>
                </div>
            `;
            
            document.getElementById('detailTitle').innerHTML = `Detail - ${data.nama}`;
            document.getElementById('detailContent').innerHTML = html;
        })
        .catch(err => {
            document.getElementById('detailContent').innerHTML = '<p style="padding: 20px; text-align: center; color: var(--danger-500);">Gagal memuat detail anggota</p>';
            console.error(err);
        });
}
</script>

<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: 10000;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
.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: 32px; height: 32px; min-width: 32px;
    border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    font-size: 0.7rem; font-weight: 700; color: white;
}
.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>

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