<?php
/**
 * Rekap Simpanan Sukarela per Anggota
 * Koperasi Management System
 */

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

$id = $_GET['id'] ?? 0;
$stmt = $db->prepare("SELECT * FROM anggota WHERE id = ?");
$stmt->execute([$id]);
$anggota = $stmt->fetch();

if (!$anggota) {
    die("Anggota tidak ditemukan.");
}

// ── Handle POST: Hapus transaksi ─────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_transaksi') {
    $del_id = intval($_POST['transaksi_id'] ?? 0);
    if ($del_id > 0) {
        $del = $db->prepare("DELETE FROM simpanan WHERE id = ? AND anggota_id = ? AND jenis = 'sukarela'");
        $del->execute([$del_id, $id]);
    }
    header("Location: simpanan_sukarela_rekap.php?id={$id}&deleted=1");
    exit;
}

$pageTitle = 'Rekap Simpanan Sukarela';
$pageSubtitle = 'Riwayat simpanan sukarela: ' . htmlspecialchars($anggota['nama']);

// Get all sukarela savings for this member
$stmt = $db->prepare("
    SELECT * FROM simpanan 
    WHERE anggota_id = ? AND jenis = 'sukarela' 
    ORDER BY tanggal DESC
");
$stmt->execute([$id]);
$history = $stmt->fetchAll();

// Total
$total = 0;
foreach ($history as $h) {
    $total += ($h['tipe'] === 'setoran' ? $h['jumlah'] : -$h['jumlah']);
}

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

<div class="mb-4" style="display: flex; gap: 10px; flex-wrap: wrap;">
    <a href="simpanan_sukarela.php" class="btn btn-outline">
        <i class="fas fa-arrow-left"></i> Kembali ke Daftar
    </a>
    <a href="simpanan_sukarela_rekap_export.php?id=<?= $id ?>" class="btn btn-primary" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none;">
        <i class="fas fa-file-export"></i> Export (PDF/Word/Excel)
    </a>
</div>

<?php if (isset($_GET['deleted'])): ?>
<div class="alert alert-success" style="padding: 12px 18px; background: #d1fae5; border: 1px solid #6ee7b7; border-radius: 8px; color: #065f46; margin-bottom: 16px; display: flex; align-items: center; gap: 10px;">
    <i class="fas fa-check-circle"></i> Transaksi berhasil dihapus.
</div>
<?php endif; ?>

<div class="row">
    <div class="col-md-4">
        <div class="card">
            <div class="card-body text-center">
                <div class="member-avatar avatar-<?= ($anggota['id'] % 6) + 1 ?> mx-auto mb-3" style="width: 80px; height: 80px; font-size: 2rem;">
                    <?= strtoupper(substr($anggota['nama'], 0, 2)) ?>
                </div>
                <h2><?= htmlspecialchars($anggota['nama']) ?></h2>
                <p class="text-muted"><?= htmlspecialchars($anggota['no_anggota']) ?></p>
                <div class="mt-4 p-3 bg-light rounded">
                    <div class="text-sm text-muted">Total Simpanan Sukarela</div>
                    <div class="h2 fw-bold text-success mt-1"><?= formatRupiah($total) ?></div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h3><i class="fas fa-history"></i> Riwayat Pembayaran</h3>
            </div>
            <div class="table-responsive">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Tanggal</th>
                            <th>Bulan (Keterangan)</th>
                            <th>Jumlah</th>
                            <th>Petugas</th>
                            <th style="text-align: center;">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($history)): ?>
                            <tr><td colspan="5" class="text-center text-muted" style="padding: 30px;">Belum ada riwayat pembayaran</td></tr>
                        <?php else: ?>
                            <?php foreach ($history as $h): ?>
                            <tr>
                                <td><?= formatTanggal($h['tanggal']) ?></td>
                                <td><?= $h['keterangan'] ?: htmlspecialchars($h['tipe']) ?></td>
                                <td style="text-align: right; font-weight: bold;">
                                    <span style="color: <?= $h['tipe'] === 'setoran' ? 'green' : 'red' ?>;">
                                        <?= ($h['tipe'] === 'setoran' ? '+' : '-') . formatRupiah($h['jumlah']) ?>
                                    </span>
                                </td>
                                <td><?php
                                    if ($h['created_by']) {
                                        $uStmt = $db->prepare("SELECT nama_lengkap FROM users WHERE id = ?");
                                        $uStmt->execute([$h['created_by']]);
                                        echo htmlspecialchars($uStmt->fetchColumn() ?: 'Unknown');
                                    } else {
                                        echo '-';
                                    }
                                ?></td>
                                <?php $confirmMsg = "Hapus transaksi " . ($h['tipe'] === 'penarikan' ? 'penarikan' : 'setoran') . " sebesar " . formatRupiah($h['jumlah']) . " ini?"; ?>
                                <td style="text-align: center;">
                                    <form method="POST" style="display: inline;"
                                          onsubmit="return confirm('<?= htmlspecialchars($confirmMsg, ENT_QUOTES) ?>');">
                                        <input type="hidden" name="action" value="delete_transaksi">
                                        <input type="hidden" name="transaksi_id" value="<?= $h['id'] ?>">
                                        <button type="submit" class="btn btn-icon btn-outline" title="Hapus Transaksi" style="color: var(--danger-500, #ef4444);">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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