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

$pageTitle = 'Simpanan Pokok';
$pageSubtitle = 'Kelola simpanan pokok anggota (sekali bayar)';

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

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

    // Save Global Setting
    if ($action === 'save_setting') {
        $nominal = str_replace('.', '', $_POST['nominal']);
        $db->prepare("UPDATE pengaturan SET nilai=? WHERE kunci='simpanan_pokok'")->execute([$nominal]);
        setFlash('success', 'Nominal simpanan pokok global diperbarui.');
        header('Location: simpanan_pokok.php');
        exit;
    }

    // Add/Update Payment
    if ($action === 'add_payment') {
        $anggota_id = $_POST['anggota_id'];
        $tanggal = $_POST['tanggal'] ?: date('Y-m-d');
        $nominal = str_replace('.', '', $_POST['nominal']);
        $keterangan = sanitize($_POST['keterangan'] ?? 'Simpanan pokok anggota');
        
        // Check if already paid
        $chk = $db->prepare("SELECT id FROM simpanan WHERE anggota_id = ? AND jenis = 'pokok'");
        $chk->execute([$anggota_id]);
        $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 pokok berhasil diperbarui.');
        } else {
            $stmt = $db->prepare("INSERT INTO simpanan (anggota_id, jenis, tipe, jumlah, tanggal, keterangan, created_by) VALUES (?, 'pokok', 'setoran', ?, ?, ?, ?)");
            $stmt->execute([$anggota_id, $nominal, $tanggal, $keterangan, $_SESSION['user_id']]);
            setFlash('success', 'Simpanan pokok berhasil dicatat.');
        }
        
        header('Location: simpanan_pokok.php');
        exit;
    }

    if ($action === 'bulk_payment') {
        $nominal = str_replace('.', '', $_POST['nominal']);
        $tanggal = $_POST['tanggal'] ?: date('Y-m-d');
        $keterangan = sanitize($_POST['keterangan'] ?: 'Simpanan pokok (bayar masal)');
        $update_existing = isset($_POST['update_existing']);

        $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 (?, 'pokok', 'setoran', ?, ?, ?, ?)");
        $updateStmt = $db->prepare("UPDATE simpanan SET jumlah = ?, keterangan = ? WHERE anggota_id = ? AND jenis = 'pokok'");
        
        $inserted = 0;
        $updated = 0;
        $skipped = 0;

        foreach ($allAnggota as $aid) {
            // Check if already paid
            $chk = $db->prepare("SELECT id, jumlah FROM simpanan WHERE anggota_id=? AND jenis='pokok'");
            $chk->execute([$aid]);
            $existing = $chk->fetch();

            if ($existing) {
                if ($update_existing && (float)$existing['jumlah'] != (float)$nominal) {
                    $updateStmt->execute([$nominal, $keterangan . ' (Update Nominal)', $aid]);
                    $updated++;
                } else {
                    $skipped++;
                }
                continue;
            }

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

        $msg = "Berhasil memproses: $inserted baru dicatat";
        if ($updated) $msg .= ", $updated data diperbarui";
        if ($skipped) $msg .= ", $skipped data dilewati";
        
        setFlash('success', $msg);
        header('Location: simpanan_pokok.php');
        exit;
    }

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

// ── Data Retrieval ────────────────────────────────────────────────────────────

$currentGlobal = (float)getSetting('simpanan_pokok', 100000);

// Get all members and join with their 'pokok' payment if exists
$members = $db->query("
    SELECT a.*, s.id as payment_id, s.jumlah, s.tanggal as payment_date, s.keterangan as payment_desc
    FROM anggota a
    LEFT JOIN simpanan s ON s.anggota_id = a.id AND s.jenis = 'pokok'
    WHERE a.status = 'aktif'
    ORDER BY a.nama ASC
")->fetchAll();

// Handle AJAX request for member detail (Pokok history)
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 = 'pokok'
        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();
    
    echo json_encode(['nama' => $info['nama'], 'no_anggota' => $info['no_anggota'], 'rows' => $rows, 'total_setor' => array_sum(array_column($rows, 'jumlah'))]);
    exit;
}

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

<div class="stats-grid" style="grid-template-columns: repeat(3, 1fr);">
    <div class="stat-card primary">
        <div class="stat-info">
            <h3>Saldo Keseluruhan</h3>
            <?php 
                $totalSaldo = array_sum(array_column($members, 'jumlah'));
            ?>
            <div class="stat-value"><?= formatRupiah($totalSaldo) ?></div>
            <span class="text-muted" style="font-size: 0.75rem;">Total dana terkumpul</span>
        </div>
        <div class="stat-icon primary"><i class="fas fa-wallet"></i></div>
    </div>
    
    <div class="stat-card success">
        <div class="stat-info">
            <h3>Total Lunas</h3>
            <?php 
                $lunasCount = 0;
                foreach($members as $m) if($m['payment_id']) $lunasCount++;
            ?>
            <div class="stat-value"><?= $lunasCount ?> <span style="font-size: 0.9rem; font-weight: normal;">Anggota</span></div>
        </div>
        <div class="stat-icon success"><i class="fas fa-check-circle"></i></div>
    </div>

    <div class="stat-card danger">
        <div class="stat-info">
            <h3>Belum Lunas</h3>
            <div class="stat-value"><?= count($members) - $lunasCount ?> <span style="font-size: 0.9rem; font-weight: normal;">Anggota</span></div>
        </div>
        <div class="stat-icon danger"><i class="fas fa-times-circle"></i></div>
    </div>
</div>

<div class="card">
    <div class="card-header" style="justify-content: space-between; display: flex; align-items: center;">
        <h3 style="margin:0;">Daftar Status Simpanan Pokok Anggota</h3>
        <div class="action-buttons" style="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>
            <button class="btn btn-success" onclick="openModal('bulkModal')">
                <i class="fas fa-users"></i> Bayar Masal
            </button>
            <a href="simpanan_pokok_export.php" class="btn btn-primary">
                <i class="fas fa-file-export"></i> Export
            </a>
        </div>
    </div>
    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th style="width: 40px; text-align: center;"><input type="checkbox" onchange="toggleAllCheckboxes(this)"></th>
                    <th style="width: 50px; text-align: center;">Nomor</th>
                    <th>No. Anggota</th>
                    <th>Nama Anggota</th>
                    <th>Status</th>
                    <th>Tanggal Bayar</th>
                    <th>Jumlah</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php $nomor = 1; foreach ($members as $m): ?>
                <tr>
                    <td style="text-align: center;">
                        <?php if ($m['payment_id']): ?>
                            <input type="checkbox" class="rowCheckbox" value="<?= $m['payment_id'] ?>" onchange="updateBulkDeleteBtn()">
                        <?php else: ?>
                            <input type="checkbox" disabled title="Belum lunas">
                        <?php endif; ?>
                    </td>
                    <td style="text-align: center; font-weight: bold;"><?=$nomor++?></td>
                    <td><?= htmlspecialchars($m['no_anggota']) ?></td>
                    <td><?= htmlspecialchars($m['nama']) ?></td>
                    <td>
                        <?php if ($m['payment_id']): ?>
                            <span class="badge badge-success">Lunas</span>
                        <?php else: ?>
                            <span class="badge badge-danger">Belum Lunas</span>
                        <?php endif; ?>
                    </td>
                    <td><?= $m['payment_date'] ? formatTanggal($m['payment_date']) : '-' ?></td>
                    <td>
                        <?php if ($m['payment_id']): ?>
                            <a href="javascript:void(0)" onclick="showDetailPokok(<?=$m['id']?>)"
                               class="<?= (float)$m['jumlah'] == 0 ? 'text-danger fw-bold' : 'text-primary fw-bold' ?>"
                               style="text-decoration:none;" title="Klik untuk lihat rincian">
                                <?= formatRupiah($m['jumlah']) ?>
                            </a>
                        <?php else: ?>
                            <span class="text-muted" style="font-size: 0.85rem;">
                                Tagihan: <strong><?= formatRupiah($currentGlobal) ?></strong>
                            </span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <div class="action-buttons">
                            <?php if (!$m['payment_id']): ?>
                                <button class="btn btn-sm btn-primary" onclick="payMember(<?= $m['id'] ?>, '<?= addslashes($m['nama']) ?>')">
                                    <i class="fas fa-hand-holding-usd"></i> Bayar
                                </button>
                            <?php else: ?>
                                <button class="btn btn-sm btn-outline-warning" onclick="editPayment(<?= $m['payment_id'] ?>, <?= $m['id'] ?>, '<?= addslashes($m['nama']) ?>', '<?= $m['jumlah'] ?>', '<?= $m['payment_date'] ?>', '<?= addslashes($m['payment_desc']) ?>')">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <form method="POST" style="display:inline;" onsubmit="return confirm('Hapus data simpanan pokok ini?');">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= $m['payment_id'] ?>">
                                    <button class="btn btn-sm btn-outline-danger">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr style="background: var(--gray-50); font-weight: 800; border-top: 2px solid var(--gray-200);">
                    <td colspan="6" class="text-right">TOTAL KESELURUHAN</td>
                    <td colspan="2" class="text-left text-primary" style="font-size: 1.05rem;">
                        <?= formatRupiah($totalSaldo) ?>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

<!-- Modal Setting Global -->
<div class="modal" id="settingModal">
    <div class="modal-header">
        <h3>Pengaturan Simpanan Pokok</h3>
        <button class="modal-close" onclick="closeModal('settingModal')">&times;</button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="save_setting">
        <div class="modal-body">
            <div class="form-group">
                <label>Nominal Pokok (Rp)</label>
                <input type="text" name="nominal" class="form-control" value="<?= number_format($currentGlobal,0,'','.') ?>" oninput="formatCurrencyInput(this)" required>
                <small class="text-muted">Ini adalah nominal pendaftaran tetap untuk semua anggota.</small>
            </div>
        </div>
<!-- Modal Bulk Payment -->
<div class="modal" id="bulkModal">
    <div class="modal-header">
        <h3>Bayar Masal Simpanan Pokok</h3>
        <button class="modal-close" onclick="closeModal('bulkModal')">&times;</button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="bulk_payment">
        <div class="modal-body">
            <div style="background:#e0f2fe; border: 1px solid #7dd3fc; padding: 10px; border-radius: 6px; margin-bottom: 15px; font-size: 0.9rem;">
                <i class="fas fa-info-circle" style="color:#0284c7;"></i> Fitur ini akan mencatat pembayaran simpanan pokok untuk <strong>semua anggota yang belum lunas</strong> menggunakan nominal global saat ini.
            </div>
            <div class="form-group">
                <label>Nominal Bayar (Rp)</label>
                <input type="text" name="nominal" class="form-control" value="<?= number_format($currentGlobal,0,'','.') ?>" oninput="formatCurrencyInput(this)" required>
            </div>
            <div class="form-group">
                <label>Tanggal Pembayaran</label>
                <input type="date" name="tanggal" class="form-control" value="<?= date('Y-m-d') ?>" required>
            </div>
            <div class="form-group">
                <label>Keterangan</label>
                <input type="text" name="keterangan" class="form-control" placeholder="Simpanan pokok pendaftaran">
            </div>
            <div class="form-group" style="margin-top: 15px;">
                <label style="display:flex; align-items:center; gap:8px; cursor:pointer;">
                    <input type="checkbox" name="update_existing" value="1" style="width:16px; height:16px;">
                    <span>Update nominal untuk anggota yang <strong>sudah lunas</strong> (jika nominal berbeda)</span>
                </label>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('bulkModal')">Batal</button>
            <button type="submit" class="btn btn-success">Mulai Proses Bayar Masal</button>
        </div>
    </form>
</div>

<!-- Modal Add/Edit Payment -->
<div class="modal" id="paymentModal">
    <div class="modal-header">
        <h3 id="paymentModalTitle">Input Simpanan Pokok</h3>
        <button class="modal-close" onclick="closeModal('paymentModal')">&times;</button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="add_payment">
        <input type="hidden" name="anggota_id" id="modal_anggota_id">
        <div class="modal-body">
            <div class="form-group">
                <label>Nama Anggota</label>
                <input type="text" id="modal_nama_anggota" class="form-control" readonly style="background:#f3f4f6;">
            </div>
            <div class="form-group">
                <label>Nominal (Rp)</label>
                <input type="text" name="nominal" id="modal_nominal" class="form-control" oninput="formatCurrencyInput(this)" required>
            </div>
            <div class="form-group">
                <label>Tanggal Bayar</label>
                <input type="date" name="tanggal" id="modal_tanggal" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Keterangan</label>
                <textarea name="keterangan" id="modal_keterangan" class="form-control" rows="2"></textarea>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('paymentModal')">Batal</button>
            <button type="submit" class="btn btn-primary">Simpan Pembayaran</button>
        </div>
    </form>
</div>

<!-- MODAL: Detail Simpanan Pokok -->
<div class="modal" id="detailPokokModal" style="max-width:600px;">
    <div class="modal-header">
        <h3><i class="fas fa-list" style="color:var(--primary-500);margin-right:8px;"></i>Rincian Simpanan Pokok</h3>
        <button class="modal-close" onclick="closeModal('detailPokokModal')"><i class="fas fa-times"></i></button>
    </div>
    <div class="modal-body">
        <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(--primary-500)20;display:flex;align-items:center;justify-content:center;">
                <i class="fas fa-user-shield" style="color:var(--primary-500);"></i>
            </div>
            <div>
                <div id="detPokNama" style="font-weight:700;color:var(--gray-800);">-</div>
                <div id="detPokNoAnggota" style="font-size:0.78rem;color:var(--gray-500);">-</div>
            </div>
            <div style="margin-left:auto;text-align:right;">
                <div style="font-size:0.7rem;color:var(--gray-400);text-transform:uppercase;">Total Terbayar</div>
                <div id="detPokTotal" style="font-weight:800;color:var(--primary-600);font-size:1.1rem;">-</div>
            </div>
        </div>
        <div id="detailPokokLoading" style="text-align:center;padding:20px;display:none;">
            <i class="fas fa-spinner fa-spin" style="color:var(--gray-400);"></i>
        </div>
        <div id="detailPokokContent">
            <table class="data-table" style="margin:0;">
                <thead>
                    <tr>
                        <th style="width:40px;text-align:center;">No</th>
                        <th>Tanggal</th>
                        <th class="text-right">Jumlah</th>
                        <th>Keterangan</th>
                    </tr>
                </thead>
                <tbody id="detailPokokBody"></tbody>
            </table>
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-primary" onclick="closeModal('detailPokokModal')">Tutup</button>
    </div>
</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 + ' data simpanan pokok 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;
}

