<?php
require_once 'config.php';
require_once 'auth_helper.php';

// Ensure user is logged in (REMOVED to allow public access)
// requireLogin(); 

// Check Login Status
$is_logged_in = isset($_SESSION['user_id']);
$user_name = $_SESSION['username'] ?? '';
$user_role = $_SESSION['role'] ?? '';
$role_label = $is_logged_in ? getRoleName($user_role) : '';

// Get statistics
/* Rekap Angka Total: Menghitung kapasitas kuantitas riil (COUNT) berapa banyak pendaftar pada masing-masing tabel master (KUB, KK, dan Pengurus) untuk dijajakan pada panel utama dashboard. */
$stats_kub = $pdo->query("SELECT COUNT(*) as total FROM kub")->fetch()['total'];
$stats_kk = $pdo->query("SELECT COUNT(*) as total FROM kartu_keluarga")->fetch()['total'];
// Data anggota individual (anggota_keluarga/jumlah_anggota) telah dihapus dari sistem Flat Family Model
$stats_pengurus = $pdo->query("SELECT COUNT(*) as total FROM pengurus")->fetch()['total'];

// Get financial data for chart (current year)
/* Agregator Grafik Keuangan: Menelusuri seluruh riwayat transaksi iuran bulanan dan pengeluaran kegiatan per-tahun untuk diubah menjadi struktur tabel array yang nanti dibaca oleh Line Chart di depan. */
$current_year = date('Y');
$financial_data = [];
$total_pemasukan_year = 0;
$total_pengeluaran_year = 0;
$running_saldo = 0;

for ($i = 1; $i <= 12; $i++) {
    $month = str_pad($i, 2, '0', STR_PAD_LEFT);
    $pemasukan = $pdo->query("SELECT COALESCE(SUM(kk.jumlah_iuran_bulanan), 0) as total FROM iuran i LEFT JOIN kartu_keluarga kk ON i.id_kk = kk.id_kk WHERE YEAR(i.tanggal_pembayaran) = $current_year AND MONTH(i.tanggal_pembayaran) = $i")->fetch()['total'];
    $pengeluaran = $pdo->query("SELECT COALESCE(SUM(dana), 0) as total FROM kegiatan WHERE YEAR(waktu_tanggal) = $current_year AND MONTH(waktu_tanggal) = $i")->fetch()['total'];

    $total_pemasukan_year += $pemasukan;
    $total_pengeluaran_year += $pengeluaran;
    $running_saldo += ($pemasukan - $pengeluaran);

    $financial_data[] = [
        'month' => $bulan_indo[$i],
        'pemasukan' => $pemasukan,
        'pengeluaran' => $pengeluaran,
        'saldo' => $running_saldo
    ];
}

$saldo_akhir = $total_pemasukan_year - $total_pengeluaran_year;

