<?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) : '';
require_once 'auth_helper.php';

$current_user_id = $_SESSION['user_id'] ?? null;
$current_role = $_SESSION['role'] ?? null;
$is_admin = hasRole(['admin_paroki', 'ketua_wilayah', 'ketua_kub']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireLogin();

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

    try {
        if ($action === 'create') {
            $sql = "INSERT INTO kartu_keluarga (nama_kepala_keluarga, id_kub, alamat, jumlah_jiwa, jumlah_iuran_bulanan, no_hp, created_by_user_id) 
                    VALUES (:nama_kepala_keluarga, :id_kub, :alamat, :jumlah_jiwa, :jumlah_iuran_bulanan, :no_hp, :user_id)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':nama_kepala_keluarga' => $_POST['nama_kepala_keluarga'] ?: null,
                ':id_kub' => $_POST['id_kub'] ?: null,
                ':alamat' => $_POST['alamat'],
                ':jumlah_jiwa' => $_POST['jumlah_jiwa'] ?: 0,
                ':jumlah_iuran_bulanan' => $_POST['jumlah_iuran_bulanan'] ?: 0,
                ':no_hp' => $_POST['no_hp'],
                ':user_id' => $_SESSION['user_id']
            ]);
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Data kartu keluarga berhasil ditambahkan!'];
        } elseif ($action === 'update' || $action === 'delete') {
            $id_kk = $_POST['id_kk'];

            if (!$is_admin) {
                $check = $pdo->prepare("SELECT created_by_user_id FROM kartu_keluarga WHERE id_kk = :id");
                $check->execute([':id' => $id_kk]);
                $kk_owner = $check->fetchColumn();

                if ($kk_owner != $_SESSION['user_id']) {
                    // Deny Access silently or set error
                    $_SESSION['message'] = ['type' => 'error', 'text' => 'Anda tidak memiliki izin untuk mengubah data ini!'];
                    header('Location: kartu_keluarga.php');
                    exit;
                }
            }

            if ($action === 'update') {
                $sql = "UPDATE kartu_keluarga SET 
                        nama_kepala_keluarga = :nama_kepala_keluarga,
                        id_kub = :id_kub,
                        alamat = :alamat,
                        jumlah_jiwa = :jumlah_jiwa,
                        jumlah_iuran_bulanan = :jumlah_iuran_bulanan,
                        no_hp = :no_hp
                        WHERE id_kk = :id_kk";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([
                    ':id_kk' => $_POST['id_kk'],
                    ':nama_kepala_keluarga' => $_POST['nama_kepala_keluarga'] ?: null,
                    ':id_kub' => $_POST['id_kub'] ?: null,
                    ':alamat' => $_POST['alamat'],
                    ':jumlah_jiwa' => $_POST['jumlah_jiwa'] ?: 0,
                    ':jumlah_iuran_bulanan' => $_POST['jumlah_iuran_bulanan'] ?: 0,
                    ':no_hp' => $_POST['no_hp']
                ]);
                $_SESSION['message'] = ['type' => 'success', 'text' => 'Data kartu keluarga berhasil diupdate!'];
            } elseif ($action === 'delete') {
                $sql = "DELETE FROM kartu_keluarga WHERE id_kk = :id_kk";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([':id_kk' => $_POST['id_kk']]);
                $_SESSION['message'] = ['type' => 'success', 'text' => 'Data kartu keluarga berhasil dihapus!'];
            }
        }
    } catch (PDOException $e) {
        $_SESSION['message'] = ['type' => 'error', 'text' => 'Error: ' . $e->getMessage()];
    }

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

// Query data kartu keluarga
/* Tabel Utama Kartu Keluarga: Menggunakan teknik LEFT JOIN ke sub-data master KUB, sehingga antarmuka pengguna dapat menatap tulisan nama fungsional KUB nya secara manusiawi, alih-alih cuma disodori angka id_kub acak di layarnya. */
$sql = "
    SELECT 
        kk.*,
        k.nama_kub
    FROM kartu_keluarga kk
    LEFT JOIN kub k ON kk.id_kub = k.id_kub
    ORDER BY kk.id_kk