function payMember(id, nama) {
    document.getElementById('paymentModalTitle').innerText = 'Input Simpanan Pokok';
    document.getElementById('modal_anggota_id').value = id;
    document.getElementById('modal_nama_anggota').value = nama;
    document.getElementById('modal_nominal').value = '<?= number_format($currentGlobal,0,'','.') ?>';
    document.getElementById('modal_tanggal').value = '<?= date('Y-m-d') ?>';
    document.getElementById('modal_keterangan').value = 'Simpanan pokok anggota';
    openModal('paymentModal');
}

function editPayment(pay_id, anggota_id, nama, jumlah, tanggal, ket) {
    document.getElementById('paymentModalTitle').innerText = 'Edit Simpanan Pokok';
    document.getElementById('modal_anggota_id').value = anggota_id;
    document.getElementById('modal_nama_anggota').value = nama;
    document.getElementById('modal_nominal').value = formatRupiahJs(jumlah);
    document.getElementById('modal_tanggal').value = tanggal;
    document.getElementById('modal_keterangan').value = ket;
    openModal('paymentModal');
}

function formatRupiahJs(angka) {
    return new Intl.NumberFormat('id-ID').format(angka);
}

function showDetailPokok(aid) {
    const loading = document.getElementById('detailPokokLoading');
    const body = document.getElementById('detailPokokBody');
    loading.style.display = 'block';
    body.innerHTML = '';
    
    openModal('detailPokokModal');
    
    fetch('simpanan_pokok.php?ajax_detail=' + aid)
        .then(r => r.json())
        .then(data => {
            loading.style.display = 'none';
            document.getElementById('detPokNama').textContent = data.nama;
            document.getElementById('detPokNoAnggota').textContent = data.no_anggota;
            document.getElementById('detPokTotal').textContent = 'Rp ' + formatRupiahJs(data.total_setor);
            
            if (data.rows.length === 0) {
                body.innerHTML = '<tr><td colspan="4" class="text-center text-muted">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'});
                    html += `<tr>
                        <td style="text-align:center;">${i+1}</td>
                        <td>${tgl}</td>
                        <td class="text-right fw-bold text-success">Rp ${formatRupiahJs(row.jumlah)}</td>
                        <td>${row.keterangan || '-'}</td>
                    </tr>`;
                });
                body.innerHTML = html;
            }
        });
}
</script>

<style>
.edit-setting {
    position:absolute; top:10px; right:10px; color:var(--primary-500); cursor:pointer;
    background: white; width:26px; height:26px; display:flex; align-items:center; justify-content:center;
    border-radius:50%; box-shadow:0 1px 3px rgba(0,0,0,0.1);
}
.edit-setting:hover { background: var(--gray-100); }
</style>

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