<?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 pengurus (id_kub, nama_pengurus, jenis_pengurus, no_hp) 
                    VALUES (:id_kub, :nama_pengurus, :jenis_pengurus, :no_hp)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':id_kub' => $_POST['id_kub'] ?: null,
                ':nama_pengurus' => $_POST['nama_pengurus'],
                ':jenis_pengurus' => $_POST['jenis_pengurus'],
                ':no_hp' => $_POST['no_hp']
            ]);
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Data pengurus berhasil ditambahkan!'];
        } elseif ($action === 'update') {
            $sql = "UPDATE pengurus SET 
                    id_kub = :id_kub,
                    nama_pengurus = :nama_pengurus,
                    jenis_pengurus = :jenis_pengurus,
                    no_hp = :no_hp
                    WHERE id_pengurus = :id_pengurus";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':id_pengurus' => $_POST['id_pengurus'],
                ':id_kub' => $_POST['id_kub'] ?: null,
                ':nama_pengurus' => $_POST['nama_pengurus'],
                ':jenis_pengurus' => $_POST['jenis_pengurus'],
                ':no_hp' => $_POST['no_hp']
            ]);
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Data pengurus berhasil diupdate!'];
        } elseif ($action === 'delete') {
            $sql = "DELETE FROM pengurus WHERE id_pengurus = :id_pengurus";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([':id_pengurus' => $_POST['id_pengurus']]);
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Data pengurus berhasil dihapus!'];
        }
    } catch (PDOException $e) {
        $_SESSION['message'] = ['type' => 'error', 'text' => 'Error: ' . $e->getMessage()];
    }

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

// Query data
// Tabel gabungan: Menggabungkan tabel utama Pengurus dan relasinya terhadap (LEFT JOIN) tabel KUB agar informasi 'Nama KUB' nya terlampir, bukan sekadar relasi ID angkanya.
$sql = "
    SELECT 
        p.*,
        k.nama_kub
    FROM pengurus p
    LEFT JOIN kub k ON p.id_kub = k.id_kub
    ORDER BY k.nama_kub, p.nama_pengurus
";

