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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validasi Akses Backend: Pastikan yang mengirim POST benar-benar berwenang
    if (!$is_logged_in || !hasRole(['ketua_wilayah', 'ketua_kub'])) {
        $_SESSION['message'] = ['type' => 'error', 'text' => 'Akses ditolak! Anda tidak memiliki izin (Role) yang sesuai untuk menginput atau mengedit setoran Iuran.'];
        header('Location: iuran.php');
        exit;
    }

    $action = $_POST['action'] ?? '';

    try {
        if ($action === 'create' || $action === 'update') {
            if ($action === 'create') {
                $sql = "INSERT INTO iuran (periode, id_kk, tanggal_pembayaran, metode_pembayaran, status_pembayaran) 
                        VALUES (:periode, :id_kk, :tanggal_pembayaran, :metode_pembayaran, :status_pembayaran)";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([
                    ':periode' => $_POST['periode'],
                    ':id_kk' => $_POST['id_kk'],
                    ':tanggal_pembayaran' => $_POST['tanggal_pembayaran'] ?: null,
                    ':metode_pembayaran' => $_POST['metode_pembayaran'],
                    ':status_pembayaran' => $_POST['status_pembayaran']
                ]);
                $_SESSION['message'] = ['type' => 'success', 'text' => 'Data iuran berhasil ditambahkan!'];
            } else {
                // Update
                $sql = "UPDATE iuran SET 
                        periode = :periode,
                        id_kk = :id_kk,
                        tanggal_pembayaran = :tanggal_pembayaran,
                        metode_pembayaran = :metode_pembayaran,
                        status_pembayaran = :status_pembayaran
                        WHERE id_iuran = :id_iuran";

                $params = [
                    ':id_iuran' => $_POST['id_iuran'],
                    ':periode' => $_POST['periode'],
                    ':id_kk' => $_POST['id_kk'],
                    ':tanggal_pembayaran' => $_POST['tanggal_pembayaran'] ?: null,
                    ':metode_pembayaran' => $_POST['metode_pembayaran'],
                    ':status_pembayaran' => $_POST['status_pembayaran']
                ];

                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);
                $_SESSION['message'] = ['type' => 'success', 'text' => 'Data iuran berhasil diupdate!'];
            }
        } elseif ($action === 'delete') {
            $sql = "DELETE FROM iuran WHERE id_iuran = :id_iuran";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([':id_iuran' => $_POST['id_iuran']]);
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Data iuran berhasil dihapus!'];
        }
    } catch (PDOException $e) {
        $_SESSION['message'] = ['type' => 'error', 'text' => 'Error: ' . $e->getMessage()];
    }

    header('Location: iuran.php');
    exit;
}

// Query data iuran
/* Query Master Transaksi Iuran: Menarik data pembayaran sumbangan kas dan melakukan relasi bertingkat (LEFT JOIN) ke data Kartu Keluarga lalu diteruskan ke tabel KUB agar mendapat visual utuh nama pemangku keluarga dan dari wilayah/blok KUB mana uang tersebut berasal. */
$sql = "
    SELECT 
        i.*,
        kk.nama_kepala_keluarga,
        kk.jumlah_iuran_bulanan,
        kk.no_hp,
        k.nama_kub,
        k.id_kub,
        k.ketua
    FROM iuran i
    LEFT JOIN kartu_keluarga kk ON i.id_kk = kk.id_kk
    LEFT JOIN kub k ON kk.id_kub = k.id_kub
    ORDER BY i.periode DESC, i.tanggal_pembayaran DESC
";

$stmt = $pdo->query($sql);
$iuran_list = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get summary data
$current_month = date('Y-m');
$last_month = date('Y-m', strtotime('-1 month'));

// Total iuran bulan ini
$total_bulan_ini = $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_month' AND i.status_pembayaran = 'Sudah Dibayar'
")->fetch()['total'];

// Total iuran bulan lalu
$total_bulan_lalu = $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 = '$last_month' AND i.status_pembayaran = 'Sudah Dibayar'
")->fetch()['total'];

// Total iuran tahun ini
$current_year = date('Y');
$total_tahun_ini = $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 LIKE '$current_year-%' AND i.status_pembayaran = 'Sudah Dibayar'
")->fetch()['total'];

// Ringkasan per bulan (12 bulan terakhir)
$monthly_summary = $pdo->query("
    SELECT 
        i.periode as bulan,
        COUNT(*) as total_transaksi,
        SUM(CASE WHEN i.status_pembayaran = 'Sudah Dibayar' THEN kk.jumlah_iuran_bulanan ELSE 0 END) as total_dibayar,
        SUM(CASE WHEN i.status_pembayaran = 'Belum Dibayar' THEN kk.jumlah_iuran_bulanan ELSE 0 END) as total_belum_dibayar,
        SUM(CASE WHEN i.status_pembayaran = 'Sudah Dibayar' THEN 1 ELSE 0 END) as kk_sudah_bayar,
        SUM(CASE WHEN i.status_pembayaran = 'Belum Dibayar' THEN 1 ELSE 0 END) as kk_belum_bayar
    FROM iuran i
    LEFT JOIN kartu_keluarga kk ON i.id_kk = kk.id_kk
    WHERE i.periode >= DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 12 MONTH), '%Y-%m')
    GROUP BY i.periode
    ORDER BY i.periode DESC
    LIMIT 12
")->fetchAll();

$kk_list = $pdo->query("SELECT * FROM kartu_keluarga ORDER BY id_kk")->fetchAll();
$kub_list = $pdo->query("SELECT * FROM kub ORDER BY nama_kub")->fetchAll();

