<?php
/**
 * Dashboard
 * Koperasi Management System
 */

$pageTitle = 'Dashboard';
$pageSubtitle = 'Ringkasan data koperasi';

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

// Stats
$totalAnggota = $db->query("SELECT COUNT(*) FROM anggota WHERE status='aktif'")->fetchColumn();
$totalSimpanan = $db->query("SELECT COALESCE(SUM(CASE WHEN s.tipe='setoran' THEN s.jumlah ELSE -s.jumlah END), 0) FROM simpanan s JOIN anggota a ON s.anggota_id = a.id")->fetchColumn();
$totalPinjaman = $db->query("SELECT COALESCE(SUM(p.sisa_pinjaman), 0) FROM pinjaman p JOIN anggota a ON p.anggota_id = a.id WHERE p.status='disetujui'")->fetchColumn();
$pinjamanPending = $db->query("SELECT COUNT(*) FROM pinjaman WHERE status='pending'")->fetchColumn();

// Recent transactions
$recentSimpanan = $db->query("
    SELECT s.*, a.nama, a.no_anggota 
    FROM simpanan s 
    JOIN anggota a ON s.anggota_id = a.id 
    ORDER BY s.created_at DESC LIMIT 5
")->fetchAll();

$recentPinjaman = $db->query("
    SELECT p.*, a.nama, a.no_anggota 
    FROM pinjaman p 
    JOIN anggota a ON p.anggota_id = a.id 
    ORDER BY p.created_at DESC LIMIT 5
")->fetchAll();

// Monthly savings data for chart (last 6 months)
$chartData = $db->query("
    SELECT 
        DATE_FORMAT(tanggal, '%Y-%m') as bulan,
        SUM(CASE WHEN tipe='setoran' THEN jumlah ELSE 0 END) as setoran,
        SUM(CASE WHEN tipe='penarikan' THEN jumlah ELSE 0 END) as penarikan
    FROM simpanan 
    WHERE tanggal >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
    GROUP BY DATE_FORMAT(tanggal, '%Y-%m')
    ORDER BY bulan ASC
")->fetchAll();

$chartLabels = [];
$chartSetoran = [];
$chartPenarikan = [];
$bulanNama = ['01'=>'Jan','02'=>'Feb','03'=>'Mar','04'=>'Apr','05'=>'Mei','06'=>'Jun','07'=>'Jul','08'=>'Ags','09'=>'Sep','10'=>'Okt','11'=>'Nov','12'=>'Des'];

foreach ($chartData as $row) {
    $m = substr($row['bulan'], 5, 2);
    $chartLabels[] = $bulanNama[$m] ?? $m;
    $chartSetoran[] = (float)$row['setoran'];
    $chartPenarikan[] = (float)$row['penarikan'];
}

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

<!-- Stats Cards -->
<div class="stats-grid">
    <div class="stat-card primary">
        <div class="stat-info">
            <h3>Total Anggota</h3>
            <div class="stat-value"><?= number_format($totalAnggota) ?></div>
            <span class="stat-change up"><i class="fas fa-arrow-up"></i> Aktif</span>
        </div>
        <div class="stat-icon primary">
            <i class="fas fa-users"></i>
        </div>
    </div>
    <div class="stat-card success">
        <div class="stat-info">
            <h3>Total Simpanan</h3>
            <div class="stat-value"><?= formatRupiah($totalSimpanan) ?></div>
            <span class="stat-change up"><i class="fas fa-arrow-up"></i> Semua jenis</span>
        </div>
        <div class="stat-icon success">
            <i class="fas fa-piggy-bank"></i>
        </div>
    </div>
    <div class="stat-card warning">
        <div class="stat-info">
            <h3>Pinjaman Berjalan</h3>
            <div class="stat-value"><?= formatRupiah($totalPinjaman) ?></div>
            <span class="stat-change down"><i class="fas fa-clock"></i> Outstanding</span>
        </div>
        <div class="stat-icon warning">
            <i class="fas fa-hand-holding-usd"></i>
        </div>
    </div>
    <div class="stat-card info">
        <div class="stat-info">
            <h3>Pinjaman Pending</h3>
            <div class="stat-value"><?= number_format($pinjamanPending) ?></div>
            <span class="stat-change up"><i class="fas fa-hourglass-half"></i> Menunggu</span>
        </div>
        <div class="stat-icon info">
            <i class="fas fa-clipboard-list"></i>
        </div>
    </div>
</div>

<!-- Charts & Recent Activity -->
<div class="grid-2">
    <!-- Chart -->
    <div class="card">
        <div class="card-header">
            <h2><i class="fas fa-chart-area" style="color: var(--primary-500); margin-right: 8px;"></i>Grafik Simpanan</h2>
        </div>
        <div class="card-body">
            <div class="chart-container">
                <canvas id="savingsChart"></canvas>
            </div>
        </div>
    </div>

    <!-- Recent Savings -->
    <div class="card">
        <div class="card-header">
            <h2><i class="fas fa-history" style="color: var(--success-500); margin-right: 8px;"></i>Transaksi Terbaru</h2>
            <a href="simpanan/simpanan.php" class="btn btn-sm btn-outline">Lihat Semua</a>
        </div>
        <div class="card-body" style="padding: 12px 24px;">
            <?php if (empty($recentSimpanan)): ?>
                <div class="empty-state">
                    <i class="fas fa-inbox"></i>
                    <p>Belum ada transaksi</p>
                </div>
            <?php else: ?>
                <ul class="recent-list">
                    <?php foreach ($recentSimpanan as $s): ?>
                        <li class="recent-item">
                            <div class="recent-icon <?= $s['tipe'] === 'setoran' ? 'stat-icon success' : 'stat-icon danger' ?>">
                                <i class="fas fa-<?= $s['tipe'] === 'setoran' ? 'arrow-down' : 'arrow-up' ?>"></i>
                            </div>
                            <div class="recent-info">
                                <div class="recent-title"><?= htmlspecialchars($s['nama']) ?></div>
                                <div class="recent-desc">
                                    <?= ucfirst($s['jenis']) ?> · <?= formatTanggal($s['tanggal']) ?>
                                </div>
                            </div>
                            <div class="recent-amount <?= $s['tipe'] === 'setoran' ? 'positive' : 'negative' ?>">
                                <?= $s['tipe'] === 'setoran' ? '+' : '-' ?><?= formatRupiah($s['jumlah']) ?>
                            </div>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Recent Loans -->
<div class="card mt-3">
    <div class="card-header">
        <h2><i class="fas fa-file-invoice-dollar" style="color: var(--warning-500); margin-right: 8px;"></i>Pinjaman Terbaru</h2>
        <a href="pinjaman.php" class="btn btn-sm btn-outline">Lihat Semua</a>
    </div>
    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>No. Pinjaman</th>
                    <th>Anggota</th>
                    <th>Jumlah</th>
                    <th>Sisa</th>
                    <th>Status</th>
                    <th>Tanggal</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($recentPinjaman)): ?>
                    <tr><td colspan="6" class="text-center text-muted" style="padding:30px;">Belum ada pinjaman</td></tr>
                <?php else: ?>
                    <?php foreach ($recentPinjaman as $p): ?>
                        <tr>
                            <td><strong><?= htmlspecialchars($p['no_pinjaman']) ?></strong></td>
                            <td><?= htmlspecialchars($p['nama']) ?></td>
                            <td><?= formatRupiah($p['jumlah_pinjaman']) ?></td>
                            <td><?= formatRupiah($p['sisa_pinjaman']) ?></td>
                            <td>
                                <?php
                                $badgeClass = match($p['status']) {
                                    'pending' => 'badge-warning',
                                    'disetujui' => 'badge-success',
                                    'ditolak' => 'badge-danger',
                                    'lunas' => 'badge-info',
                                    default => 'badge-primary'
                                };
                                ?>
                                <span class="badge <?= $badgeClass ?>"><?= ucfirst($p['status']) ?></span>
                            </td>
                            <td><?= formatTanggal($p['tanggal_pinjaman']) ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php
$extraJS = "
<script>
    // Savings Chart
    const ctx = document.getElementById('savingsChart')?.getContext('2d');
    if (ctx) {
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: " . json_encode($chartLabels) . ",
                datasets: [
                    {
                        label: 'Setoran',
                        data: " . json_encode($chartSetoran) . ",
                        backgroundColor: 'rgba(16, 185, 129, 0.8)',
                        borderColor: 'rgba(16, 185, 129, 1)',
                        borderWidth: 1,
                        borderRadius: 6,
                        borderSkipped: false,
                    },
                    {
                        label: 'Penarikan',
                        data: " . json_encode($chartPenarikan) . ",
                        backgroundColor: 'rgba(239, 68, 68, 0.8)',
                        borderColor: 'rgba(239, 68, 68, 1)',
                        borderWidth: 1,
                        borderRadius: 6,
                        borderSkipped: false,
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                        labels: {
                            boxWidth: 12,
                            padding: 20,
                            font: { family: 'Inter', size: 12 }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            font: { family: 'Inter', size: 11 },
                            callback: function(value) {
                                return 'Rp ' + new Intl.NumberFormat('id-ID').format(value);
                            }
                        },
                        grid: { color: 'rgba(0,0,0,0.04)' }
                    },
                    x: {
                        ticks: { font: { family: 'Inter', size: 12 } },
                        grid: { display: false }
                    }
                }
            }
        });
    }
</script>
";

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