<?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') {
    $action = $_POST['action'] ?? '';

    try {
        if ($action === 'create') {
            $sql = "INSERT INTO kub (nama_kub, kelurahan, ketua, no_hp) 
                    VALUES (:nama_kub, :kelurahan, :ketua, :no_hp)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':nama_kub' => $_POST['nama_kub'],
                ':kelurahan' => $_POST['kelurahan'],
                ':ketua' => $_POST['ketua'],
                ':no_hp' => $_POST['no_hp']
            ]);
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Data KUB berhasil ditambahkan!'];
        } elseif ($action === 'update') {
            $sql = "UPDATE kub SET 
                    nama_kub = :nama_kub,
                    kelurahan = :kelurahan,
                    ketua = :ketua,
                    no_hp = :no_hp
                    WHERE id_kub = :id_kub";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':id_kub' => $_POST['id_kub'],
                ':nama_kub' => $_POST['nama_kub'],
                ':kelurahan' => $_POST['kelurahan'],
                ':ketua' => $_POST['ketua'],
                ':no_hp' => $_POST['no_hp']
            ]);
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Data KUB berhasil diupdate!'];
        } elseif ($action === 'delete') {
            $sql = "DELETE FROM kub WHERE id_kub = :id_kub";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([':id_kub' => $_POST['id_kub']]);
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Data KUB berhasil dihapus!'];
        }
    } catch (PDOException $e) {
        $_SESSION['message'] = ['type' => 'error', 'text' => 'Error: ' . $e->getMessage()];
    }

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

// Query data
/* Tabel Analitik Sentral KUB: Bukan sekadar me-load daftar nama KUB, ini menggunakan perhitungan ganda (COUNT DISTINCT KK & Sub-query COUNT list pengurus) agar di baris informasinya langsung memampang statistik kepengurusan di tiap unit bloknya! */
$sql = "
    SELECT 
        k.*,
        COUNT(DISTINCT kk.id_kk) as total_kk,
        COALESCE(SUM(kk.jumlah_jiwa), 0) as total_jiwa,
        (SELECT COUNT(*) FROM pengurus p WHERE p.id_kub = k.id_kub) as total_pengurus
    FROM kub k
    LEFT JOIN kartu_keluarga kk ON k.id_kub = kk.id_kub
    GROUP BY k.id_kub 
    ORDER BY k.nama_kub
";

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