// Define wilayah data for Print/Export signature
$wilayah = [
    'id_wilayah' => 4,
    'nama_wilayah' => 'Wilayah IV',
    'ketua_wilayah' => 'Ketua Wilayah IV'
];
?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Iuran Bulanan - Sistem Informasi KUB Katedral Kupang</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/exceljs/4.3.0/exceljs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
    <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>
        /* THEME OVERRIDES: Maroon, Gold, Cream, White */
        .btn-primary,
        .btn-success,
        .btn-info {
            background-color: #800000 !important;
            /* Maroon */
            border-color: #800000 !important;
            color: #ffffff !important;
        }

        .btn-primary:hover,
        .btn-success:hover,
        .btn-info:hover {
            background-color: #5c0000 !important;
            /* Darker Maroon */
            border-color: #5c0000 !important;
        }

        .btn-danger {
            background-color: var(--primary-light) !important;
            border-color: var(--primary-light) !important;
            color: #ffffff !important;
            box-shadow: none !important;
            transition: all 0.3s ease !important;
        }

        .btn-danger:hover {
            background-color: var(--primary) !important;
            border-color: var(--primary) !important;
            color: #ffffff !important;
            box-shadow: 0 6px 15px rgba(139, 26, 26, 0.45) !important;
            transform: translateY(-2px);
        }

        .btn-warning,
        .btn-edit {
            background-color: #DAA520 !important;
            /* Gold */
            border-color: #DAA520 !important;
            color: #ffffff !important;
        }

        .btn-warning:hover,
        .btn-edit:hover {
            background-color: #b8860b !important;
            /* Darker Gold */
            border-color: #b8860b !important;
        }

        .modal-header {
            background-color: #800000 !important;
            /* Maroon */
            color: #ffffff !important;
        }

        .table thead tr {
            background-color: #FFFDD0 !important;
            /* Cream */
            color: #800000 !important;
            /* Maroon text for header */
        }

        .pagination .page-link {
            color: #800000 !important;
        }

        .pagination .active .page-link {
            background-color: #800000 !important;
            border-color: #800000 !important;
            color: #ffffff !important;
        }


        /* CSS Override for Edit Button as requested */
        .card .btn-warning {
            background-color: #C83F12 !important;
            border-color: #C83F12 !important;
            color: #ffffff !important;
            box-shadow: none !important;
            transition: all 0.3s ease !important;
        }

        .card .btn-warning:hover {
            background-color: #a6340e !important;
            border-color: #a6340e !important;
            color: #ffffff !important;
            box-shadow: 0 6px 15px rgba(200, 63, 18, 0.45) !important;
            transform: translateY(-2px);
        }

        /* 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);
            }
        }

        .iuran-scroll-container::-webkit-scrollbar {
            width: 8px;
        }

        .iuran-scroll-container::-webkit-scrollbar-track {
            background: rgba(197, 165, 90, 0.1);
            border-radius: 4px;
        }

        .iuran-scroll-container::-webkit-scrollbar-thumb {
            background: var(--gold);
            border-radius: 4px;
        }

        .iuran-scroll-container::-webkit-scrollbar-thumb:hover {
            background: #b8860b;
        }


    </style>
</head>

<body>
    <!-- Loading Overlay -->
    <div id="loadingOverlay">
        <div class="spinner"></div>
        <p style="margin-top:10px; font-weight:bold;">Sedang mendownload file excel...</p>
    </div>

    <!-- Logo di-encode oleh PHP, tidak perlu tag img -->

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

    <!-- Spacer to prevent overlap -->
    <div style="height: 80px; width: 100%; display: block;"></div>
    <div class="container">
        <?php if (isset($_SESSION['message'])): ?>
            <div class="alert <?= $_SESSION['message']['type'] ?>">
                <span><?= $_SESSION['message']['text'] ?></span>
                <span class="close-alert" onclick="this.parentElement.remove()">×</span>
            </div>
            <?php unset($_SESSION['message']); ?>
        <?php endif; ?>

        <!-- Statistics Cards -->
        <div class="stats-grid no-print">
            <div class="stat-card">
                <h3>Total Iuran Bulan Ini</h3>
                <div class="value"><?= formatRupiah($total_bulan_ini) ?></div>

            </div>
            <div class="stat-card">
                <h3>Total Iuran Bulan Lalu</h3>
                <div class="value"><?= formatRupiah($total_bulan_lalu) ?></div>
            </div>
            <div class="stat-card">
                <h3>Total Iuran Tahun Ini</h3>
                <div class="value"><?= formatRupiah($total_tahun_ini) ?></div>
            </div>
        </div>

        <div class="card no-print" style="transition: box-shadow 0.3s ease;" 
             onmouseover="this.style.boxShadow='0 10px 30px rgba(168, 139, 61, 0.15)'" 
             onmouseout="this.style.boxShadow=''">
            <h3 class="card-title">Ringkasan 1 Tahun Terakhir (12 Bulan)</h3>
            <div class="table-wrapper iuran-scroll-container" data-lenis-prevent="true" style="max-height: 280px; overflow-y: auto;">
                <table class="table" style="margin-bottom: 0;">
                    <thead>
                        <tr>
                            <th>Bulan</th>
                            <th>Transaksi</th>
                            <th>KK Bayar</th>
                            <th>KK Belum</th>
                            <th>Progres</th>
                            <th>Sudah Dibayar</th>
                            <th>Belum Dibayar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $total_all_kk = count($kk_list);
                        $total_potensi = array_sum(array_column($kk_list, 'jumlah_iuran_bulanan'));
                        
                        foreach ($monthly_summary as $ms):
                            $real_belum_kk = $total_all_kk - $ms['kk_sudah_bayar'];
                            $pct = $total_all_kk > 0 ? round(($ms['kk_sudah_bayar'] / $total_all_kk) * 100) : 0;
                            if ($pct > 100) $pct = 100;
                            if ($pct < 0) $pct = 0;
                            
                            $real_uang_belum = $total_potensi - $ms['total_dibayar'];
                            if ($real_uang_belum < 0) $real_uang_belum = 0;
                        ?>
                            <tr onclick="showMonthDetail('<?= $ms['bulan'] ?>')" title="Klik untuk melihat detail">
                                <td><strong><?= date('F Y', strtotime($ms['bulan'] . '-01')) ?></strong></td>
                                <td style="text-align:center;"><?= $ms['total_transaksi'] ?></td>
                                <td style="text-align:center; color: #5a1111;">
                                    <strong><?= $ms['kk_sudah_bayar'] ?></strong> KK
                                </td>
                                <td style="text-align:center; color: #8b7530;">
                                    <strong><?= $real_belum_kk ?></strong> KK
                                </td>
                                <td>
                                    <div class="progress-bar-container">
                                        <div class="progress-bar-fill" style="width: <?= $pct ?>%; background: rgba(139, 26, 26, 0.9) !important;"></div>
                                    </div>
                                    <span class="progress-label" style="color: var(--primary); font-weight: 700;"><?= $pct ?>%</span>
                                </td>
                                <td style="color: #1e293b;"><strong><?= formatRupiah($ms['total_dibayar']) ?></strong>
                                </td>
                                <td style="color: #8b7530; font-weight: 600;">*- <?= formatRupiah($real_uang_belum) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php if (empty($monthly_summary)): ?>
                <p style="text-align: center; padding: 20px; color: #6b7280;">
                    📭 Belum ada data iuran. Silakan tambah data iuran terlebih dahulu.
                </p>
            <?php endif; ?>
        </div>

        <div class="card" style="transition: box-shadow 0.3s ease;" 
             onmouseover="this.style.boxShadow='0 10px 30px rgba(168, 139, 61, 0.15)'" 
             onmouseout="this.style.boxShadow=''">
            <div class="page-header" style="margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #eee;">
                <h2 style="margin: 0;">Daftar Iuran</h2>
                <div class="header-actions">
                    <div style="position: relative; display: inline-block;">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color: var(--text-muted); position: absolute; left: 12px; top: 50%; transform: translateY(-50%); pointer-events: none;">
                            <circle cx="11" cy="11" r="8"></circle>
                            <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                        </svg>
                        <input type="text" class="search-box" id="searchBox" placeholder="Cari Iuran..."
                            style="width: 250px; padding-left: 35px; border: 1px solid rgba(168, 139, 61, 0.1); background: rgba(168, 139, 61, 0.02); box-shadow: 0 2px 5px rgba(168, 139, 61, 0.05); transition: box-shadow 0.3s ease;" 
                            onmouseover="this.style.boxShadow='0 5px 15px rgba(168, 139, 61, 0.15)'" 
                            onmouseout="this.style.boxShadow='0 2px 5px rgba(168, 139, 61, 0.05)'"
                            onkeyup="searchTable()">
                    </div>
                    <?php if ($is_logged_in && hasRole(['admin_paroki', 'ketua_wilayah', 'ketua_kub'])): ?>
                        <button class="btn btn-print" onclick="confirmPrint()" style="display: inline-flex; align-items: center; gap: 6px;">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <polyline points="6 9 6 2 18 2 18 9"></polyline>
                                <path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"></path>
                                <rect x="6" y="14" width="12" height="8"></rect>
                            </svg>
                            Print
                        </button>
                        <button class="btn btn-export" onclick="confirmExportExcel()" style="display: inline-flex; align-items: center; gap: 6px;">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M14 2H6a2 2 0 0 0-2 2v16c0 1.1.9 2 2 2h12a2 2 0 0 0 2-2V8l-6-6z"/>
                                <path d="M14 3v5h5M16 13H8M16 17H8M10 9H8"/>
                            </svg>
                            Export Excel
                        </button>
                    <?php endif; ?>
                    <?php if ($is_logged_in && hasRole(['ketua_wilayah', 'ketua_kub'])): ?>
                        <button class="btn btn-success" onclick="openModal('create')">+ Tambah Iuran</button>
                    <?php endif; ?>
                </div>
            </div>
            <div class="print-header" id="printHeader"></div>
            <div class="table-wrapper">
                <table class="table" id="iuranTable" style="margin-bottom: 0;">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Periode</th>
                            <th>Nama Kepala Keluarga</th>
                            <th>KUB</th>
                            <th>Jumlah Iuran</th>
                            <th>Tanggal Pembayaran</th>
                            <th>Metode</th>
                            <th>Status</th>
                            <?php if ($is_logged_in && hasRole(['ketua_wilayah', 'ketua_kub'])): ?>
                                <th class="no-print">Aksi</th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody id="iuranTableBody">
                        <!-- Pola perulangan Foreach: Menyalin format baris sel HTML ke bawah secara berulang sebanyak akumulasi rekam iuran kas -->
                        <?php $no = 1;
                        foreach ($iuran_list as $i): ?>
                            <tr data-kub-id="<?= htmlspecialchars($i['id_kub'] ?? '') ?>"
                                data-nama-kub="<?= htmlspecialchars($i['nama_kub'] ?? '') ?>"
                                data-ketua="<?= htmlspecialchars($i['ketua'] ?? '') ?>"
                                data-periode="<?= htmlspecialchars($i['periode']) ?>">
                                <td><?= $no++ ?></td>
                                <td><?= date('F Y', strtotime($i['periode'] . '-01')) ?></td>
                                <td><strong><?= htmlspecialchars($i['nama_kepala_keluarga']) ?></strong></td>
                                <td>
                                    <?php if (!empty($i['nama_kub'])): ?>
                                        <?= htmlspecialchars($i['nama_kub']) ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Belum dipilih</span>
                                    <?php endif; ?>
                                </td>
                                <td><?= formatRupiah($i['jumlah_iuran_bulanan']) ?></td>
                                <td><?= $i['tanggal_pembayaran'] ? formatTanggalIndo($i['tanggal_pembayaran']) : '<span style="color: #999; font-size: 12px; font-style: italic;">Belum bayar</span>' ?></td>
                                <td>
                                    <?php if (!empty($i['metode_pembayaran'])): ?>
                                        <?= htmlspecialchars($i['metode_pembayaran']) ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Belum dipilih</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?= $i['status_pembayaran'] ?>
                                </td>
                                <?php if ($is_logged_in && hasRole(['ketua_wilayah', 'ketua_kub'])): ?>
                                    <td class="no-print">
                                        <div style="display: flex; gap: 5px;">
                                            <button class="btn btn-sm btn-warning"
                                                onclick='editIuran(<?= json_encode($i) ?>)'>Edit</button>
                                            <button class="btn btn-sm btn-danger"
                                                onclick="deleteIuran(<?= $i['id_iuran'] ?>, '<?= htmlspecialchars($i['nama_kepala_keluarga']) ?>')">Hapus</button>
                                        </div>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot id="tableFooter">
                        <tr style="background-color: rgba(168, 139, 61, 0.1); font-weight: bold;">
                            <td colspan="4" style="text-align: right; padding: 12px;">Total Iuran:</td>
                            <td id="totalIuran" style="padding: 12px; white-space: nowrap;">Rp 0</td>
                            <td colspan="3"></td>
                            <?php if ($is_logged_in && hasRole(['ketua_wilayah', 'ketua_kub'])): ?>
                                <td class="no-print"></td>
                            <?php endif; ?>
                        </tr>
                    </tfoot>
                </table>
            </div>
            <div class="pagination-container" id="iuranPagination"></div>
        </div>
        <div class="print-footer" id="printFooter"></div>
    </div>


    <!-- Print/Export Modal -->


    <!-- Modal CRUD -->
    <div id="iuranModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">Tambah Iuran</h3>
                <button class="close" onclick="closeModal()">&times;</button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <div class="modal-body">
                    <input type="hidden" name="action" id="formAction" value="create">
                    <input type="hidden" name="id_iuran" id="id_iuran">

                    <div class="form-row">
                        <div class="form-group">
                            <label>Periode (Bulan) *</label>
                            <input type="month" name="periode" id="periode" required>
                        </div>
                        <div class="form-group">
                            <label>Kepala Keluarga *</label>
                            <input type="hidden" name="id_kk" id="id_kk" required>
                            <input type="text" id="search_kk" list="kk_options" placeholder="Ketik atau Pilih KK..." required autocomplete="off" onchange="handleKKSelection(this)" oninput="handleKKSelection(this)">
                            <datalist id="kk_options">
                                <?php foreach ($kk_list as $kk): ?>
                                    <option value="<?= htmlspecialchars($kk['nama_kepala_keluarga']) ?>" data-id="<?= $kk['id_kk'] ?>" data-iuran="<?= $kk['jumlah_iuran_bulanan'] ?>"></option>
                                <?php endforeach; ?>
                            </datalist>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Jumlah Iuran (Rp) </label>
                            <input type="number" name="jumlah_iuran" id="jumlah_iuran" required min="0" readonly tabindex="-1" style="pointer-events: none; background-color: #f5f5f5; color: #666; border-color: #e0e0e0; cursor: not-allowed;">
                        </div>
                        <div class="form-group">
                            <label>Tanggal Pembayaran </label>
                            <input type="date" name="tanggal_pembayaran" id="tanggal_pembayaran">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Metode Pembayaran </label>
                            <select name="metode_pembayaran" id="metode_pembayaran">
                                <option value="">Pilih</option>
                                <option value="Tunai">Tunai</option>
                                <option value="Transfer">Transfer Bank</option>
                                <option value="E-Wallet">E-Wallet</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Status Pembayaran *</label>
                            <select name="status_pembayaran" id="status_pembayaran" required>
                                <option value="Belum Dibayar">Belum Dibayar</option>
                                <option value="Sudah Dibayar">Sudah Dibayar</option>
                            </select>
                        </div>
                    </div>


                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-print" onclick="closeModal()">Batal</button>
                    <button type="submit" class="btn btn-export">Simpan</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Delete Modal -->
    <div id="deleteModal" class="modal">
        <div class="modal-content" style="max-width: 400px;">
            <div class="modal-header">
                <h3>Hapus Iuran</h3>
                <button class="close" onclick="closeDeleteModal()">&times;</button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id_iuran" id="delete_id_iuran">
                    <p>Yakin ingin menghapus data iuran <strong id="delete_nama_kk"></strong>?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-print" onclick="closeDeleteModal()">Batal</button>
                    <button type="submit" class="btn btn-export">Hapus</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Month Detail Modal -->
    <div id="monthDetailModal" class="modal">
        <div class="modal-content" style="max-width: 800px;">
            <div class="modal-header">
                <h3 id="monthDetailTitle">Detail Iuran</h3>
                <button class="close" onclick="closeMonthDetailModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div id="monthDetailContent">
                    <p style="text-align: center; color: #6b7280;">Memuat data...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-print"
                    onclick="closeMonthDetailModal()">Tutup</button>
            </div>
        </div>
    </div>

    <script>
        // Logo base64 di-generate langsung oleh PHP (menghindari masalah canvas/CORS)
        <?php
        $__logo_file = __DIR__ . DIRECTORY_SEPARATOR . 'logo1.jpg';
        $__logo_data = file_exists($__logo_file) ? base64_encode(file_get_contents($__logo_file)) : '';
        ?>
        var LOGO_BASE64_RAW = "<?= $__logo_data ?>";
        var LOGO_DATA_URI = LOGO_BASE64_RAW ? "data:image/jpeg;base64," + LOGO_BASE64_RAW : "";

        function openModal(action) {
            document.body.style.overflow = 'hidden';
            if (window.lenis) window.lenis.stop();
            document.getElementById('iuranModal').style.display = 'block';
            if (window.initModalLenis) window.initModalLenis('iuranModal');

            if (action === 'create') {
                document.getElementById('modalTitle').innerText = 'Tambah Iuran';
                document.getElementById('formAction').value = 'create';
                document.querySelector('#iuranModal form').reset();
                document.getElementById('id_iuran').value = '';
                document.getElementById('id_kk').value = '';
                document.getElementById('search_kk').value = '';
                // Set default periode to current month
                document.getElementById('periode').value = '<?= date('Y-m') ?>';
            }
        }

        function closeModal() {
            if (window.modalLenis) {
                window.modalLenis.destroy();
                window.modalLenis = null;
            }
            document.getElementById('iuranModal').style.display = 'none';
            document.body.style.overflow = '';
            if (window.lenis) window.lenis.start();
        }

        function closeDeleteModal() {
            if (window.modalLenis) {
                window.modalLenis.destroy();
                window.modalLenis = null;
            }
            document.getElementById('deleteModal').style.display = 'none';
            document.body.style.overflow = '';
            if (window.lenis) window.lenis.start();
        }

        function handleKKSelection(input) {
            const val = input.value;
            const options = document.querySelectorAll('#kk_options option');
            let found = false;
            for(let i = 0; i < options.length; i++) {
                if(options[i].value === val) {
                    document.getElementById('id_kk').value = options[i].getAttribute('data-id');
                    document.getElementById('jumlah_iuran').value = options[i].getAttribute('data-iuran');
                    found = true;
                    break;
                }
            }
            if(!found) {
                document.getElementById('id_kk').value = '';
                document.getElementById('jumlah_iuran').value = '';
                // Custom validation to prevent submit if not in list
                input.setCustomValidity("Silakan pilih Kepala Keluarga dari daftar.");
            } else {
                input.setCustomValidity("");
            }
        }

        function editIuran(iuran) {
            openModal('edit');
            document.getElementById('modalTitle').innerText = 'Edit Iuran';
            document.getElementById('formAction').value = 'update';
            document.getElementById('id_iuran').value = iuran.id_iuran;
            document.getElementById('periode').value = iuran.periode;
            
            document.getElementById('id_kk').value = iuran.id_kk;
            document.getElementById('search_kk').value = iuran.nama_kepala_keluarga;
            
            document.getElementById('jumlah_iuran').value = iuran.jumlah_iuran_bulanan;
            document.getElementById('tanggal_pembayaran').value = iuran.tanggal_pembayaran || '';
            document.getElementById('metode_pembayaran').value = iuran.metode_pembayaran;
            document.getElementById('status_pembayaran').value = iuran.status_pembayaran;
        }

        /* Fungsi keamanan lapis pertama mencegah data iuran terhapus tanpa sadar */
        function deleteIuran(id, nama) {
            document.body.style.overflow = 'hidden';
            if (window.lenis) window.lenis.stop();
            document.getElementById('deleteModal').style.display = 'block';
            if (window.initModalLenis) window.initModalLenis('deleteModal');
            document.getElementById('delete_id_iuran').value = id;
            document.getElementById('delete_nama_kk').innerText = nama;
        }

        function searchTable() {
            const filter = document.getElementById('searchBox').value.toUpperCase();
            if (window.iuranPaginationPaginator) {
                window.iuranPaginationPaginator.markSearchFiltered(function(row) {
                    const tds = row.getElementsByTagName('td');
                    for (let j = 0; j < tds.length; j++) {
                        if (tds[j].innerText.toUpperCase().indexOf(filter) > -1) return true;
                    }
                    return false;
                });
            }
            calculateTotals();
        }

        function calculateTotals() {
            let totalIuran = 0;
            document.querySelectorAll('#iuranTable tbody tr').forEach(row => {
                if (row.style.display !== 'none') {
                    const iuranText = row.cells[4].innerText;
                    const iuranNum = parseInt(iuranText.replace(/[^0-9]/g, '')) || 0;
                    totalIuran += iuranNum;
                }
            });
            document.getElementById('totalIuran').innerText = 'Rp ' + totalIuran.toLocaleString('id-ID');
        }

        // Data iuran untuk modal detail
        const iuranData = <?= json_encode($iuran_list) ?>;
        // Data semua KK
        const allKK = <?= json_encode(array_map(function ($kk) {
                            return [
                                'id_kk' => $kk['id_kk'],
                                'nama_kepala_keluarga' => $kk['nama_kepala_keluarga'],
                                'no_hp' => $kk['no_hp'],
                                'jumlah_iuran_bulanan' => $kk['jumlah_iuran_bulanan']
                            ];
                        }, $kk_list)) ?>;


        // Print/Export Functions
        const wilayahData = <?= json_encode($wilayah) ?>;

        /* Fungsi meracik cell, kop, dan logo untuk diexport jadi berkas .xlsx rekap Iuran Bulanan */
        async function confirmExportExcel() {
            document.getElementById('loadingOverlay').style.display = 'flex';
            try {
                var uniqueKUBs = new Set();
                var uniquePeriode = new Set();
                var lastVisibleKUBName = '';
                var lastVisiblePeriode = '';
                document.querySelectorAll('#iuranTable tbody tr').forEach(function(row) {
                    if (row.style.display !== 'none') {
                        var kubName = row.cells[4].innerText;
                        var periode = row.cells[1].innerText;
                        if (kubName) { uniqueKUBs.add(kubName); lastVisibleKUBName = kubName; }
                        if (periode) { uniquePeriode.add(periode); lastVisiblePeriode = periode; }
                    }
                });
                var namaKUB = uniqueKUBs.size === 1 ? lastVisibleKUBName : '';
                var periodeText = uniquePeriode.size === 1 ? lastVisiblePeriode : 'Semua Periode';

                // Logo base64 sudah tersedia dari variabel global PHP
                var base64Logo = LOGO_BASE64_RAW;

                var workbook = new ExcelJS.Workbook();
                var ws = workbook.addWorksheet('Data Iuran');

                ws.columns = [
                    { width: 6 }, { width: 15 }, { width: 25 }, { width: 15 },
                    { width: 15 }, { width: 15 }, { width: 12 }, { width: 15 }
                ];

                // === KOP SURAT ===
                ws.mergeCells('A1:I1');
                ws.getCell('A1').value = 'PAROKI KRISTUS RAJA KATEDRAL KUPANG';
                ws.getCell('A1').font = { name: 'Times New Roman', size: 14, bold: true };
                ws.getCell('A1').alignment = { horizontal: 'center', vertical: 'middle' };
                ws.getRow(1).height = 22;

                ws.mergeCells('A2:I2');
                ws.getCell('A2').value = 'WILAYAH IV MERDEKA';
                ws.getCell('A2').font = { name: 'Times New Roman', size: 12, bold: true };
                ws.getCell('A2').alignment = { horizontal: 'center', vertical: 'middle' };
                ws.getRow(2).height = 20;

                var kopLastRow = 2;
                if (namaKUB) {
                    ws.mergeCells('A3:I3');
                    ws.getCell('A3').value = namaKUB.toUpperCase();
                    ws.getCell('A3').font = { name: 'Times New Roman', size: 12, bold: true };
                    ws.getCell('A3').alignment = { horizontal: 'center', vertical: 'middle' };
                    ws.getRow(3).height = 20;
                    kopLastRow = 3;
                }

                // Garis kop surat (double bottom border)
                for (var col = 1; col <= 9; col++) {
                    ws.getRow(kopLastRow).getCell(col).border = {
                        bottom: { style: 'double', color: { argb: 'FF000000' } }
                    };
                }

                if (base64Logo) {
                    var imageId = workbook.addImage({ base64: base64Logo, extension: 'jpeg' });
                    // Ukuran logo dinamis: 72px jika 3 baris (KUB spesifik), 45px jika 2 baris (Semua KUB)
                    // Digunakan pecahan (0.1) untuk memberi jarak spasi/padding aman dari tepi margin
                    var logoSize = kopLastRow === 3 ? 62 : 40;
                    ws.addImage(imageId, { 
                        tl: { col: 0.1, row: 0.1 }, 
                        ext: { width: logoSize, height: logoSize } 
                    });
                }

                var sepRow = kopLastRow + 1;
                ws.getRow(sepRow).height = 8;

                // === TANGGAL ===
                var dRow = sepRow + 1;
                var now = new Date();
                var days = ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'];
                var months = ['Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
                var printStr = 'Dicetak pada: ' + days[now.getDay()] + ', ' + now.getDate() + ' ' + months[now.getMonth()] + ' ' + now.getFullYear() + ' Pukul ' + String(now.getHours()).padStart(2,'0') + ':' + String(now.getMinutes()).padStart(2,'0');

                ws.mergeCells('A' + dRow + ':I' + dRow);
                ws.getCell('A' + dRow).value = printStr;
                ws.getCell('A' + dRow).font = { italic: true, size: 9 };
                ws.getCell('A' + dRow).alignment = { horizontal: 'right' };

                // === JUDUL ===
                var tRow = dRow + 1;
                ws.mergeCells('A' + tRow + ':I' + tRow);
                ws.getCell('A' + tRow).value = 'DATA IURAN' + (periodeText ? ' (' + periodeText.toUpperCase() + ')' : '');
                ws.getCell('A' + tRow).font = { size: 14, bold: true, underline: true };
                ws.getCell('A' + tRow).alignment = { horizontal: 'center' };
                ws.getRow(tRow + 1).height = 8;

                // === HEADER ===
                var headerRow = ws.addRow(['No', 'Periode', 'Nama Kepala Keluarga', 'KUB', 'Jumlah Iuran', 'Tgl Pembayaran', 'Metode', 'Status']);
                headerRow.height = 22;
                headerRow.eachCell(function(cell) {
                    cell.font = { bold: true, size: 10 };
                    cell.alignment = { horizontal: 'center', vertical: 'middle' };
                    cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
                    cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } };
                });

                // === DATA ===
                var num = 1;
                var totalIuran = 0;
                document.querySelectorAll('#iuranTable tbody tr').forEach(function(row) {
                    if (row.style.display !== 'none') {
                        var c = row.cells;
                        if (c && c.length >= 8) {
                            var iuranText = c[4].innerText;
                            var iuranVal = parseInt(iuranText.replace(/[^0-9]/g, '')) || 0;
                            totalIuran += iuranVal;
                            var dr = ws.addRow([num++, c[1].innerText.trim(), c[2].innerText.trim(), c[3].innerText.trim(), iuranVal, c[5].innerText.trim(), c[6].innerText.trim(), c[7].innerText.trim()]);
                            dr.eachCell(function(cell, colNumber) {
                                cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } };
                                cell.font = { size: 10 };
                                
                                // wrapText: true berfungsi agar teks yang berjejal, seperti "Diterima \r\n RD. Simon", tidak merusak dan menembus garis
                                cell.alignment = { vertical: 'middle', wrapText: true };
                                if (colNumber === 1 || colNumber === 8) {
                                    cell.alignment = { horizontal: 'center', vertical: 'middle', wrapText: true };
                                }
                                
                                if (colNumber === 5) cell.numFmt = '"Rp "#,##0';
                            });
                        }
                    }
                });

                // === TOTAL ===
                var totalRow = ws.addRow(['', '', '', 'Total Iuran:', totalIuran, '', '', '']);
                ws.mergeCells('A' + totalRow.number + ':D' + totalRow.number);
                
                var cellA = ws.getCell('A' + totalRow.number);
                cellA.value = 'Total Iuran:';
                cellA.font = { bold: true };
                cellA.alignment = { horizontal: 'right' };
                
                var cellIuran = ws.getCell('E' + totalRow.number);
                cellIuran.value = totalIuran;
                cellIuran.font = { bold: true };
                cellIuran.numFmt = '"Rp "#,##0';

                // Tambahkan border dari kolom 1 (A) sampai 8 (H) agar garisnya penuh mengikuti panjang tabel
                for (var i = 1; i <= 8; i++) {
                    var cell = ws.getCell(totalRow.number, i);
                    cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } };
                }

                var dateFile = now.toISOString().split('T')[0];
                var safeKubName = namaKUB ? namaKUB.replace(/\s+/g, '_') : 'Semua';
                var safePeriode = uniquePeriode.size === 1 ? '_' + lastVisiblePeriode : '';
                var buffer = await workbook.xlsx.writeBuffer();
                saveAs(new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), 'Iuran_' + safeKubName + safePeriode + '_' + dateFile + '.xlsx');
            } catch (error) {
                console.error('Excel Export Error:', error);
                alert('Gagal mengekspor data ke Excel: ' + error.message);
            } finally {
                document.getElementById('loadingOverlay').style.display = 'none';
            }
        }


        /* Fungsi men-generate DOM baru bergaya dokumen resmi (print-ready) sementara yang asli disembunyikan */
        function confirmPrint() {
            let uniqueKUBs = new Set();
            let uniquePeriode = new Set();
            let lastVisibleKUBName = '';
            let lastVisiblePeriode = '';
            document.querySelectorAll('#iuranTable tbody tr').forEach(row => {
                if (row.style.display !== 'none') {
                    const kubName = row.cells[3].innerText;
                    const periode = row.cells[1].innerText;
                    if (kubName) { uniqueKUBs.add(kubName); lastVisibleKUBName = kubName; }
                    if (periode) { uniquePeriode.add(periode); lastVisiblePeriode = periode; }
                }
            });
            const namaKUB = uniqueKUBs.size === 1 ? lastVisibleKUBName : '';
            const periodeText = uniquePeriode.size === 1 ? lastVisiblePeriode : 'Semua Periode';

            // Logo data URI sudah tersedia dari variabel global PHP
            const base64Logo = LOGO_DATA_URI;

            // Build table rows from visible data
            let tableRows = '';
            let num = 1;
            document.querySelectorAll('#iuranTable tbody tr').forEach(row => {
                if (row.style.display !== 'none') {
                    const c = row.cells;
                    tableRows += `<tr>
                        <td style="border:1px solid #000; padding:6px; text-align:center;">${num++}</td>
                        <td style="border:1px solid #000; padding:6px;">${c[1].innerText}</td>
                        <td style="border:1px solid #000; padding:6px;">${c[2].innerText}</td>
                        <td style="border:1px solid #000; padding:6px;">${c[4].innerText}</td>
                        <td style="border:1px solid #000; padding:6px;">${c[3].innerText}</td>
                        <td style="border:1px solid #000; padding:6px;">${c[5].innerText}</td>
                        <td style="border:1px solid #000; padding:6px;">${c[7].innerText}</td>
                    </tr>`;
                }
            });

            let totalIuranPrint = 0;
            document.querySelectorAll('#iuranTable tbody tr').forEach(row => {
                if (row.style.display !== 'none') {
                    const iuranText = row.cells[4].innerText;
                    totalIuranPrint += parseInt(iuranText.replace(/[^0-9]/g, '')) || 0;
                }
            });
            const totalIuranPrintStr = 'Rp ' + totalIuranPrint.toLocaleString('id-ID');

            tableRows += `
                <tr style="background-color: #f0f0f0; font-weight: bold;">
                    <td colspan="6" style="border:1px solid #000; padding:6px; text-align:right;">Total Iuran:</td>
                    <td style="border:1px solid #000; padding:6px; text-align:right;">${totalIuranPrintStr}</td>
                </tr>`;

            const now = new Date();
            const days = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
            const months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
            const dayName = days[now.getDay()];
            const printDateTimeStr = `Dicetak pada: ${dayName}, ${now.getDate()} ${months[now.getMonth()]} ${now.getFullYear()} Pukul ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;

            // Create standalone print overlay
            const printOverlay = document.createElement('div');
            printOverlay.id = 'tempPrintOverlay';
            printOverlay.style.cssText = 'display:none;';
            printOverlay.innerHTML = `
            <div style="padding: 20px; font-family: 'Times New Roman', Times, serif;">
                <div style="position:relative; min-height:77px; border-bottom:3px double #000; padding-bottom:8px; margin-bottom:13px;">
                    <img src="${base64Logo}" style="position:absolute; left:0; top:0; width:70px;">
                    <div style="width:100%; text-align:center; padding-top:5px;">
                        <h2 style="margin:0; font-size:18px;">PAROKI KRISTUS RAJA KATEDRAL KUPANG</h2>
                        <h3 style="margin:2px 0; font-size:16px;">WILAYAH IV MERDEKA</h3>
                        ${namaKUB ? `<h3 style="margin:2px 0; font-size:16px;">${namaKUB.toUpperCase()}</h3>` : ''}
                    </div>
                </div>
                <div style="text-align:right; font-size:10pt; margin-bottom:8px;"><i>${printDateTimeStr}</i></div>
                <div style="text-align:center; margin-bottom:17px;">
                    <h3 style="text-decoration:underline; font-size:16px;">DATA IURAN${periodeText ? ` (${periodeText.toUpperCase()})` : ''}</h3>
                </div>
                <table style="width:100%; border-collapse:collapse; font-size:9pt;">
                    <thead>
                        <tr style="background:#f0f0f0;">
                            <th style="border:1px solid #000; padding:6px;">No</th>
                            <th style="border:1px solid #000; padding:6px;">Periode</th>
                            <th style="border:1px solid #000; padding:6px;">Nama Kepala Keluarga</th>
                            <th style="border:1px solid #000; padding:6px;">Jumlah</th>
                            <th style="border:1px solid #000; padding:6px;">KUB</th>
                            <th style="border:1px solid #000; padding:6px;">Tanggal Pembayaran</th>
                            <th style="border:1px solid #000; padding:6px;">Status</th>
                        </tr>
                    </thead>
                    <tbody>${tableRows}</tbody>
                </table>
            </div>`;

            const printStyle = document.createElement('style');
            printStyle.id = 'tempPrintStyle';
            printStyle.innerHTML = `
                @media print {
                    body > *:not(#tempPrintOverlay) { display: none !important; }
                    #tempPrintOverlay { display: block !important; position: absolute; left: 0; top: 0; width: 100%; padding: 20px; box-sizing: border-box; }
                    @page { margin: 15mm; size: auto; }
                    table th { background-color: #f0f0f0 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
                }
            `;

            document.head.appendChild(printStyle);
            document.body.appendChild(printOverlay);

            setTimeout(() => {
                window.print();
            }, 300);
        }

        window.onafterprint = function() {
            const overlay = document.getElementById('tempPrintOverlay');
            if (overlay) overlay.remove();
            const style = document.getElementById('tempPrintStyle');
            if (style) style.remove();
        };

        // Show month detail - full detail view for clicked month
        function showMonthDetail(periode) {
            document.body.style.overflow = 'hidden';
            if (window.lenis) window.lenis.stop();

            const allRows = document.querySelectorAll('#iuranTable tbody tr');
            let paidFamilies = [];
            let unpaidFamilies = [];
            let totalPaid = 0;
            let totalUnpaid = 0;

            allRows.forEach(row => {
                const rowPeriode = row.getAttribute('data-periode');
                if (rowPeriode === periode) {
                    const nama = row.cells[2]?.innerText || '';
                    const kub = row.cells[3]?.innerText || '';
                    const jumlah = row.cells[4]?.innerText || '';
                    const rawAmount = parseInt(jumlah.replace(/[^0-9]/g, '')) || 0;
                    const tglBayar = row.cells[5]?.innerText || '-';
                    const metode = row.cells[6]?.innerText || '-';
                    const status = row.cells[7]?.innerText.trim() || '';
                    const entry = {
                        nama,
                        kub,
                        jumlah,
                        tglBayar,
                        metode
                    };

                    if (status === 'Sudah Dibayar') {
                        paidFamilies.push(entry);
                        totalPaid += rawAmount;
                    } else {
                        unpaidFamilies.push(entry);
                        totalUnpaid += rawAmount;
                    }
                }
            });

            const months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
            const [year, month] = periode.split('-');
            const periodeLabel = months[parseInt(month) - 1] + ' ' + year;
            const totalKK = paidFamilies.length + unpaidFamilies.length;
            const pct = totalKK > 0 ? Math.round((paidFamilies.length / totalKK) * 100) : 0;
            const grandTotal = totalPaid + totalUnpaid;

            // Format currency
            const fmt = (n) => 'Rp ' + n.toLocaleString('id-ID');

            // Build summary stats
            const summaryHTML = `
                <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap:12px; margin-bottom:20px;">
                    <div style="background:rgba(90, 17, 17, 0.05); padding:14px; border-radius:12px; text-align:center; border: 1px solid rgba(90, 17, 17, 0.1);">
                        <div style="font-size:11px; color:#5a1111; font-weight:600; text-transform:uppercase; letter-spacing: 0.5px;">Sudah Bayar</div>
                        <div style="font-size:24px; font-weight:700; color:#5a1111;">${paidFamilies.length} <span style="font-size:12px; font-weight:500;">KK</span></div>
                    </div>
                    <div style="background:rgba(139, 117, 48, 0.05); padding:14px; border-radius:12px; text-align:center; border: 1px solid rgba(139, 117, 48, 0.1);">
                        <div style="font-size:11px; color:#8b7530; font-weight:600; text-transform:uppercase; letter-spacing: 0.5px;">Belum Bayar</div>
                        <div style="font-size:24px; font-weight:700; color:#8b7530;">${unpaidFamilies.length} <span style="font-size:12px; font-weight:500;">KK</span></div>
                    </div>
                    <div style="background:rgba(30, 41, 59, 0.05); padding:14px; border-radius:12px; text-align:center; border: 1px solid rgba(30, 41, 59, 0.1);">
                        <div style="font-size:11px; color:#1e293b; font-weight:600; text-transform:uppercase; letter-spacing: 0.5px;">Total Terkumpul</div>
                        <div style="font-size:16px; font-weight:700; color:#1e293b;">${fmt(totalPaid)}</div>
                        <div style="font-size:11px; color:rgba(30, 41, 59, 0.6);">dari ${fmt(grandTotal)}</div>
                    </div>
                </div>
                <div style="margin-bottom:20px;">
                    <div style="display:flex; justify-content:space-between; margin-bottom:4px;">
                        <span style="font-size:12px; font-weight:600; color:#1e293b;">Progres Pembayaran</span>
                        <span style="font-size:12px; font-weight:600; color:#1e293b;">${pct}%</span>
                    </div>
                    <div class="progress-bar-container" style="height:12px;">
                        <div class="progress-bar-fill" style="width:${pct}%; height:100%; background: rgba(139, 26, 26, 0.9) !important;"></div>
                    </div>
                </div>`;

            // Build paid table
            let paidHTML = '';
            if (paidFamilies.length > 0) {
                paidHTML = `<div class="table-wrapper"><table class="table" style="min-width:auto;">
                    <thead><tr>
                        <th>No</th><th>Nama Kepala Keluarga</th><th>KUB</th>
                        <th>Jumlah</th><th>Tgl Pembayaran</th><th>Metode</th>
                    </tr></thead><tbody>`;
                paidFamilies.forEach((f, i) => {
                    paidHTML += `<tr>
                        <td>${i + 1}</td><td><strong>${f.nama}</strong></td><td>${f.kub}</td>
                        <td>${f.jumlah}</td><td>${f.tglBayar}</td><td>${f.metode}</td>
                    </tr>`;
                });
                paidHTML += '</tbody></table></div>';
            } else {
                paidHTML = '<p style="text-align:center; color:#9B8E84; padding:15px;">Belum ada keluarga yang membayar</p>';
            }

            // Build unpaid table
            let unpaidHTML = '';
            if (unpaidFamilies.length > 0) {
                unpaidHTML = `<div class="table-wrapper"><table class="table" style="min-width:auto;">
                    <thead><tr>
                        <th>No</th><th>Nama Kepala Keluarga</th><th>KUB</th>
                        <th>Jumlah</th>
                    </tr></thead><tbody>`;
                unpaidFamilies.forEach((f, i) => {
                    unpaidHTML += `<tr>
                        <td>${i + 1}</td><td><strong>${f.nama}</strong></td><td>${f.kub}</td>
                        <td>${f.jumlah}</td>
                    </tr>`;
                });
                unpaidHTML += '</tbody></table></div>';
            } else {
                unpaidHTML = '<p style="text-align:center; color:#2E7D32; padding:15px;">&#10004; Semua keluarga sudah membayar!</p>';
            }

            let detailModal = document.getElementById('monthDetailModal');
            if (!detailModal) {
                detailModal = document.createElement('div');
                detailModal.id = 'monthDetailModal';
                detailModal.className = 'modal';
                document.body.appendChild(detailModal);
            }

            detailModal.innerHTML = `
                <div class="modal-content" style="max-width:900px;">
                    <div class="modal-header">
                        <h3>Detail Iuran - ${periodeLabel}</h3>
                        <button class="close" onclick="closeMonthDetailModal()">&times;</button>
                    </div>
                    <div class="modal-body" style="max-height:75vh; overflow-y:auto;">
                        ${summaryHTML}
                        <h4 style="color:#5a1111; margin-bottom:12px; padding-bottom:8px; border-bottom:2px solid rgba(90, 17, 17, 0.1); display: flex; align-items: center; gap: 8px;">
                            <span style="background:#5a1111; color:white; width:24px; height:24px; border-radius:50%; display:inline-flex; align-items:center; justify-content:center; font-size:12px;">&#10004;</span>
                            Sudah Dibayar <span style="font-weight:400; font-size:13px; margin-left:auto; opacity:0.6;">(${paidFamilies.length} KK)</span>
                        </h4>
                        ${paidHTML}
                        <h4 style="color:#8b7530; margin-top:25px; margin-bottom:12px; padding-bottom:8px; border-bottom:2px solid rgba(139, 117, 48, 0.1); display: flex; align-items: center; gap: 8px;">
                            <span style="background:#8b7530; color:white; width:24px; height:24px; border-radius:50%; display:inline-flex; align-items:center; justify-content:center; font-size:12px;">&#10008;</span>
                            Belum Dibayar <span style="font-weight:400; font-size:13px; margin-left:auto; opacity:0.6;">(${unpaidFamilies.length} KK)</span>
                        </h4>
                        ${unpaidHTML}
                    </div>
                </div>`;

            detailModal.style.display = 'block';
            if (window.initModalLenis) window.initModalLenis('monthDetailModal');
        }

        function closeMonthDetailModal() {
            if (window.modalLenis) {
                window.modalLenis.destroy();
                window.modalLenis = null;
            }
            document.getElementById('monthDetailModal').style.display = 'none';
            document.body.style.overflow = '';
            if (window.lenis) window.lenis.start();
        }



        window.onclick = function(e) {
            if (e.target.classList.contains('modal')) {
                e.target.style.display = 'none';
            }
        }
    </script>



    <script src="pagination.js?v=1"></script>
    <script src="navbar.js?v=6"></script>
    <script>
        document.addEventListener("DOMContentLoaded", () => {
            // ========== PAGINATION ==========
            initPagination({ tableId: 'iuranTable', tbodyId: 'iuranTableBody', containerId: 'iuranPagination', perPage: 10, onPageChange: calculateTotals });
            calculateTotals(); // Initial load

            // ========== SCROLL-TRIGGERED ANIMATIONS ==========
            gsap.registerPlugin(ScrollTrigger);

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

            // Grid-2 cards (iuran + kegiatan) — 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%'
                    }
                });
            });

            // Standalone cards (financial chart, jadwal misa, etc.) — fade up
            document.querySelectorAll('.container > .card').forEach(card => {
                gsap.from(card, {
                    y: 30,
                    opacity: 0,
                    duration: 0.8,
                    ease: 'power3.out',
                    scrollTrigger: {
                        trigger: card,
                        start: 'top 90%',
                        toggleActions: 'play none none none'
                    }
                });
            });

            // Ensure triggers are calculated after layout is stable
            setTimeout(() => {
                ScrollTrigger.refresh();
            }, 100);

            // 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%'
                }
            });

            // KUB stat items — stagger
            gsap.from('.kub-stat-item', {
                y: 30,
                opacity: 0,
                duration: 0.5,
                stagger: 0.08,
                ease: 'power3.out',
                scrollTrigger: {
                    trigger: '.kub-stat-item',
                    start: 'top 85%'
                }
            });

        });
    </script>
</body>

</html>
