<?php
/**
 * Rekap Umum Simpanan Wajib (Matrix View)
 * Koperasi Management System
 */

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

$year = $_GET['year'] ?? date('Y');
$pageTitle = 'Rekap Simpanan Wajib';
$pageSubtitle = 'Status pembayaran seluruh anggota tahun ' . $year;

// Get all active members
$members = $db->query("SELECT id, no_anggota, nama FROM anggota WHERE status='aktif' ORDER BY nama ASC")->fetchAll();

// Get summary of payments per month for the selected year
$stmtSummary = $db->prepare("
    SELECT DATE_FORMAT(tanggal, '%m') as bulan, SUM(jumlah) as total_nominal, COUNT(DISTINCT anggota_id) as paid_members
    FROM simpanan 
    WHERE jenis = 'wajib' AND tipe = 'setoran' AND DATE_FORMAT(tanggal, '%Y') = ?
    GROUP BY bulan
");
$stmtSummary->execute([$year]);
$summaryData = $stmtSummary->fetchAll();

$monthlySummary = [];
$totalYearlyAmount = 0;
$totalYearlyPayments = 0;
foreach ($summaryData as $s) {
    $monthlySummary[(int)$s['bulan']] = [
        'nominal' => $s['total_nominal'],
        'members' => $s['paid_members']
    ];
    $totalYearlyAmount += $s['total_nominal'];
    $totalYearlyPayments += $s['paid_members'];
}

$months = [
    1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April', 5 => 'Mei', 6 => 'Juni',
    7 => 'Juli', 8 => 'Agustus', 9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
];

// Get all payments for the selected year for the detail matrix
$stmt = $db->prepare("
    SELECT anggota_id, DATE_FORMAT(tanggal, '%m') as bulan, SUM(jumlah) as amount
    FROM simpanan 
    WHERE jenis = 'wajib' AND tipe = 'setoran' AND DATE_FORMAT(tanggal, '%Y') = ?
    GROUP BY anggota_id, bulan
");
$stmt->execute([$year]);
$paymentsData = $stmt->fetchAll();

// Format payments into a matrix [anggota_id][month] = amount
$matrix = [];
foreach ($paymentsData as $p) {
    $matrix[$p['anggota_id']][(int)$p['bulan']] = $p['amount'];
}

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

<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row align-items-center">
            <div class="col-auto">
                <label class="fw-bold">Pilih Tahun:</label>
            </div>
            <div class="col-auto">
                <select name="year" class="form-control" onchange="this.form.submit()">
                    <?php 
                    $startYear = 2024;
                    $endYear = date('Y') + 1;
                    for($y=$startYear; $y<=$endYear; $y++): ?>
                        <option value="<?= $y ?>" <?= $y == $year ? 'selected' : '' ?>><?= $y ?></option>
                    <?php endfor; ?>
                </select>
            </div>
            <div class="col text-end">
                <button onclick="window.print()" class="btn btn-primary no-print">
                    <i class="fas fa-print"></i> Cetak Laporan
                </button>
                <a href="simpanan_wajib.php" class="btn btn-outline no-print">
                    <i class="fas fa-arrow-left"></i> Kembali
                </a>
            </div>
        </form>
    </div>
</div>

<div class="row mb-5">
    <div class="col-md-4">
        <div class="card h-100 shadow-sm border-0">
            <div class="card-header bg-white border-bottom py-3">
                <h3 class="mb-0"><i class="fas fa-calendar-check text-primary me-2"></i> Ringkasan Tahun <?= $year ?></h3>
            </div>
            <div class="card-body">
                <div class="p-4 bg-light-success rounded-lg text-center mb-3">
                    <div class="text-sm text-secondary text-uppercase mb-2">Total Terkumpul</div>
                    <div class="h2 fw-bold text-success mb-0"><?= formatRupiah($totalYearlyAmount) ?></div>
                </div>
                <div class="p-4 bg-light-primary rounded-lg text-center">
                    <div class="text-sm text-secondary text-uppercase mb-2">Total Transaksi</div>
                    <div class="h2 fw-bold text-primary mb-0"><?= number_format($totalYearlyPayments) ?></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-8">
        <div class="card h-100 shadow-sm border-0">
            <div class="card-header bg-white border-bottom py-3">
                <h3 class="mb-0"><i class="fas fa-chart-bar text-primary me-2"></i> Rekap Pendapatan Per Bulan</h3>
            </div>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th class="ps-4">Bulan</th>
                            <th class="text-center">Setoran</th>
                            <th class="text-end pe-4">Total Nominal</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($months as $idx => $mName): 
                            $mNom = $monthlySummary[$idx]['nominal'] ?? 0;
                            $mMem = $monthlySummary[$idx]['members'] ?? 0;
                        ?>
                        <tr>
                            <td class="ps-4 py-3 fw-medium"><?= $mName ?></td>
                            <td class="text-center"><?= $mMem ?> Anggota</td>
                            <td class="text-end pe-4 fw-bold text-primary"><?= formatRupiah($mNom) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot class="bg-light-primary">
                        <tr class="fw-bold">
                            <td class="ps-4 py-3">TOTAL TAHUNAN</td>
                            <td class="text-center"><?= $totalYearlyPayments ?> Transaksi</td>
                            <td class="text-end pe-4 text-success h5 mb-0"><?= formatRupiah($totalYearlyAmount) ?></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h3><i class="fas fa-table"></i> Matrix Pembayaran Simpanan Wajib <?= $year ?></h3>
    </div>
    <div class="table-responsive">
        <table class="data-table text-center">
            <thead>
                <tr>
                    <th class="text-start">Nama Anggota</th>
                    <?php 
                    $shortMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'];
                    foreach($shortMonths as $m): ?>
                        <th style="width: 60px;"><?= $m ?></th>
                    <?php endforeach; ?>
                    <th class="bg-light">Total</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($members as $mem): ?>
                <tr>
                    <td class="text-start border-end">
                        <div class="fw-bold"><?= htmlspecialchars($mem['nama']) ?></div>
                        <div class="text-xs text-muted"><?= $mem['no_anggota'] ?></div>
                    </td>
                    <?php 
                    $rowTotal = 0;
                    for($i=1; $i<=12; $i++): 
                        $amt = $matrix[$mem['id']][$i] ?? 0;
                        $rowTotal += $amt;
                    ?>
                        <td class="<?= $amt > 0 ? '' : 'bg-light-gray' ?>">
                            <?php if($amt > 0): ?>
                                <div class="text-success fw-medium" style="font-size: 0.8rem;">
                                    <?= number_format($amt, 0, ',', '.') ?>
                                </div>
                            <?php else: ?>
                                <span class="text-muted" style="font-size: 0.7rem;">-</span>
                            <?php endif; ?>
                        </td>
                    <?php endfor; ?>
                    <td class="bg-light fw-bold text-primary border-start">
                        <?= number_format($rowTotal, 0, ',', '.') ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot class="bg-light fw-bold">
                <tr>
                    <td class="text-start border-end">TOTAL BULANAN</td>
                    <?php for($i=1; $i<=12; $i++): 
                        $mTotal = $monthlySummary[$i]['nominal'] ?? 0;
                    ?>
                        <td class="text-primary">
                            <?= $mTotal > 0 ? number_format($mTotal, 0, ',', '.') : '-' ?>
                        </td>
                    <?php endfor; ?>
                    <td class="text-success h6 mb-0 border-start">
                        <?= number_format($totalYearlyAmount, 0, ',', '.') ?>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

<style>
.text-gray-300 { color: #d1d5db; }
.text-xs { font-size: 0.75rem; }
.table-compact { border-collapse: collapse; }
.table-compact th, .table-compact td { padding: 8px 12px; }
.bg-light-success { background-color: #f0fdf4; }
.bg-light-primary { background-color: #f0f9ff; }
.bg-light-gray { background-color: #f8fafc; }
.rounded-lg { border-radius: 0.75rem; }
.fw-medium { font-weight: 500; }
@media print {
    .no-print { display: none !important; }
    .card { border: 1px solid #ddd !important; box-shadow: none !important; }
    body { background: white !important; }
    .container-fluid { padding: 0 !important; }
}
</style>

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