$kub_stats = $pdo->query("
    SELECT k.nama_kub, 
           (SELECT COUNT(id_kk) FROM kartu_keluarga kk WHERE kk.id_kub = k.id_kub) as total_kk,
           (SELECT COALESCE(SUM(jumlah_jiwa), 0) FROM kartu_keluarga kk WHERE kk.id_kub = k.id_kub) as total_jiwa,
           (SELECT COUNT(id_pengurus) FROM pengurus p WHERE p.id_kub = k.id_kub) as total_pengurus
    FROM kub k
    ORDER BY k.nama_kub
")->fetchAll();

// Mass schedule system has been decommissioned
$jadwal_misa = [];

// Calculate total KK per KUB
$total_kk_all = array_sum(array_column($kub_stats, 'total_kk'));

// Get current month iuran status
$current_month = date('n');
$current_month_name = $bulan_indo[$current_month];
$current_periode = date('Y-m'); // Format periode: 2026-04

// Count KK that have paid this month (berdasarkan periode dan status pembayaran)
$iuran_paid = $pdo->query("
    SELECT COUNT(DISTINCT id_kk) as total 
    FROM iuran 
    WHERE periode = '$current_periode' 
    AND status_pembayaran = 'Sudah Dibayar'
")->fetch()['total'];

// Total iuran collected this month (hanya yang sudah dibayar)
$iuran_total_collected = $pdo->query("
    SELECT COALESCE(SUM(kk.jumlah_iuran_bulanan), 0) as total 
    FROM iuran i
    LEFT JOIN kartu_keluarga kk ON i.id_kk = kk.id_kk
    WHERE i.periode = '$current_periode' 
    AND i.status_pembayaran = 'Sudah Dibayar'
")->fetch()['total'];

// Calculate unpaid count
$iuran_unpaid = max(0, $stats_kk - $iuran_paid);
$iuran_percentage = $stats_kk > 0 ? round(($iuran_paid / $stats_kk) * 100, 1) : 0;

// Get upcoming activities (recently added)
$upcoming_activities = $pdo->query("
    SELECT k.*, kub.nama_kub
    FROM kegiatan k
    LEFT JOIN kub ON k.id_kub = kub.id_kub
    ORDER BY k.id_kegiatan DESC
    LIMIT 5
")->fetchAll();
?>

<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Sistem Informasi KUB Katedral Kupang</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script>
    <script src="https://unpkg.com/lenis@1/dist/lenis.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/lenis@1/dist/lenis.css">
    <link rel="stylesheet" href="style.css?v=<?= time() ?>">
    <style>
        /* Hide scrollbar completely but keep scrolling functional */
        ::-webkit-scrollbar {
            display: none;
        }

        body {
            -ms-overflow-style: none;
            /* IE and Edge */
            scrollbar-width: none;
            /* Firefox */
        }

        /* Scroll-reveal animation for stat cards */
        .stat-card {
            opacity: 0;
            transform: translateY(40px);
        }

        .stat-card.stat-visible {
            animation: statFadeUp 0.6s ease-out forwards;
        }

        /* Stagger using nth-child */
        .stat-card:nth-child(2).stat-visible {
            animation-delay: 0.1s;
        }

        .stat-card:nth-child(3).stat-visible {
            animation-delay: 0.2s;
        }

        .stat-card:nth-child(4).stat-visible {
            animation-delay: 0.3s;
        }

        @keyframes statFadeUp {
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>

<body>

    <?php $active_page = 'dashboard.php';
    include 'navbar.php'; ?>

    <!-- Wrapping main content to easily push it down -->
    <div class="main-content-wrapper" style="padding-top: 80px;">
        <div class="container" style="display: flex; flex-direction: column; gap: 25px;">
            <!-- Statistics Cards -->
            <div class="stats-grid" style="grid-template-columns: repeat(3, 1fr); align-items: stretch;">
                <div class="stat-card">
                    <div class="icon">
                        <svg viewBox="0 0 24 24" style="stroke: var(--gold)">
                            <path d="M12 2v6" />
                            <path d="M10 5h4" />
                            <path d="M12 8l-8 7v7h16v-7l-8-7z" />
                        </svg>
                    </div>
                    <div class="label">Total KUB</div>
                    <div class="value"><?= $stats_kub ?></div>
                </div>
                <div class="stat-card">
                    <div class="icon">
                        <svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 32 32">
                            <path fill="var(--gold)" stroke-width="0.2"
                                d="M28 6v20H4V6h24m0-2H4a2 2 0 0 0-2 2v20a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2Z" />
                            <path fill="var(--gold)" stroke-width="0.2"
                                d="M6 10h7v2H6zm0 4h4v2H6zm17 4h-6a3 3 0 0 0-3 3v2h2v-2a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2h2v-2a3 3 0 0 0-3-3zm-3-1a4 4 0 1 0-4-4a4 4 0 0 0 4 4zm0-6a2 2 0 1 1-2 2a2 2 0 0 1 2-2z" />
                        </svg>
                    </div>
                    <div class="label">Total Kepala Keluarga</div>
                    <div class="value"><?= $stats_kk ?></div>
                </div>
                <div class="stat-card">
                    <div class="icon">
                        <svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 48 48">
                            <path fill="none" stroke="var(--gold)" stroke-linecap="round" stroke-linejoin="round"
                                stroke-width="4"
                                d="M24 20a7 7 0 1 0 0-14a7 7 0 0 0 0 14ZM12 7.255A6.992 6.992 0 0 0 9 13a6.996 6.996 0 0 0 3.392 6M36 7.255A6.992 6.992 0 0 1 39 13a6.992 6.992 0 0 1-3 5.745M12 40v2h24v-2c0-3.727 0-5.591-.609-7.062a8 8 0 0 0-4.33-4.329C29.591 28 27.727 28 24 28s-5.591 0-7.061.609a8 8 0 0 0-4.33 4.33C12 34.408 12 36.273 12 40Zm32 2v-1.2c0-4.48 0-6.72-.872-8.432a8 8 0 0 0-3.496-3.496M4 42v-1.2c0-4.48 0-6.72.872-8.432a8 8 0 0 1 3.496-3.496" />
                        </svg>
                    </div>
                    <div class="label">Total Pengurus</div>
                    <div class="value"><?= $stats_pengurus ?></div>
                </div>
            </div>

            <!-- Iuran Status & Upcoming Activities -->
            <div class="grid-2" style="margin-top: 20px;">
                <!-- Iuran Status Widget -->
                <!-- Iuran Status Widget -->
                <div class="card" style="display: flex; flex-direction: column; gap: 20px;">
                    <h3 class="card-title"
                        style="display: flex; align-items: center; gap: 10px; border-bottom: none; padding-bottom: 0; margin-bottom: 0;">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                            stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color: var(--gold)">
                            <rect x="2" y="6" width="20" height="12" rx="2" />
                            <circle cx="12" cy="12" r="2" />
                            <path d="M6 12h.01M18 12h.01" />
                        </svg>
                        Status Iuran Bulan <?= $current_month_name ?> <?= $current_year ?>
                    </h3>
                    <div class="iuran-widget"
                        style="background: rgba(255,255,255,0.4); border-radius: 20px; padding: 25px; display: grid; grid-template-columns: 1fr 1.5fr; gap: 30px; align-items: center; border: 1px solid rgba(139, 26, 26, 0.05);">
                        <div class="iuran-chart-container"
                            style="position: relative; width: 100%; max-width: 200px; margin: 0 auto; display: flex; align-items: center; justify-content: center;">
                            <canvas id="iuranChart" style="display: block; width: 100%; position: relative; z-index: 2;"></canvas>
                            <div class="iuran-percentage"
                                style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; pointer-events: none; width: 100%; z-index: 1;">
                                <div class="value"
                                    style="font-size: 36px; font-weight: 800; color: var(--primary); font-family: 'Neue Montreal', 'Inter', sans-serif; letter-spacing: -1px; line-height: 1; margin-bottom: 2px;">
                                    <?= $iuran_percentage ?>%
                                </div>
                                <div class="label"
                                    style="font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 1.5px; color: var(--text-muted); opacity: 0.9;">
                                    Terbayar</div>
                            </div>
                        </div>
                        <div class="iuran-details" style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                            <div class="iuran-stat"
                                style="background: rgba(139, 26, 26, 0.05); padding: 15px 20px; border-radius: 16px; border: 1px solid rgba(139, 26, 26, 0.15); box-shadow: 0 4px 15px rgba(0,0,0,0.02);">
                                <span class="label"
                                    style="display: flex; align-items: center; gap: 6px; font-size: 12px; color: #8b1a1a; font-weight: 600; text-transform: uppercase;">
                                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#8b1a1a"
                                        stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
                                        <polyline points="20 6 9 17 4 12"></polyline>
                                    </svg>
                                    Sudah Bayar
                                </span>
                                <span class="value paid"
                                    style="display: block; font-size: 24px; font-weight: 800; color: #5a1111; margin-top: 5px; white-space: nowrap;"><?= $iuran_paid ?> KK</span>
                            </div>
                            <div class="iuran-stat"
                                style="background: rgba(197, 165, 90, 0.05); padding: 15px 20px; border-radius: 16px; border: 1px solid rgba(197, 165, 90, 0.2); box-shadow: 0 4px 15px rgba(0,0,0,0.02);">
                                <span class="label"
                                    style="display: flex; align-items: center; gap: 6px; font-size: 12px; color: #c5a55a; font-weight: 600; text-transform: uppercase;">
                                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#c5a55a"
                                        stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                        <circle cx="12" cy="12" r="10"></circle>
                                        <polyline points="12 6 12 12 16 14"></polyline>
                                    </svg>
                                    Belum Bayar
                                </span>
                                <span class="value unpaid"
                                    style="display: block; font-size: 24px; font-weight: 800; color: #8b7530; margin-top: 5px; white-space: nowrap;"><?= $iuran_unpaid ?> KK</span>
                            </div>
                            <div class="iuran-stat"
                                style="background: rgba(71, 85, 105, 0.05); padding: 15px 20px; border-radius: 16px; border: 1px solid rgba(71, 85, 105, 0.15); box-shadow: 0 4px 15px rgba(0,0,0,0.02); grid-column: span 2;">
                                <span class="label"
                                    style="display: flex; align-items: center; gap: 6px; font-size: 12px; color: #475569; font-weight: 600; text-transform: uppercase;">
                                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#475569"
                                        stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                        <polygon
                                            points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2">
                                        </polygon>
                                    </svg>
                                    Total Terkumpul <span style="color: #475569; white-space: nowrap;">(<?= $iuran_paid ?> KK)</span>
                                </span>
                                <span class="value amount"
                                    style="display: block; font-size: 28px; font-weight: 800; color: #1e293b; margin-top: 5px; letter-spacing: -0.5px; white-space: nowrap;">Rp <?= number_format($iuran_total_collected, 0, ',', '.') ?></span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Upcoming Activities Widget -->
                <div class="card" style="display: flex; flex-direction: column; gap: 20px;">
                    <h3 class="card-title"
                        style="display: flex; align-items: center; gap: 10px; border-bottom: none; padding-bottom: 0; margin-bottom: 0;">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                            stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color: var(--gold)">
                            <rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
                            <line x1="16" y1="2" x2="16" y2="6" />
                            <line x1="8" y1="2" x2="8" y2="6" />
                            <line x1="3" y1="10" x2="21" y2="10" />
                        </svg>
                        5 Kegiatan Terakhir
                    </h3>
                    <?php if (empty($upcoming_activities)): ?>
                        <div class="no-activity"
                            style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; min-height: 250px; text-align: center; padding: 30px; opacity: 0.6; background: rgba(255,255,255,0.4); border-radius: 20px; border: 1px solid rgba(139, 26, 26, 0.05);">
                            <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 48 48"
                                fill="#eaeaea99">
                                <g fill="none" stroke="#eaeaea99" stroke-width="4">
                                    <path stroke-linejoin="round"
                                        d="M5 19h38v22a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V19Zm0-9a2 2 0 0 1 2-2h34a2 2 0 0 1 2 2v9H5v-9Z" />
                                    <path stroke-linecap="round" stroke-linejoin="round" d="m16 31l6 6l12-12" />
                                    <path stroke-linecap="round" d="M16 5v8m16-8v8" />
                                </g>
                            </svg>
                            <p
                                style="font-family: 'Neue Montreal', 'Inter', sans-serif; font-size: 15px; font-weight: 500; margin: 0;">
                                Jadwal masih kosong</p>
                        </div>
                    <?php else: ?>
                        <div style="flex: 1; position: relative; min-height: 250px;">
                            <div class="kegiatan-scroll-container" data-lenis-prevent="true" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; overflow-y: auto; overflow-x: hidden; scrollbar-width: none; -ms-overflow-style: none; background: rgba(255,255,255,0.4); border-radius: 20px; padding: 10px 10px 10px 20px; border: 1px solid rgba(139, 26, 26, 0.05);">
                            <?php foreach ($upcoming_activities as $index => $activity): ?>
                                <?php
                                $activity_date = new DateTime($activity['waktu_tanggal']);
                                $day = $activity_date->format('d');
                                $month_num = (int) $activity_date->format('n');
                                $month_short = substr($bulan_indo[$month_num], 0, 3);
                                $time = $activity_date->format('H:i');
                                $day_name = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'][$activity_date->format('w')];
                                $is_last = $index === count($upcoming_activities) - 1;
                                ?>
                                <div class="activity-item"
                                    style="display: flex; gap: 20px; padding: 15px 0; border-bottom: <?= $is_last ? 'none' : '1px solid rgba(0,0,0,0.05)' ?>;">
                                    <div class="activity-date"
                                        style="min-width: 60px; text-align: center; display: flex; flex-direction: column; justify-content: center;">
                                        <div class="day"
                                            style="font-size: 28px; font-weight: 800; color: rgba(255, 255, 255, 0.69); line-height: 1; font-family: 'Neue Montreal', 'Inter', sans-serif; letter-spacing: -1px;">
                                            <?= $day ?>
                                        </div>
                                        <div class="month"
                                            style="font-size: 12px; font-weight: 700; text-transform: uppercase; color: var(--gold); letter-spacing: 1px; margin-top: 4px;">
                                            <?= $month_short ?>
                                        </div>
                                    </div>
                                    <div class="activity-info"
                                        style="flex: 1; display: flex; flex-direction: column; justify-content: center;">
                                        <div class="title"
                                            style="font-weight: 600; font-size: 16px; color: var(--text); margin-bottom: 4px; font-family: 'Neue Montreal', 'Inter', sans-serif;">
                                            <?= htmlspecialchars($activity['nama_kegiatan']) ?>
                                        </div>
                                        <div class="meta"
                                            style="font-size: 13px; color: var(--text-muted); display: flex; align-items: center; gap: 12px; flex-wrap: wrap;">
                                            <span style="display: flex; align-items: center; gap: 4px;">
                                                <svg width="12" height="12" viewBox="0 0 24 24" fill="none"
                                                    stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                                    stroke-linejoin="round">
                                                    <circle cx="12" cy="12" r="10"></circle>
                                                    <polyline points="12 6 12 12 16 14"></polyline>
                                                </svg>
                                                <?= $time ?> WIT
                                            </span>
                                            <?php if ($activity['nama_kub']): ?>
                                                <span style="display: flex; align-items: center; gap: 4px;">
                                                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none"
                                                        stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                                        stroke-linejoin="round">
                                                        <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
                                                        <polyline points="9 22 9 12 15 12 15 22"></polyline>
                                                    </svg>
                                                    <?= htmlspecialchars($activity['nama_kub']) ?>
                                                </span>
                                            <?php endif; ?>
                                            <?php if ($activity['tempat']): ?>
                                                <span style="display: flex; align-items: center; gap: 4px;">
                                                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none"
                                                        stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                                        stroke-linejoin="round">
                                                        <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
                                                        <circle cx="12" cy="10" r="3"></circle>
                                                    </svg>
                                                    <?= htmlspecialchars($activity['tempat']) ?>
                                                </span>
                                            <?php endif; ?>
                                        </div>

                                        <!-- Bagian/Seksi PIC (Badge Pill Style) -->
                                        <div style="margin-top: 8px;">
                                            <?php if ($activity['pengurus_terlibat']): ?>
                                                <div
                                                    style="display: inline-flex; align-items: center; gap: 6px; background: rgba(139, 26, 26, 0.05); padding: 4px 10px; border-radius: 20px; border: 1px solid rgba(139, 26, 26, 0.1);">
                                                    <svg width="10" height="10" viewBox="0 0 24 24" fill="none"
                                                        stroke="var(--primary)" stroke-width="2" stroke-linecap="round"
                                                        stroke-linejoin="round">
                                                        <path
                                                            d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z">
                                                        </path>
                                                        <line x1="7" y1="7" x2="7.01" y2="7"></line>
                                                    </svg>
                                                    <span
                                                        style="font-weight: 600; color: var(--primary); font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px;"><?= htmlspecialchars($activity['pengurus_terlibat']) ?></span>
                                                </div>
                                            <?php else: ?>
                                                <div
                                                    style="display: inline-flex; align-items: center; gap: 6px; background: rgba(0,0,0,0.03); padding: 4px 10px; border-radius: 20px;">
                                                    <span style="color: var(--text-muted); font-size: 11px; font-weight: 500;">Belum
                                                        ada PIC</span>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Financial Chart & Schedule Row (Responsive Grid) -->
            <div style="display: grid; grid-template-columns: 1fr; gap: 20px; margin-top: 20px;">
                <!-- Financial Chart -->
                <div class="card" style="display: flex; flex-direction: column; gap: 20px;">
                    <h3 class="card-title"
                        style="display: flex; align-items: center; justify-content: space-between; border-bottom: none; padding-bottom: 0; margin-bottom: 0;">
                        <span style="display: flex; align-items: center; gap: 10px;">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                                stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
                                style="color: var(--gold)">
                                <line x1="12" y1="1" x2="12" y2="23" />
                                <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
                            </svg>
                            Grafik Keuangan <?= $current_year ?>
                        </span>

                        <!-- Chart Legend Info as sleek badges -->
                        <div
                            style="display: flex; gap: 15px; font-size: 11px; font-family: 'Neue Montreal', 'Inter', sans-serif; font-weight: 600; letter-spacing: 0.5px; text-transform: uppercase;">
                            <span style="display: flex; align-items: center; gap: 6px;">
                                <div style="width: 8px; height: 8px; border-radius: 50%; background: #8b1a1a;"></div>
                                Pemasukan
                            </span>
                            <span style="display: flex; align-items: center; gap: 6px;">
                                <div style="width: 8px; height: 8px; border-radius: 50%; background: #c5a55a;"></div>
                                Pengeluaran
                            </span>
                            <span style="display: flex; align-items: center; gap: 6px;">
                                <div style="width: 8px; height: 8px; border-radius: 50%; background: #475569;"></div>
                                Saldo Akhir
                            </span>
                        </div>
                    </h3>

                    <!-- Financial Summary Cards -->
                    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px;">
                        <div
                            style="background: rgba(139, 26, 26, 0.05); border: 1px solid rgba(139, 26, 26, 0.15); padding: 20px; border-radius: 20px; text-align: left; display: flex; flex-direction: column; justify-content: center;">
                            <div
                                style="font-size: 12px; color: #8b1a1a; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 5px; display: flex; align-items: center; gap: 6px;">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                                    stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
                                </svg> Total Pemasukan
                            </div>
                            <div
                                style="font-size: 26px; font-weight: 800; color: #5a1111; font-family: 'Neue Montreal', 'Inter', sans-serif; letter-spacing: -0.5px;">
                                Rp <?= number_format($total_pemasukan_year, 0, ',', '.') ?></div>
                        </div>
                        <div
                            style="background: rgba(197, 165, 90, 0.05); border: 1px solid rgba(197, 165, 90, 0.2); padding: 20px; border-radius: 20px; text-align: left; display: flex; flex-direction: column; justify-content: center;">
                            <div
                                style="font-size: 12px; color: #c5a55a; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 5px; display: flex; align-items: center; gap: 6px;">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                                    stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M22 12h-4l-3 9L9 3l-3 9H2" />
                                </svg> Total Pengeluaran
                            </div>
                            <div
                                style="font-size: 26px; font-weight: 800; color: #8b7530; font-family: 'Neue Montreal', 'Inter', sans-serif; letter-spacing: -0.5px;">
                                Rp <?= number_format($total_pengeluaran_year, 0, ',', '.') ?></div>
                        </div>
                        <div
                            style="background: <?= $saldo_akhir >= 0 ? 'rgba(71, 85, 105, 0.05)' : 'rgba(245, 158, 11, 0.05)' ?>; border: 1px solid <?= $saldo_akhir >= 0 ? 'rgba(71, 85, 105, 0.15)' : 'rgba(245, 158, 11, 0.2)' ?>; padding: 20px; border-radius: 20px; text-align: left; display: flex; flex-direction: column; justify-content: center;">
                            <div
                                style="font-size: 12px; color: <?= $saldo_akhir >= 0 ? '#475569' : '#d97706' ?>; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 5px; display: flex; align-items: center; gap: 6px;">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                                    stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
                                </svg> Saldo Akhir
                            </div>
                            <div
                                style="font-size: 26px; font-weight: 800; color: <?= $saldo_akhir >= 0 ? '#1e293b' : '#78350f' ?>; font-family: 'Neue Montreal', 'Inter', sans-serif; letter-spacing: -0.5px;">
                                Rp <?= number_format($saldo_akhir, 0, ',', '.') ?></div>
                        </div>
                    </div>

                    <div class="chart-container" style="height: 350px; margin-top: 10px;">
                        <canvas id="financialChart"></canvas>
                    </div>
                </div>

            </div>

            <!-- KUB Statistics (Sleek List Table) -->
            <div class="card" style="display: flex; flex-direction: column; gap: 20px;">
                <h3 class="card-title"
                    style="display: flex; align-items: center; justify-content: space-between; border-bottom: none; padding-bottom: 0; margin-bottom: 0;">
                    <span style="display: flex; align-items: center; gap: 10px;">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                            stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color: var(--gold)">
                            <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                            <polyline points="14 2 14 8 20 8" />
                            <line x1="16" y1="13" x2="8" y2="13" />
                            <line x1="16" y1="17" x2="8" y2="17" />
                            <polyline points="10 9 9 9 8 9" />
                        </svg>
                        Statistik Per Lingkungan (KUB)
                    </span>
                </h3>
                <div class="table-wrapper"
                    style="background: rgba(255,255,255,0.4); border-radius: 20px; padding: 10px; border: 1px solid rgba(139, 26, 26, 0.05); overflow-x: auto;">
                    <table class="table"
                        style="width: 100%; border-collapse: separate; border-spacing: 0 8px; min-width: 800px; border: none;">
                        <thead>
                            <tr>
                                <th
                                    style="background: transparent; padding: 10px 20px; color: var(--text-muted); font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; border: none; font-family: 'Neue Montreal', 'Inter', sans-serif;">
                                    No</th>
                                <th
                                    style="background: transparent; padding: 10px 20px; color: var(--text-muted); font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; border: none; font-family: 'Neue Montreal', 'Inter', sans-serif;">
                                    Nama KUB</th>
                                <th
                                    style="background: transparent; padding: 10px 20px; color: var(--text-muted); font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; border: none; font-family: 'Neue Montreal', 'Inter', sans-serif;">
                                    Kepala Keluarga</th>
                                <th
                                    style="background: transparent; padding: 10px 20px; color: var(--text-muted); font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; border: none; font-family: 'Neue Montreal', 'Inter', sans-serif;">
                                    Jumlah Jiwa</th>
                                <th
                                    style="background: transparent; padding: 10px 20px; color: var(--text-muted); font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; border: none; font-family: 'Neue Montreal', 'Inter', sans-serif;">
                                            Total Pengurus</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            // Mapping data dinamis: Menarik variabel data statstik murni ke dalam widget baris visual per-KUB
                            $no = 1;
                            foreach ($kub_stats as $stat):
                                // Zebra striping halus
                                $bg_color = ($no % 2 !== 0) ? 'rgba(255,255,255,0.8)' : 'rgba(255,255,255,0.4)';
                                ?>
                                <tr style="background: <?= $bg_color ?>; transition: background 0.3s ease, box-shadow 0.3s ease;"
                                    onmouseover="this.style.background='rgba(197, 165, 90, 0.08)'; this.style.boxShadow='0 4px 12px rgba(168, 139, 61, 0.05)';"
                                    onmouseout="this.style.background='<?= $bg_color ?>'; this.style.boxShadow='none';">
                                    <td
                                        style="padding: 16px 20px; border: none; border-radius: 12px 0 0 12px; font-weight: 800; color: var(--gold); font-size: 14px; font-family: 'Neue Montreal', 'Inter', sans-serif;">
                                        <?= str_pad($no++, 2, '0', STR_PAD_LEFT) ?>
                                    </td>
                                    <td
                                        style="padding: 16px 20px; border: none; font-weight: 700; color: var(--text); font-family: 'Neue Montreal', 'Inter', sans-serif; font-size: 15px; letter-spacing: -0.3px;">
                                        <?= htmlspecialchars($stat['nama_kub']) ?>
                                    </td>
                                    <td
                                        style="padding: 16px 20px; border: none; color: var(--text-light); font-size: 14px; font-weight: 500;">
                                        <div
                                            style="display: inline-flex; align-items: center; gap: 6px; background: rgba(139, 26, 26, 0.05); padding: 5px 12px; border-radius: 20px; border: 1px solid rgba(139, 26, 26, 0.1);">
                                            <span
                                                style="font-weight: 700; color: var(--primary);"><?= $stat['total_kk'] ?? 0 ?></span>
                                            <span
                                                style="font-size: 12px; text-transform: uppercase; color: var(--text-muted); font-weight: 600;">KK</span>
                                        </div>
                                    </td>
                                    <td
                                        style="padding: 16px 20px; border: none; color: var(--text-light); font-size: 14px; font-weight: 500;">
                                        <div
                                            style="display: inline-flex; align-items: center; gap: 6px; background: rgba(71, 85, 105, 0.05); padding: 5px 12px; border-radius: 20px; border: 1px solid rgba(71, 85, 105, 0.1);">
                                            <span
                                                style="font-weight: 700; color: #475569;"><?= $stat['total_jiwa'] ?? 0 ?></span>
                                            <span
                                                style="font-size: 12px; text-transform: uppercase; color: var(--text-muted); font-weight: 600;">Jiwa</span>
                                        </div>
                                    </td>
                                    <td
                                        style="padding: 16px 20px; border: none; border-radius: 0 12px 12px 0; color: var(--text-light); font-size: 14px; font-weight: 500;">
                                        <div
                                            style="display: inline-flex; align-items: center; gap: 6px; background: rgba(197, 165, 90, 0.05); padding: 5px 12px; border-radius: 20px; border: 1px solid rgba(197, 165, 90, 0.2);">
                                            <span
                                                style="font-weight: 700; color: #8b7530;"><?= $stat['total_pengurus'] ?? 0 ?></span>
                                            <span
                                                style="font-size: 12px; text-transform: uppercase; color: #c5a55a; font-weight: 600;">Pengurus</span>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    </div>

    <script>
        // Financial Chart - Enhanced with Combo Bar + Line
        const ctx = document.getElementById('financialChart').getContext('2d');
        const financialData = <?= json_encode($financial_data) ?>;

        // Create gradient for pemasukan (Maroon Theme)
        const pemasukanGradient = ctx.createLinearGradient(0, 0, 0, 400);
        pemasukanGradient.addColorStop(0, 'rgba(139, 26, 26, 0.6)'); // Maroon 60%
        pemasukanGradient.addColorStop(1, 'rgba(139, 26, 26, 0.0)');

        // Create gradient for pengeluaran (Gold Theme)
        const pengeluaranGradient = ctx.createLinearGradient(0, 0, 0, 400);
        pengeluaranGradient.addColorStop(0, 'rgba(197, 165, 90, 0.5)'); // Gold 50%
        pengeluaranGradient.addColorStop(1, 'rgba(197, 165, 90, 0.0)');

        new Chart(ctx, {
            type: 'line',
            data: {
                labels: financialData.map(d => d.month),
                datasets: [{
                    label: 'Pemasukan',
                    data: financialData.map(d => d.pemasukan),
                    backgroundColor: pemasukanGradient,
                    borderColor: 'rgba(139, 26, 26, 1)', // Maroon solid
                    borderWidth: 3,
                    pointBackgroundColor: '#ffffff',
                    pointBorderColor: 'rgba(139, 26, 26, 1)',
                    pointBorderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 8,
                    tension: 0.4, // Smooth curve
                    fill: true,
                    order: 2
                }, {
                    label: 'Pengeluaran',
                    data: financialData.map(d => d.pengeluaran),
                    backgroundColor: pengeluaranGradient,
                    borderColor: 'rgba(197, 165, 90, 1)', // Gold solid
                    borderWidth: 3,
                    pointBackgroundColor: '#ffffff',
                    pointBorderColor: 'rgba(197, 165, 90, 1)',
                    pointBorderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 8,
                    tension: 0.4, // Smooth curve
                    fill: true,
                    order: 3
                }, {
                    label: 'Saldo Akhir',
                    data: financialData.map(d => d.saldo),
                    borderColor: '#475569', // Slate grey monokrom modern
                    borderWidth: 2,
                    borderDash: [6, 4], // Dashed line
                    pointBackgroundColor: '#ffffff',
                    pointBorderColor: '#475569',
                    pointBorderWidth: 2,
                    pointRadius: 3,
                    pointHoverRadius: 6,
                    tension: 0.4,
                    fill: false,
                    order: 1,
                    yAxisID: 'y1'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        backgroundColor: 'rgba(255, 255, 255, 0.95)',
                        titleColor: '#1e293b',
                        bodyColor: '#475569',
                        borderColor: 'rgba(0,0,0,0.05)',
                        borderWidth: 1,
                        titleFont: { size: 14, weight: '700', family: "'Inter', sans-serif" },
                        bodyFont: { size: 13, weight: '500', family: "'Inter', sans-serif" },
                        padding: 12,
                        cornerRadius: 12,
                        boxPadding: 6,
                        callbacks: {
                            title: function (context) {
                                return context[0].label + ' <?= $current_year ?>';
                            },
                            label: function (context) {
                                let label = context.dataset.label || '';
                                if (label) {
                                    label += ': ';
                                }
                                if (context.parsed.y !== null) {
                                    label += new Intl.NumberFormat('id-ID', {
                                        style: 'currency',
                                        currency: 'IDR',
                                        minimumFractionDigits: 0
                                    }).format(context.parsed.y);
                                }
                                return label;
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: {
                            display: false,
                            drawBorder: false
                        },
                        ticks: {
                            font: { family: "'Inter', sans-serif", size: 12 },
                            color: '#94a3b8'
                        }
                    },
                    y: {
                        type: 'linear',
                        position: 'left',
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.03)',
                            drawBorder: false,
                            borderDash: [5, 5]
                        },
                        ticks: {
                            font: { family: "'Inter', sans-serif", size: 12 },
                            color: '#94a3b8',
                            callback: function (value) {
                                if (value >= 1000000) {
                                    return 'Rp ' + (value / 1000000) + ' Jt';
                                } else if (value >= 1000) {
                                    return 'Rp ' + (value / 1000) + ' Rb';
                                }
                                return 'Rp ' + value;
                            }
                        }
                    },
                    y1: {
                        type: 'linear',
                        position: 'right',
                        beginAtZero: false,
                        title: {
                            display: true,
                            text: 'Saldo Akhir',
                            font: { size: 12 }
                        },
                        ticks: {
                            callback: function (value) {
                                if (value >= 1000000 || value <= -1000000) {
                                    return 'Rp ' + (value / 1000000).toFixed(1) + ' Jt';
                                } else if (value >= 1000 || value <= -1000) {
                                    return 'Rp ' + (value / 1000).toFixed(0) + ' Rb';
                                }
                                return 'Rp ' + value.toLocaleString('id-ID');
                            },
                            font: { size: 11 }
                        },
                        grid: {
                            drawOnChartArea: false
                        }
                    }
                },
                animation: {
                    duration: 2000,
                    easing: 'easeOutBounce',
                    delay: (context) => {
                        let delay = 0;
                        if (context.type === 'data' && context.mode === 'default') {
                            delay = context.dataIndex * 100 + context.datasetIndex * 300;
                        }
                        return delay;
                    }
                },
                animations: {
                    y: {
                        from: 0
                    },
                    opacity: {
                        from: 0,
                        to: 1,
                        duration: 1000
                    }
                }
            }
        });

        // Iuran Status Doughnut Chart
        const iuranPaid = <?= $iuran_paid ?>;
        const iuranUnpaid = <?= $iuran_unpaid ?>;

        const iuranCtx = document.getElementById('iuranChart').getContext('2d');
        new Chart(iuranCtx, {
            type: 'doughnut',
            data: {
                labels: ['Sudah Bayar', 'Belum Bayar'],
                datasets: [{
                    data: [iuranPaid, iuranUnpaid],
                    backgroundColor: [
                        'rgba(139, 26, 26, 0.9)',  // Maroon for paid
                        'rgba(197, 165, 90, 0.9)'  // Gold for unpaid
                    ],
                    borderColor: [
                        'rgba(139, 26, 26, 1)',
                        'rgba(197, 165, 90, 1)'
                    ],
                    borderWidth: 2,
                    cutout: '75%'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function (context) {
                                const total = iuranPaid + iuranUnpaid;
                                const percentage = Math.round((context.raw / total) * 100);
                                return context.label + ': ' + context.raw + ' KK (' + percentage + '%)';
                            }
                        }
                    }
                },
                animation: {
                    animateRotate: true,
                    animateScale: true,
                    duration: 1500,
                    easing: 'easeOutCirc'
                }
            }
        });
        // ========== SCROLL-TRIGGERED ANIMATIONS (Page-specific) ==========
        document.addEventListener("DOMContentLoaded", () => {
            // Hapus class anti-FOUC agar GSAP bisa membaca posisi asli sebelum animasi
            document.documentElement.classList.remove('js-loading');
            
            gsap.registerPlugin(ScrollTrigger);

            // Stat cards — CSS class toggle
            ScrollTrigger.create({
                trigger: '.stats-grid',
                start: 'top 85%',
                onEnter: () => document.querySelectorAll('.stat-card').forEach(c => c.classList.add('stat-visible')),
                onLeaveBack: () => document.querySelectorAll('.stat-card').forEach(c => c.classList.remove('stat-visible'))
            });

            // Grid-2 cards — slide from sides
            const gridCards = document.querySelectorAll('.grid-2 > .card');
            gridCards.forEach((card, i) => {
                gsap.from(card, {
                    x: i === 0 ? -80 : 80, opacity: 0, duration: 0.8, ease: 'power3.out',
                    scrollTrigger: { 
                        trigger: card, 
                        start: 'top 80%',
                        toggleActions: 'play reverse play reverse' 
                    }
                });
            });

            // Standalone cards — fade up
            document.querySelectorAll('.container .card:not(.grid-2 > .card)').forEach(card => {
                gsap.from(card, {
                    y: 50, opacity: 0, duration: 0.8, ease: 'power3.out',
                    scrollTrigger: { 
                        trigger: card, 
                        start: 'top 80%',
                        toggleActions: 'play reverse play reverse' 
                    }
                });
            });

            // Activity items — stagger slide in
            gsap.from('.activity-item', {
                x: 60, opacity: 0, duration: 0.6, stagger: 0.1, ease: 'power3.out',
                scrollTrigger: { 
                    trigger: '.activity-item', 
                    start: 'top 85%',
                    toggleActions: 'play none none reverse' 
                }
            });
        });
    </script>
    <script src="navbar.js?v=6"></script>
</body>

</html>