/* Eksekusi query tabel pengurus gabungan */
$stmt = $pdo->query($sql);
$pengurus_list = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* Pemanggilan tabel master murni KUB untuk dimuat sebagai dropdown di formulir pengisian/edit */
$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>Pengurus KUB - 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);
            }
        }

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

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

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

        .pengurus-scroll-container::-webkit-scrollbar-thumb:hover {
            background: #b8860b;
        }
    </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 = 'pengurus.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 Pengurus KUB</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 nama pengurus..."
                            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>
                        <button class="btn btn-success" onclick="openModal('create')">+ Tambah Pengurus</button>
                    <?php endif; ?>
                </div>
            </div>
            <div class="print-header" id="printHeader"></div>
            <div class="table-wrapper">
                <table class="table" id="pengurusTable" style="margin-bottom: 0;">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Nama KUB</th>
                            <th>Nama Pengurus</th>
                            <th>Jenis Pengurus</th>
                            <th>No. HP</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="pengurusTableBody">
                        <!-- Memecah array pengurus_list hasil kueri menjadi elemen individu untuk dijejerkan ke dalam baris tabel UI -->
                        <?php $no = 1;
                        foreach ($pengurus_list as $p): ?>
                            <tr data-kub-id="<?= $p['id_kub'] ?>"
                                data-nama-kub="<?= htmlspecialchars($p['nama_kub'] ?? '') ?>"
                                data-bagian="<?= htmlspecialchars($p['jenis_pengurus']) ?>">
                                <td>
                                    <?= $no++ ?>
                                </td>
                                <td>
                                    <?php if (!empty($p['nama_kub'])): ?>
                                        <?= htmlspecialchars($p['nama_kub']) ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Belum dipilih</span>
                                    <?php endif; ?>
                                </td>
                                <td><strong>
                                        <?= htmlspecialchars($p['nama_pengurus']) ?>
                                    </strong></td>
                                <td>
                                    <?= htmlspecialchars($p['jenis_pengurus']) ?>
                                </td>
                                <td>
                                    <?php if (!empty($p['no_hp'])): ?>
                                        <?= htmlspecialchars($p['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 && hasRole(['admin_paroki', 'ketua_wilayah', 'ketua_kub'])): ?>
                                    <td class="no-print">
                                        <button class="btn btn-sm btn-warning"
                                            onclick='editPengurus(<?= json_encode($p) ?>)'>Edit</button>
                                        <button class="btn btn-sm btn-danger"
                                            onclick="deletePengurus(<?= $p['id_pengurus'] ?>, '<?= htmlspecialchars($p['nama_pengurus']) ?>')">Hapus</button>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <div class="pagination-container" id="pengurusPagination"></div>
        </div>
    </div>
    <div class="print-footer" id="printFooter"></div>
    </div>


    <!-- Modal CRUD -->
    <div id="pengurusModal" class="modal">
        <div class="modal-content" style="max-height: 90vh; display: flex; flex-direction: column;">
            <div class="modal-header">
                <h3 id="modalTitle">Tambah Pengurus</h3>
                <button class="close" onclick="closeModal()">&times;</button>
            </div>
            <form method="POST" style="display: flex; flex-direction: column; flex: 1; min-height: 0;">
                <div class="modal-body" style="overflow-y: auto; flex: 1;">
                    <input type="hidden" name="action" id="formAction" value="create">
                    <input type="hidden" name="id_pengurus" id="id_pengurus">

                    <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>Nama Pengurus *</label>
                        <input type="text" name="nama_pengurus" id="nama_pengurus" placeholder="Isi Nama Pengurus" required>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Jenis Pengurus *</label>
                            <select name="jenis_pengurus" id="jenis_pengurus" required>
                                <option value="">Pilih</option>
                                <option value="Liturgi">Liturgi</option>
                                <option value="Humas">Humas</option>
                                <option value="UsahaDana">UsahaDana</option>
                                <option value="Sekretaris">Sekretaris</option>
                                <option value="Penasehat">Penasehat</option>
                                <option value="Bendahara">Bendahara</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>No. HP *</label>
                            <input type="text" name="no_hp" id="no_hp" placeholder="Isi No. HP" required>
                        </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 Pengurus</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_pengurus" id="delete_id_pengurus">
                    <p>Yakin ingin menghapus pengurus <strong id="delete_nama"></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('pengurusModal').style.display = 'block';
            if (window.initModalLenis) window.initModalLenis('pengurusModal');
            
            if (action === 'create') {
                document.getElementById('modalTitle').innerText = 'Tambah Pengurus';
                document.getElementById('formAction').value = 'create';
                document.querySelector('#pengurusModal form').reset();
                document.getElementById('id_pengurus').value = '';
            }
        }

        function closeModal() {
            if (window.modalLenis) {
                window.modalLenis.destroy();
                window.modalLenis = null;
            }
            document.getElementById('pengurusModal').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 inject value dari tabel ke input form edit khusus data Pengurus/Dewan Pastoral */
        function editPengurus(pengurus) {
            openModal('edit');
            document.getElementById('modalTitle').innerText = 'Edit Pengurus';
            document.getElementById('formAction').value = 'update';
            document.getElementById('id_pengurus').value = pengurus.id_pengurus;
            document.getElementById('id_kub').value = pengurus.id_kub || '';
            document.getElementById('nama_pengurus').value = pengurus.nama_pengurus;
            document.getElementById('jenis_pengurus').value = pengurus.jenis_pengurus;
            document.getElementById('no_hp').value = pengurus.no_hp || '';
        }

        /* Fungsi interupsi via dialog konfirmasi saat tombol hapus pengurus ditekan */
        function deletePengurus(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_pengurus').value = id;
            document.getElementById('delete_nama').innerText = nama;
        }

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



        /* Fungsi compile seluruh data Pengurus menjadi arsip dokumen softcopy berbentuk Excel */
        async function confirmExportExcel() {
            document.getElementById('loadingOverlay').style.display = 'flex';
            try {
                var uniqueKUBs = new Set();
                var uniqueBagian = new Set();
                var lastVisibleKUBName = '';
                var lastVisibleBagian = '';
                document.querySelectorAll('#pengurusTable tbody tr').forEach(function(row) {
                    if (row.style.display !== 'none') {
                        var kubName = (row.cells[1] || {}).innerText || '';
                        var bagian  = (row.cells[3] || {}).innerText || '';
                        if (kubName) { uniqueKUBs.add(kubName); lastVisibleKUBName = kubName; }
                        if (bagian)  { uniqueBagian.add(bagian); lastVisibleBagian = bagian; }
                    }
                });
                var namaKUB = uniqueKUBs.size === 1 ? lastVisibleKUBName : '';
                var bagianCtx = uniqueBagian.size === 1 ? lastVisibleBagian : 'all';

                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 ws = workbook.addWorksheet('Pengurus KUB');

                ws.columns = [
                    { width: 6 }, { width: 22 }, { width: 30 },
                    { width: 20 }, { width: 16 }
                ];

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

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

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

                // === TANGGAL CETAK ===
                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 + ':E' + 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 + ':E' + tRow);
                ws.getCell('A' + tRow).value = 'DATA PENGURUS KUB' + (bagianCtx !== 'all' ? ' (' + bagianCtx.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 TABEL ===
                var headerRow = ws.addRow(['No', 'Nama KUB', 'Nama Pengurus', 'Jenis Pengurus', '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 ROWS ===
                var num = 1;
                document.querySelectorAll('#pengurusTable tbody tr').forEach(function(row) {
                    if (row.style.display !== 'none') {
                        var c = row.cells;
                        if (c && c.length >= 5) {
                            var dr = ws.addRow([num++, c[1].innerText.trim(), c[2].innerText.trim(), c[3].innerText.trim(), c[4].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' };
                            });
                        }
                    }
                });

                // === SIMPAN ===
                var dateFile = now.toISOString().split('T')[0];
                var kubFile = namaKUB ? namaKUB.replace(/\s+/g, '_') : 'Wilayah_IV';
                var bagianFile = bagianCtx !== 'all' ? '_' + bagianCtx.replace(/\s+/g, '_') : '';
                var buffer = await workbook.xlsx.writeBuffer();
                saveAs(new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), 'Pengurus_' + kubFile + bagianFile + '_' + 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 formatting layar agar susunan tabel Pengurus KUB selaras saat masuk mesin Printer */
        async function confirmPrint() {
            let uniqueKUBs = new Set();
            let uniqueBagian = new Set();
            let lastVisibleKUBName = '';
            let lastVisibleBagian = '';
            document.querySelectorAll('#pengurusTable tbody tr').forEach(row => {
                if (row.style.display !== 'none') {
                    const kubName = row.cells[1].innerText;
                    const bagian = row.cells[3].innerText;
                    if (kubName) { uniqueKUBs.add(kubName); lastVisibleKUBName = kubName; }
                    if (bagian) { uniqueBagian.add(bagian); lastVisibleBagian = bagian; }
                }
            });
            const namaKUB = uniqueKUBs.size === 1 ? lastVisibleKUBName : '';
            const bagian = uniqueBagian.size === 1 ? lastVisibleBagian : 'all';

            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('#pengurusTable 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>
                    </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 PENGURUS${bagian !== 'all' ? ` (${bagian.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;">Nama KUB</th>
                            <th style="border:1px solid #000; padding:6px;">Nama Pengurus</th>
                            <th style="border:1px solid #000; padding:6px;">Jenis Pengurus</th>
                            <th style="border:1px solid #000; padding:6px;">No. HP</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();
        };

        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: 'pengurusTable', tbodyId: 'pengurusTableBody', containerId: 'pengurusPagination', 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, 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>