// Define wilayah data (placeholder/default if not in DB)
$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>Data KUB - Wilayah IV 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,
        .btn-danger {
            background-color: #800000 !important;
            /* Maroon */
            border-color: #800000 !important;
            color: #ffffff !important;
        }

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

        .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);
        }

        .card .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;
        }

        .card .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);
        }

        /* 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>
    <div id="loadingOverlay">
        <div class="spinner"></div>
        <p style="margin-top:10px; font-weight:bold;">Sedang mendownload file excel...</p>
    </div>

    <img src="logo1.jpg" id="logoExport" style="display:none;" crossorigin="anonymous">

    <?php $active_page = 'kub.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; ?>

        <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 Kelompok Umat Basis (KUB)</h2>
                <div class="header-actions">
                    <?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>
                        <button class="btn" onclick="openModal('create')">+ Tambah KUB</button>
                    <?php endif; ?>
                </div>
            </div>
            <div class="print-header" id="printHeader"></div>

            <div class="table-wrapper kub-scroll-container" data-lenis-prevent="true" style="max-height: 500px; overflow-y: auto;">
                <table class="table" id="kubTable">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Nama KUB</th>
                            <th>Ketua KUB</th>
                            <th>No. HP</th>
                            <th>Kelurahan</th>
                            <th>Jumlah KK</th>
                            <th>Jumlah Jiwa</th>
                            <th>Pengurus</th>
                            <?php if ($is_logged_in && hasRole(['admin_paroki', 'ketua_wilayah', 'ketua_kub'])): ?>
                                <th class="no-print">Aksi</th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <!-- Rendering data dinamis: Menjalankan rotasi tiap unit Data KUB untuk memetakan nama wilayah beserta statistiknya ke dalam list antarmuka -->
                        <?php $no = 1;
                        foreach ($kub_list as $kub): ?>
                            <tr data-kub-id="<?= $kub['id_kub'] ?>"
                                data-kub-name="<?= htmlspecialchars($kub['nama_kub']) ?>"
                                data-ketua="<?= htmlspecialchars($kub['ketua'] ?? '') ?>">
                                <td>
                                    <?= $no++ ?>
                                </td>
                                <td><strong>
                                        <?= htmlspecialchars($kub['nama_kub']) ?>
                                    </strong></td>
                                <td>
                                    <?php if (!empty($kub['ketua'])): ?>
                                        <?= htmlspecialchars($kub['ketua']) ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Belum ada ketua</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if (!empty($kub['no_hp'])): ?>
                                        <?= htmlspecialchars($kub['no_hp']) ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Belum diisi</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if (!empty($kub['kelurahan'])): ?>
                                        <?= htmlspecialchars($kub['kelurahan']) ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Belum diisi</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?= $kub['total_kk'] ?> KK
                                </td>
                                <td>
                                    <?= $kub['total_jiwa'] ?> jiwa
                                </td>
                                <td>
                                    <?= $kub['total_pengurus'] ?> orang
                                </td>
                                <?php if ($is_logged_in && hasRole(['admin_paroki', 'ketua_wilayah', 'ketua_kub'])): ?>
                                    <td class="no-print">
                                        <button class="btn btn-sm btn-warning"
                                            onclick='editKub(<?= json_encode($kub) ?>)'>Edit</button>
                                        <button class="btn btn-sm btn-danger"
                                            onclick="deleteKub(<?= $kub['id_kub'] ?>, '<?= htmlspecialchars($kub['nama_kub']) ?>')">Hapus</button>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <div class="print-footer" id="printFooter"></div>
        </div>
    </div>

    <div id="pdfRenderContainer" style="position: absolute; left: -9999px; top: 0; width: 1050px; background: white;">
    </div>


    <div id="kubModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">Edit KUB</h3><button class="close" onclick="closeModal()">&times;</button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" id="formAction" value="create">
                    <input type="hidden" name="id_kub" id="id_kub">
                    <div class="form-group"><label>Nama KUB *</label><input type="text" name="nama_kub" id="nama_kub"
                            placeholder="Isi Nama KUB" required></div>
                    <!-- <div class="form-group">
                        <label>Wilayah *</label>
                        <select name="id_wilayah" id="id_wilayah" required>
                            <?php foreach ($wilayah_options as $w_opt): ?>
                                <option value="<?= $w_opt['id_wilayah'] ?>">
                                    <?= htmlspecialchars($w_opt['nama_wilayah']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div> -->
                    <div class="form-row">
                        <div class="form-group"><label>Kelurahan *</label><input type="text" name="kelurahan"
                                id="kelurahan" placeholder="Isi Kelurahan" required></div>
                    </div>
                    <div class="form-row">
                        <div class="form-group"><label>Ketua KUB *</label><input type="text" name="ketua" id="ketua" placeholder="Isi Ketua KUB" required></div>
                        <div class="form-group"><label>No. HP Ketua KUB</label><input type="text" name="no_hp" id="no_hp" placeholder="Isi No. HP Ketua KUB">
                        </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>

    <div id="deleteModal" class="modal">
        <div class="modal-content" style="max-width: 400px;">
            <div class="modal-header">
                <h3>Hapus KUB</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_kub" id="delete_id_kub">
                    <p>Yakin ingin menghapus KUB <strong id="delete_nama_kub"></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>

    <script>
        const wilayahData = <?= json_encode($wilayah) ?>;

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

            if (action === 'create') {
                document.getElementById('modalTitle').innerText = 'Tambah KUB';
                document.getElementById('formAction').value = 'create';
                // Reset form agar inputan kosong saat tambah data baru
                document.querySelector('#kubModal form').reset();
                document.getElementById('id_kub').value = '';
            }
        }

        function closeModal() {
            if (window.modalLenis) {
                window.modalLenis.destroy();
                window.modalLenis = null;
            }
            document.getElementById('kubModal').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();
        }

        /* Fungsi untuk memunculkan konfirmasi penghapusan data KUB secara aman */
        function deleteKub(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_kub').value = id;
            document.getElementById('delete_nama_kub').innerText = nama;
        }

        /* Fungsi untuk menarik data spesifik KUB ke form edit agar siap diperbarui */
        function editKub(kub) {
            // 1. Tampilkan Modal
            openModal('edit');

            // 2. Ubah Judul & Action
            document.getElementById('modalTitle').innerText = 'Edit KUB';
            document.getElementById('formAction').value = 'update';

            // 3. Isi Data (Gunakan ID yang sesuai dengan atribut name di form)
            document.getElementById('id_kub').value = kub.id_kub;
            document.getElementById('nama_kub').value = kub.nama_kub;
            document.getElementById('kelurahan').value = kub.kelurahan;
            document.getElementById('ketua').value = kub.ketua;
            document.getElementById('no_hp').value = kub.no_hp;

            // Tambahkan pengecekan untuk id_wilayah karena di HTML Anda sedang di-comment
            const wilayahElem = document.getElementById('id_wilayah');
            if (wilayahElem) {
                wilayahElem.value = kub.id_wilayah;
            }
        }

        // Helper: Convert Image URL to Base64 (Untuk mencegah PDF Kosong/Logo Hilang)
        function getBase64Image(imgElement) {
            return new Promise((resolve) => {
                const canvas = document.createElement("canvas");
                canvas.width = imgElement.naturalWidth;
                canvas.height = imgElement.naturalHeight;
                const ctx = canvas.getContext("2d");
                ctx.drawImage(imgElement, 0, 0);
                resolve(canvas.toDataURL("image/jpeg"));
            });
        }

        /* Fungsi mendownload serta mengatur layout data tabel KUB ke format Microsoft Excel */
        async function confirmExportExcel() {
            document.getElementById('loadingOverlay').style.display = 'flex';
            try {
                var logoImg = document.getElementById('logoExport');
                var base64Logo = '';
                if (logoImg && logoImg.naturalWidth > 0) {
                    var cvs = document.createElement('canvas');
                    cvs.width = logoImg.naturalWidth;
                    cvs.height = logoImg.naturalHeight;
                    cvs.getContext('2d').drawImage(logoImg, 0, 0);
                    base64Logo = cvs.toDataURL('image/png');
                }

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

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

                // === KOP SURAT ===
                ws.mergeCells('A1:H1');
                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:H2');
                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;

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

                if (base64Logo) {
                    var imageId = workbook.addImage({ base64: base64Logo, extension: 'png' });
                    // Ukuran logo fix 40px karena Kop Surat kub.php statis 2 baris
                    // Digunakan pecahan (0.1) untuk memberi jarak spasi/padding aman dari tepi margin
                    var logoSize = 40;
                    ws.addImage(imageId, { 
                        tl: { col: 0.1, row: 0.1 }, 
                        ext: { width: logoSize, height: logoSize } 
                    });
                }

                ws.getRow(3).height = 8;

                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('A4:H4');
                ws.getCell('A4').value = printStr;
                ws.getCell('A4').font = { italic: true, size: 9 };
                ws.getCell('A4').alignment = { horizontal: 'right' };

                ws.mergeCells('A5:H5');
                ws.getCell('A5').value = 'DATA KELOMPOK UMAT BASIS (KUB)';
                ws.getCell('A5').font = { size: 14, bold: true, underline: true };
                ws.getCell('A5').alignment = { horizontal: 'center' };
                ws.getRow(6).height = 8;

                var headerRow = ws.addRow(['No', 'Nama KUB', 'Ketua KUB', 'No. HP', 'Kelurahan', 'KK', 'Jiwa', 'Pengurus']);
                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' } };
                });

                var num = 1;
                document.querySelectorAll('#tableBody tr').forEach(function(row) {
                    if (row.style.display !== 'none') {
                        var c = row.cells;
                        if (c && c.length >= 8) {
                            var dr = ws.addRow([num++, c[1].innerText.trim(), c[2].innerText.trim(), c[3].innerText.trim(), c[4].innerText.trim(), c[5].innerText.replace(' KK','').trim(), c[6].innerText.replace(' jiwa','').trim(), c[7].innerText.replace(' orang','').trim()]);
                            dr.eachCell(function(cell, colNumber) {
                                cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } };
                                cell.font = { size: 10 };
                                if (colNumber === 1 || colNumber === 6 || colNumber === 7 || colNumber === 8) cell.alignment = { horizontal: 'center' };
                            });
                        }
                    }
                });

                var dateFile = now.toISOString().split('T')[0];
                var buffer = await workbook.xlsx.writeBuffer();
                saveAs(new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), 'KUB_Wilayah_IV_' + 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 memanipulasi DOM sejenak guna merapikan tampilan cetak (Print) tabel KUB */
        async function confirmPrint() {
            const logoImg = document.getElementById('logoExport');
            let base64Logo = "";
            if (logoImg) {
                const canvas = document.createElement("canvas");
                canvas.width = logoImg.naturalWidth;
                canvas.height = logoImg.naturalHeight;
                const ctx = canvas.getContext("2d");
                ctx.drawImage(logoImg, 0, 0);
                base64Logo = canvas.toDataURL("image/jpeg");
            }

            // Build table rows from visible data
            let tableRows = '';
            let num = 1;
            document.querySelectorAll('#tableBody tr').forEach(row => {
                if (!row.style.display || 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[3].innerText}</td>
                        <td style="border:1px solid #000; padding:6px;">${c[4].innerText}</td>
                        <td style="border:1px solid #000; padding:6px;">${c[5].innerText}</td>
                        <td style="border:1px solid #000; padding:6px;">${c[6].innerText}</td>
                        <td style="border:1px solid #000; padding:6px;">${c[7].innerText}</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>
                    </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 KELOMPOK UMAT BASIS (KUB)</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;">Nama KUB</th>
                            <th style="border:1px solid #000; padding:6px;">Ketua KUB</th>
                            <th style="border:1px solid #000; padding:6px;">No. HP</th>
                            <th style="border:1px solid #000; padding:6px;">Kelurahan</th>
                            <th style="border:1px solid #000; padding:6px;">Jumlah KK</th>
                            <th style="border:1px solid #000; padding:6px;">Jumlah Jiwa</th>
                            <th style="border:1px solid #000; padding:6px;">Pengurus</th>
                        </tr>
                    </thead>
                    <tbody>${tableRows}</tbody>
                </table>
            </div>`;

            // Inject print style that hides EVERYTHING else
            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.onclick = function(e) {
            if (e.target.classList.contains('modal')) e.target.style.display = 'none';
        }
        window.onafterprint = function() {
            // Clean up overlay and style
            const overlay = document.getElementById('tempPrintOverlay');
            if (overlay) overlay.remove();
            const style = document.getElementById('tempPrintStyle');
            if (style) style.remove();
        };
    </script>

    <script src="navbar.js?v=6"></script>
    <script>
        document.addEventListener("DOMContentLoaded", () => {
            // ========== 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: 50,
                    opacity: 0,
                    duration: 0.8,
                    ease: 'power3.out',
                    scrollTrigger: {
                        trigger: card,
                        start: 'top 80%'
                    }
                });
            });

            // 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>
    <script src="navbar.js?v=6"></script>
</body>

</html>