";

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

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

// Define wilayah data (placeholder/default)
$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>Kartu Keluarga - 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>
        /* 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);
        }

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

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

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

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

        .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 = 'kartu_keluarga.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 Kartu Keluarga</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 Kartu Keluarga..." 
                        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 (isset($_SESSION['user_id'])): ?>
                    <button class="btn" onclick="openModal('create')">+ Tambah Kartu Keluarga</button>
                <?php else: ?>
                    <a href="login.php" class="btn" style="text-decoration:none;">+ Tambah Kartu Keluarga</a>
                <?php endif; ?>
            </div>
            </div>
            <div class="print-header" id="printHeader"></div>
            <div class="table-wrapper">
                <table class="table" id="kkTable" style="margin-bottom: 0;">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Nama Kepala Keluarga</th>
                            <th>KUB</th>
                            <th>Alamat</th>
                            <th>Jumlah Jiwa</th>
                            <th>Jumlah Iuran</th>
                            <th>No. HP</th>

                            <?php if ($is_logged_in): ?>
                                <th class="no-print">Aksi</th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody id="kkTableBody">
                        <!-- Instansiasi visual: Membongkar isi kueri KK per item ke dalam komponen sel (td) tabel HTML pengguna -->
                        <?php $no = 1;
                        foreach ($kk_list as $kk):
                            $row_class = '';
                            // Check if user is 'anggota_kub' and owns this record
                            if (
                                isset($_SESSION['role']) && $_SESSION['role'] === 'anggota_kub' &&
                                isset($kk['created_by_user_id']) && $kk['created_by_user_id'] == $_SESSION['user_id']
                            ) {
                                $row_class = 'user-owned-row';
                            }
                            ?>
                            <tr class="<?= $row_class ?>" data-kub-id="<?= $kk['id_kub'] ?>"
                                data-nama-kub="<?= htmlspecialchars($kk['nama_kub'] ?? '') ?>">
                                <td>
                                    <?= $no++ ?>
                                </td>
                                <td><strong>
                                    <?php if (!empty($kk['nama_kepala_keluarga'])): ?>
                                        <?= htmlspecialchars($kk['nama_kepala_keluarga']) ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Belum diisi</span>
                                    <?php endif; ?>
                                </strong></td>
                                <td>
                                    <?php if (!empty($kk['nama_kub'])): ?>
                                        <?= htmlspecialchars($kk['nama_kub']) ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Belum dipilih</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if (!empty($kk['alamat'])): ?>
                                        <?= htmlspecialchars($kk['alamat']) ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Belum diisi</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?= htmlspecialchars($kk['jumlah_jiwa'] ?? 0) ?>
                                </td>
                                <td>
                                    Rp <?= number_format($kk['jumlah_iuran_bulanan'] ?? 0, 0, ',', '.') ?>
                                </td>
                                <td>
                                    <?php if (!empty($kk['no_hp'])): ?>
                                        <?= htmlspecialchars($kk['no_hp']) ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Belum diisi</span>
                                    <?php endif; ?>
                                </td>

                                <?php if ($is_logged_in): ?>
                                    <td class="no-print">
                                        <?php if ($is_admin || (isset($kk['created_by_user_id']) && $kk['created_by_user_id'] == $_SESSION['user_id'])): ?>
                                            <button class="btn btn-sm btn-warning" onclick='editKK(<?= htmlspecialchars(json_encode($kk), ENT_QUOTES) ?>)'>Edit</button>
                                            <button class="btn btn-sm btn-danger" onclick="deleteKK(<?= $kk['id_kk'] ?>, '<?= htmlspecialchars($kk['nama_kepala_keluarga'] ?? '-', ENT_QUOTES) ?>')">Hapus</button>
                                        <?php else: ?>
                                            <span style="color: var(--text-muted); font-size: 0.85em; font-style: italic;">Tidak ada akses</span>
                                        <?php endif; ?>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <div class="pagination-container" id="kkPagination"></div>
        </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>



    <!-- Modal CRUD -->
    <div id="kkModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">Tambah Kartu Keluarga</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_kk" id="id_kk">



                    <div class="form-group">
                        <label>Nama Kepala Keluarga *</label>
                        <input type="text" name="nama_kepala_keluarga" id="nama_kepala_keluarga" required placeholder="Isi Nama Kepala Keluarga" required>
                    </div>

                    <div class="form-group">
                        <label>KUB *</label>
                        <select name="id_kub" id="id_kub" required>
                            <option value="">Pilih KUB</option>
                            <?php foreach ($kub_list as $kub): ?>
                                <option value="<?= $kub['id_kub'] ?>">
                                    <?= htmlspecialchars($kub['nama_kub']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Alamat *</label>
                        <textarea name="alamat" id="alamat" rows="3" placeholder="Isi Alamat" required></textarea>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Jumlah Jiwa *</label>
                            <input type="number" name="jumlah_jiwa" id="jumlah_jiwa" min="0" placeholder="Isi jumlah jiwa" required>
                        </div>
                        <div class="form-group">
                            <label>Jumlah Iuran Bulanan (Rp) *</label>
                            <input type="number" name="jumlah_iuran_bulanan" id="jumlah_iuran_bulanan" min="0" placeholder="Contoh isi 10000" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>No. HP</label>
                        <input type="text" name="no_hp" id="no_hp" placeholder="Isi No. HP">
                    </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 Kartu Keluarga</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_kk" id="delete_id_kk">
                    <p>Yakin ingin menghapus kartu keluarga <strong id="delete_nama_kk"></strong>?</p>
                    <p style="color: #991b1b; font-size: 12px; margin-top: 10px;">⚠️ Data anggota keluarga juga akan
                        terhapus!</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('kkModal').style.display = 'block';
            if (window.initModalLenis) window.initModalLenis('kkModal');

            if (action === 'create') {
                document.getElementById('modalTitle').innerText = 'Tambah Kartu Keluarga';
                document.getElementById('formAction').value = 'create';
                document.querySelector('#kkModal form').reset();
                document.getElementById('id_kk').value = '';
            }
        }

        function closeModal() {
            if (window.modalLenis) {
                window.modalLenis.destroy();
                window.modalLenis = null;
            }
            document.getElementById('kkModal').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 mengisi otomatis seluruh kolom form modal saat mode ganti data (Edit KK) */
        function editKK(kk) {
            openModal('edit');
            document.getElementById('modalTitle').innerText = 'Edit Kartu Keluarga';
            document.getElementById('formAction').value = 'update';
            document.getElementById('id_kk').value = kk.id_kk;
            document.getElementById('nama_kepala_keluarga').value = kk.nama_kepala_keluarga || '';
            document.getElementById('id_kub').value = kk.id_kub || '';
            document.getElementById('alamat').value = kk.alamat || '';
            document.getElementById('jumlah_jiwa').value = kk.jumlah_jiwa || '';
            document.getElementById('jumlah_iuran_bulanan').value = kk.jumlah_iuran_bulanan || '';
            document.getElementById('no_hp').value = kk.no_hp || '';

        }

        /* Fungsi validasi konfirmasi sebelum me-remove data KK dari database */
        function deleteKK(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_kk').value = id;
            document.getElementById('delete_nama_kk').innerText = nama;
        }

        function searchTable() {
            const filter = document.getElementById('searchBox').value.toUpperCase();
            if (window.kkPaginationPaginator) {
                window.kkPaginationPaginator.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;
                });
            }
        }

        // 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 generator worksheet Excel standar rekap Data KK Lengkap */
        async function confirmExportExcel() {
            document.getElementById('loadingOverlay').style.display = 'flex';
            try {
                // Determine KUB context from visible rows
                var uniqueKUBs = new Set();
                var lastVisibleKUBName = '';
                document.querySelectorAll('#kkTable tbody tr').forEach(function(row) {
                    if (row.style.display !== 'none') {
                        var kubName = row.getAttribute('data-nama-kub');
                        if (kubName) {
                            uniqueKUBs.add(kubName);
                            lastVisibleKUBName = kubName;
                        }
                    }
                });
                var namaKUB = uniqueKUBs.size === 1 ? lastVisibleKUBName : '';

                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 Kartu Keluarga');

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

                // === KOP SURAT ===
                ws.mergeCells('A1:G1');
                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:G2');
                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:G3');
                    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 <= 7; col++) {
                    ws.getRow(kopLastRow).getCell(col).border = {
                        bottom: { style: 'double', color: { argb: 'FF000000' } }
                    };
                }

                if (base64Logo) {
                    var imageId = workbook.addImage({ base64: base64Logo, extension: 'png' });
                    // Ukuran logo dinamis: 62px jika 3 baris (KUB spesifik), 40px 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 + ':G' + 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 + ':G' + tRow);
                ws.getCell('A' + tRow).value = 'DATA KARTU KELUARGA';
                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', 'Nama Kepala Keluarga', 'KUB', 'Alamat', 'Jumlah Jiwa', 'Jumlah Iuran', 'No. HP']);
                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;
                document.querySelectorAll('#kkTable tbody tr').forEach(function(row) {
                    if (row.style.display !== 'none') {
                        var c = row.cells;
                        if (c && c.length >= 7) {
                            var dr = ws.addRow([num++, c[1].innerText.trim(), c[2].innerText.trim(), c[3].innerText.trim(), c[4].innerText.trim(), c[5].innerText.trim(), c[6].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 };
                                if (colNumber === 1) cell.alignment = { horizontal: 'center' };
                            });
                        }
                    }
                });

                var dateFile = now.toISOString().split('T')[0];
                var kubNameFile = namaKUB ? namaKUB.replace(/\s+/g, '_') : 'Wilayah_IV';
                var buffer = await workbook.xlsx.writeBuffer();
                saveAs(new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), 'KK_' + kubNameFile + '_' + 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 merender ulang tabel Data Ummat (KK) ke tata letak yang ramah cetak (Print mode) */
        async function confirmPrint() {
            let uniqueKUBs = new Set();
            let lastVisibleKUBName = '';
            document.querySelectorAll('#kkTable tbody tr').forEach(row => {
                if (row.style.display !== 'none') {
                    const kubName = row.getAttribute('data-nama-kub');
                    if (kubName) {
                        uniqueKUBs.add(kubName);
                        lastVisibleKUBName = kubName;
                    }
                }
            });
            const namaKUB = uniqueKUBs.size === 1 ? lastVisibleKUBName : '';

            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('#kkTable 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[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>
                    </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 KARTU KELUARGA</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 Kepala Keluarga</th>
                            <th style="border:1px solid #000; padding:6px;">KUB</th>
                            <th style="border:1px solid #000; padding:6px;">Alamat</th>
                            <th style="border:1px solid #000; padding:6px;">Jumlah Jiwa</th>
                            <th style="border:1px solid #000; padding:6px;">Jumlah Iuran</th>
                            <th style="border:1px solid #000; padding:6px;">No. HP</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 () {
            const overlay = document.getElementById('tempPrintOverlay');
            if (overlay) overlay.remove();
            const style = document.getElementById('tempPrintStyle');
            if (style) style.remove();
        };
    </script>

    <script src="pagination.js?v=1"></script>
    <script src="navbar.js?v=6"></script>
    <script>
        document.addEventListener("DOMContentLoaded", () => {
            // ========== PAGINATION ==========
            initPagination({ tableId: 'kkTable', tbodyId: 'kkTableBody', containerId: 'kkPagination', perPage: 10 });
            // ========== 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 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>
