<?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') {
            $butuh_persetujuan = $_POST['butuh_persetujuan_paroki'] ?? 'tidak';
            $id_pastor = ($butuh_persetujuan === 'iya') ? ($_POST['id_pastor'] ?: null) : null;
            $status = ($butuh_persetujuan === 'iya') ? 'ditahan' : '-';

            $sql = "INSERT INTO kegiatan (nama_kegiatan, id_kub, jenis_kegiatan, waktu_tanggal, tempat, pengurus_terlibat, keterangan, dana, butuh_persetujuan_paroki, id_pastor, status) 
                    VALUES (:nama_kegiatan, :id_kub, :jenis_kegiatan, :waktu_tanggal, :tempat, :pengurus_terlibat, :keterangan, :dana, :butuh_persetujuan_paroki, :id_pastor, :status)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':nama_kegiatan' => $_POST['nama_kegiatan'],
                ':id_kub' => ($_POST['id_kub'] && $_POST['id_kub'] !== 'semua') ? $_POST['id_kub'] : null,
                ':jenis_kegiatan' => $_POST['jenis_kegiatan'],
                ':waktu_tanggal' => $_POST['waktu_tanggal'],
                ':tempat' => $_POST['tempat'],
                ':pengurus_terlibat' => isset($_POST['pengurus_terlibat']) ? implode(', ', (array)$_POST['pengurus_terlibat']) : null,
                ':keterangan' => $_POST['keterangan'],
                ':dana' => $_POST['dana'] ?: 0,
                ':butuh_persetujuan_paroki' => $butuh_persetujuan,
                ':id_pastor' => $id_pastor,
                ':status' => $status
            ]);
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Data kegiatan berhasil ditambahkan!'];
        } elseif ($action === 'update') {
            $butuh_persetujuan = $_POST['butuh_persetujuan_paroki'] ?? 'tidak';
            $id_pastor = ($butuh_persetujuan === 'iya') ? ($_POST['id_pastor'] ?: null) : null;
            
            $status = $_POST['status'] ?? '-';
            if ($butuh_persetujuan === 'tidak') {
                $status = '-';
            } elseif ($butuh_persetujuan === 'iya' && $status === '-') {
                $status = 'ditahan';
            }

            $sql = "UPDATE kegiatan SET 
                    nama_kegiatan = :nama_kegiatan,
                    id_kub = :id_kub,
                    jenis_kegiatan = :jenis_kegiatan,
                    waktu_tanggal = :waktu_tanggal,
                    tempat = :tempat,
                    pengurus_terlibat = :pengurus_terlibat,
                    keterangan = :keterangan,
                    dana = :dana,
                    butuh_persetujuan_paroki = :butuh_persetujuan_paroki,
                    id_pastor = :id_pastor,
                    status = :status
                    WHERE id_kegiatan = :id_kegiatan";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':id_kegiatan' => $_POST['id_kegiatan'],
                ':nama_kegiatan' => $_POST['nama_kegiatan'],
                ':id_kub' => ($_POST['id_kub'] && $_POST['id_kub'] !== 'semua') ? $_POST['id_kub'] : null,
                ':jenis_kegiatan' => $_POST['jenis_kegiatan'],
                ':waktu_tanggal' => $_POST['waktu_tanggal'],
                ':tempat' => $_POST['tempat'],
                ':pengurus_terlibat' => isset($_POST['pengurus_terlibat']) ? implode(', ', (array)$_POST['pengurus_terlibat']) : null,
                ':keterangan' => $_POST['keterangan'],
                ':dana' => $_POST['dana'] ?: 0,
                ':butuh_persetujuan_paroki' => $butuh_persetujuan,
                ':id_pastor' => $id_pastor,
                ':status' => $status
            ]);
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Data kegiatan berhasil diupdate!'];
        } elseif ($action === 'delete') {
            $sql = "DELETE FROM kegiatan WHERE id_kegiatan = :id_kegiatan";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([':id_kegiatan' => $_POST['id_kegiatan']]);
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Data kegiatan berhasil dihapus!'];
        }
    } catch (PDOException $e) {
        $_SESSION['message'] = ['type' => 'error', 'text' => 'Error: ' . $e->getMessage()];
    }

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

// Query data
/* Tabel Relasi Kegiatan: Mengambil master KUB dan Pastor menggunakan LEFT JOIN */
$sql = "
    SELECT 
        kg.*,
        k.nama_kub,
        k.ketua as nama_ketua, 
        pst.nama_pastor
    FROM kegiatan kg
    LEFT JOIN kub k ON kg.id_kub = k.id_kub
    LEFT JOIN pastor pst ON kg.id_pastor = pst.id_pastor
    ORDER BY kg.waktu_tanggal DESC
";

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

$kub_list = $pdo->query("SELECT * FROM kub ORDER BY nama_kub")->fetchAll();
$pengurus_list = $pdo->query("SELECT DISTINCT jenis_pengurus FROM pengurus WHERE jenis_pengurus IS NOT NULL ORDER BY jenis_pengurus")->fetchAll();
$pastor_list = $pdo->query("SELECT * FROM pastor ORDER BY nama_pastor")->fetchAll();

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

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kegiatan 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 href="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/css/tom-select.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/js/tom-select.complete.min.js"></script>
    <link rel="stylesheet" href="style.css?v=<?= time() ?>">
    <style>
        /* Tom Select Style Override to match KUB Theme */
        .ts-wrapper.multi .ts-control {
            border: 2px solid transparent !important;
            border-radius: 16px !important; 
            padding: 8px 14px !important;
            min-height: 44px;
            font-size: 14px;
            font-family: inherit;
            background: white !important;
            color: #2c1810;
            box-shadow: none !important;
            transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
        }

        .ts-wrapper.multi.focus .ts-control {
            outline: none;
            border-color: #c5a55a !important;
            box-shadow: 0 0 0 3px rgba(197, 165, 90, 0.15) !important;
        }

        .ts-control > input {
            font-size: 14px;
            color: #2c1810;
        }

        .ts-wrapper.multi .ts-control > div {
            background: rgba(197, 165, 90, 0.12) !important; 
            color: #a88b3d !important; 
            border: 1px solid rgba(197, 165, 90, 0.3);
            border-radius: 8px;
            padding: 3px 8px;
            margin: 2px 4px 2px 0;
            font-weight: 600;
        }

        .ts-dropdown {
            border: none;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(168, 139, 61, 0.15);
            margin-top: 4px;
            font-family: inherit;
            font-size: 14px;
            overflow: hidden;
            padding: 4px;
        }
        
        .ts-dropdown .option.active, .ts-dropdown .option:hover {
            background-color: rgba(197, 165, 90, 0.08) !important;
            color: #a88b3d !important;
            border-radius: 8px;
        }

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

        .keg-scroll-container {
            scrollbar-width: thin;
            scrollbar-color: var(--gold) rgba(197, 165, 90, 0.1);
        }

        .keg-scroll-container::-webkit-scrollbar {
            display: block;
            width: 8px;
        }

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

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

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

        /* Quick CSS for Badges */
        .badge { display: inline-block; padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: bold; }
        .status-diterima { background-color: #d1fae5; color: #065f46; border: 1px solid #34d399; }
        .status-ditahan { background-color: #fef3c7; color: #92400e; border: 1px solid #fbbf24; }
        .status-dibatalkan { background-color: #fee2e2; color: #991b1b; border: 1px solid #f87171; }
        .status-- { background-color: transparent; }

    </style>
</head>

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

    <!-- Hidden Logo for Export -->
    <img src="logo1.jpg" id="logoExport" style="display:none;" crossorigin="anonymous">

    <?php $active_page = 'kegiatan.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 Kegiatan</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 Kegiatan..." 
                        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" onclick="openModal('create')">+ Tambah Kegiatan</button>
                <?php endif; ?>
            </div>
            </div>
            <div class="print-header" id="printHeader"></div>

            <div class="table-wrapper">
                <table class="table" id="kegiatanTable" style="margin-bottom: 0;">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Nama Kegiatan</th>
                            <th>KUB</th>
                            <th>Jenis Kegiatan</th>
                            <th>Waktu/Tanggal</th>
                            <th>Tempat</th>
                            <th>Pengurus</th>
                            <th>Dana</th>
                            <th>Keterangan</th>
                            <th>Status Paroki</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">
                        <!-- Algoritma penarikan visual: Megurai bundelan array "kegiatan_list" agar masing-masing riwayat tampil tersusun rapi berurutan ke bawah -->
                        <?php $no = 1;
                        foreach ($kegiatan_list as $kg): ?>
                            <tr data-kub-id="<?= htmlspecialchars($kg['id_kub'] ?? '') ?>"
                                data-nama-kub="<?= htmlspecialchars($kg['nama_kub'] ?? '') ?>"
                                data-ketua="<?= htmlspecialchars($kg['nama_ketua'] ?? '') ?>"
                                data-jenis-kegiatan="<?= htmlspecialchars($kg['jenis_kegiatan']) ?>">
                                <td>
                                    <?= $no++ ?>
                                </td>
                                <td><strong>
                                        <?= htmlspecialchars($kg['nama_kegiatan']) ?>
                                    </strong></td>
                                <td>
                                    <?= htmlspecialchars($kg['nama_kub'] ?? '') ?: 'Semua KUB' ?>
                                </td>
                                <td>
                                    <?= htmlspecialchars($kg['jenis_kegiatan']) ?>
                                </td>
                                <td>
                                    <?= formatTanggalIndo($kg['waktu_tanggal']) ?>
                                </td>
                                <td>
                                    <?php if (!empty($kg['tempat'])): ?>
                                        <?= htmlspecialchars($kg['tempat']) ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Belum ditentukan</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if (!empty($kg['pengurus_terlibat'])): ?>
                                        <?= htmlspecialchars($kg['pengurus_terlibat']) ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Belum ada pengurus</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    Rp <?= number_format($kg['dana'] ?? 0, 0, ',', '.') ?>
                                </td>
                                <td>
                                    <?php if (!empty($kg['keterangan'])): ?>
                                        <?= htmlspecialchars($kg['keterangan']) ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Tidak ada keterangan</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <?php if ($kg['butuh_persetujuan_paroki'] === 'iya'): ?>
                                        <span class="badge status-<?= strtolower($kg['status']) ?>"><?= ucfirst($kg['status']) ?></span>
                                        <?php if (!empty($kg['nama_pastor'])): ?>
                                            <div style="font-size: 11px; margin-top: 4px; color: #555;"><?= htmlspecialchars($kg['nama_pastor']) ?></div>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Tidak membutuhkan kehadiran pastor</span>
                                    <?php endif; ?>
                                </td>
                                <?php if ($is_logged_in && hasRole(['admin_paroki', 'ketua_wilayah', 'ketua_kub'])): ?>
                                    <td class="no-print">
                                        <div style="display: flex; gap: 5px;">
                                            <button class="btn btn-sm btn-warning"
                                                onclick='editKegiatan(<?= json_encode($kg) ?>)'>Edit</button>
                                            <button class="btn btn-sm btn-danger"
                                                onclick="deleteKegiatan(<?= $kg['id_kegiatan'] ?>, '<?= htmlspecialchars($kg['nama_kegiatan']) ?>')">Hapus</button>
                                        </div>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot id="tableFooter">
                        <tr style="background-color: rgba(168, 139, 61, 0.1); font-weight: bold;">
                            <td colspan="7" style="text-align: right; padding: 12px;">Total Dana:</td>
                            <td id="totalDana" style="padding: 12px; white-space: nowrap;">Rp 0</td>
                            <td colspan="2"></td>
                            <?php if ($is_logged_in && hasRole(['admin_paroki', 'ketua_wilayah', 'ketua_kub'])): ?>
                                <td class="no-print"></td>
                            <?php endif; ?>
                        </tr>
                    </tfoot>
                </table>
            </div>
            <div class="pagination-container" id="kegPagination"></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="kegiatanModal" class="modal">
        <div class="modal-content" style="max-height: 84.5vh; display: flex; flex-direction: column;">
            <div class="modal-header">
                <h3 id="modalTitle">Tambah Kegiatan</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_kegiatan" id="id_kegiatan">

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

                    <div class="form-row">
                        <div class="form-group">
                            <label>KUB *</label>
                            <select name="id_kub" id="id_kub" required>
                                <option value="">Pilih KUB</option>
                                <option value="semua">Semua 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>Jenis Kegiatan *</label>
                            <select name="jenis_kegiatan" id="jenis_kegiatan" required>
                                <option value="">Pilih</option>
                                <option value="Doa Rosario">Doa Rosario</option>
                                <option value="Tanggungan Koor">Tanggungan Koor</option>
                                <option value="Sosial">Sosial</option>
                                <option value="Perayaan">Perayaan</option>
                                <option value="Lainnya">Lainnya</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Waktu/Tanggal *</label>
                            <input type="datetime-local" name="waktu_tanggal" id="waktu_tanggal" required>
                        </div>
                        <div class="form-group">
                            <label>Tempat *</label>
                            <input type="text" name="tempat" id="tempat" placeholder="Isi Tempat" required>
                        </div>
                    </div>

                    <div class="form-group" style="padding-bottom: 25px;">
                        <label>Pengurus Terlibat (Pilih Seksi) *</label>
                        <select name="pengurus_terlibat[]" id="pengurus_terlibat" multiple required autocomplete="off" placeholder="Ketik atau pilih...">
                            <?php foreach ($pengurus_list as $p): ?>
                                <option value="<?= htmlspecialchars($p['jenis_pengurus']) ?>">
                                    <?= htmlspecialchars($p['jenis_pengurus']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Dana/Anggaran (Rp)</label>
                        <input type="number" name="dana" id="dana" min="0" step="1000" placeholder="0">
                    </div>

                    <div class="form-group">
                        <label>Keterangan</label>
                        <textarea name="keterangan" id="keterangan" rows="3" placeholder="Isi Keterangan"></textarea>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Butuh Kehadiran Pastor?</label>
                            <select name="butuh_persetujuan_paroki" id="butuh_persetujuan_paroki" onchange="togglePersetujuan(this.value)">
                                <option value="tidak">Tidak</option>
                                <option value="iya">Ya</option>
                            </select>
                        </div>
                        <div class="form-group" id="pastor_container" style="display: none;">
                            <label>Pilih Pastor</label>
                            <select name="id_pastor" id="id_pastor">
                                <option value="">Pilih Pastor</option>
                                <?php foreach ($pastor_list as $pst): ?>
                                    <option value="<?= $pst['id_pastor'] ?>"><?= htmlspecialchars($pst['nama_pastor']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <?php if (hasRole(['admin_paroki'])): ?>
                        <div class="form-group" id="status_container" style="display: none;">
                            <label>Status Persetujuan Paroki</label>
                            <select name="status" id="status">
                                <option value="ditahan">Ditahan</option>
                                <option value="diterima">Diterima</option>
                                <option value="dibatalkan">Dibatalkan</option>
                            </select>
                        </div>
                    <?php else: ?>
                        <input type="hidden" name="status" id="status_hidden">
                    <?php endif; ?>

                </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 Kegiatan</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_kegiatan" id="delete_id_kegiatan">
                    <p>Yakin ingin menghapus kegiatan <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) ?>;
        
        let tsInstance;

        function togglePersetujuan(value) {
            const dp = document.getElementById('pastor_container');
            const ds = document.getElementById('status_container');
            const ip = document.getElementById('id_pastor');
            if (value === 'iya') {
                dp.style.display = 'block';
                if(ds) ds.style.display = 'block';
            } else {
                dp.style.display = 'none';
                ip.value = '';
                if(ds) ds.style.display = 'none';
            }
        }

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

            if (action === 'create') {
                document.getElementById('modalTitle').innerText = 'Tambah Kegiatan';
                document.getElementById('formAction').value = 'create';
                document.querySelector('#kegiatanModal form').reset();
                if (tsInstance) tsInstance.clear(true);
                document.getElementById('id_kegiatan').value = '';
                if(document.getElementById('butuh_persetujuan_paroki')) {
                    document.getElementById('butuh_persetujuan_paroki').value = 'tidak';
                    togglePersetujuan('tidak');
                }
            }
        }

        function closeModal() {
            if (window.modalLenis) {
                window.modalLenis.destroy();
                window.modalLenis = null;
            }
            document.getElementById('kegiatanModal').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 meload detail kegiatan yang ingin diperbarui ke jendela form modal edit */
        function editKegiatan(kegiatan) {
            openModal('edit');
            document.getElementById('modalTitle').innerText = 'Edit Kegiatan';
            document.getElementById('formAction').value = 'update';
            document.getElementById('id_kegiatan').value = kegiatan.id_kegiatan;
            document.getElementById('nama_kegiatan').value = kegiatan.nama_kegiatan;
            document.getElementById('id_kub').value = kegiatan.id_kub || 'semua';
            document.getElementById('jenis_kegiatan').value = kegiatan.jenis_kegiatan;
            document.getElementById('waktu_tanggal').value = kegiatan.waktu_tanggal.replace(' ', 'T');
            document.getElementById('tempat').value = kegiatan.tempat;
            
            const valuesPengurus = (kegiatan.pengurus_terlibat || '').split(',').map(s => s.trim()).filter(Boolean);
            if (tsInstance) {
                tsInstance.clear(true);
                if (valuesPengurus.length > 0) tsInstance.setValue(valuesPengurus, true);
            } else {
                const selectPengurus = document.getElementById('pengurus_terlibat');
                Array.from(selectPengurus.options).forEach(opt => {
                    opt.selected = valuesPengurus.includes(opt.value);
                });
            }
            
            document.getElementById('dana').value = kegiatan.dana || 0;
            document.getElementById('keterangan').value = kegiatan.keterangan || '';
            
            const butuh = kegiatan.butuh_persetujuan_paroki || 'tidak';
            if(document.getElementById('butuh_persetujuan_paroki')) {
                document.getElementById('butuh_persetujuan_paroki').value = butuh;
                togglePersetujuan(butuh);
            }
            if (document.getElementById('id_pastor')) document.getElementById('id_pastor').value = kegiatan.id_pastor || '';
            if (document.getElementById('status_hidden')) document.getElementById('status_hidden').value = kegiatan.status || '-';
            if (document.getElementById('status')) document.getElementById('status').value = kegiatan.status || '-';
        }

        /* Fungsi pencegahan penghapusan tak disengaja dengan dialog konfirmasi untuk Kegiatan */
        function deleteKegiatan(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_kegiatan').value = id;
            document.getElementById('delete_nama').innerText = nama;
        }

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

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

        // Print/Export Functions

        /* Fungsi pemrosesan file Excel untuk mengunduh rekapitulasi daftar Kegiatan beserta biayanya */
        async function confirmExportExcel() {
            document.getElementById('loadingOverlay').style.display = 'flex';
            try {
                var uniqueKUBs = new Set();
                var uniqueJenis = new Set();
                var lastVisibleKUBName = '';
                var lastVisibleKetua = '';
                var lastVisibleJenis = '';

                document.querySelectorAll('#tableBody tr').forEach(function(row) {
                    if (row.style.display !== 'none') {
                        var kubName = row.getAttribute('data-nama-kub');
                        var ketuaName = row.getAttribute('data-ketua');
                        var jenisName = row.getAttribute('data-jenis-kegiatan');
                        if (kubName) { uniqueKUBs.add(kubName); lastVisibleKUBName = kubName; lastVisibleKetua = ketuaName; }
                        if (jenisName) { uniqueJenis.add(jenisName); lastVisibleJenis = jenisName; }
                    }
                });

                var isSingleKUB = uniqueKUBs.size === 1;
                var namaKUB = isSingleKUB ? lastVisibleKUBName : '';
                var jenis = uniqueJenis.size === 1 ? lastVisibleJenis : '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 workbook = new ExcelJS.Workbook();
                var ws = workbook.addWorksheet('Data Kegiatan');

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

                // === KOP SURAT ===
                ws.mergeCells('A1:J1');
                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:J2');
                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:J3');
                    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 <= 10; 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: 72px jika 3 baris (KUB spesifik), 45px jika 2 baris (Semua KUB)
                    // Digunakan pecahan (0.1) untuk memberi jarak spasi/padding aman dari tepi margin
                    var logoSize = kopLastRow === 3 ? 62 : 40;
                    ws.addImage(imageId, { 
                        tl: { col: 0.1, row: 0.1 }, 
                        ext: { width: logoSize, height: logoSize } 
                    });
                }

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

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

                ws.mergeCells('A' + dRow + ':J' + 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 + ':J' + tRow);
                ws.getCell('A' + tRow).value = 'DATA KEGIATAN KUB' + (jenis !== 'all' ? ' (' + jenis.toUpperCase() + ')' : '');
                ws.getCell('A' + tRow).font = { size: 14, bold: true, underline: true };
                ws.getCell('A' + tRow).alignment = { horizontal: 'center' };
                ws.getRow(tRow + 1).height = 8;

                // === HEADER ===
                var headerRow = ws.addRow(['No', 'Nama Kegiatan', 'KUB', 'Jenis', 'Waktu', 'Tempat', 'Pengurus', 'Dana', 'Keterangan', 'Status']);
                headerRow.height = 22;
                headerRow.eachCell(function(cell) {
                    cell.font = { bold: true, size: 10 };
                    cell.alignment = { horizontal: 'center', vertical: 'middle' };
                    cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
                    cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } };
                });

                // === DATA ===
                var num = 1;
                var totalDana = 0;
                document.querySelectorAll('#tableBody tr').forEach(function(row) {
                    if (row.style.display !== 'none') {
                        var c = row.cells;
                        if (c && c.length >= 10) {
                            var danaText = c[7].innerText;
                            var danaVal = parseInt(danaText.replace(/[^0-9]/g, '')) || 0;
                            totalDana += danaVal;
                            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(), danaVal, c[8].innerText.trim(), c[9].innerText.trim()]);
                            dr.eachCell(function(cell, colNumber) {
                                cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } };
                                cell.font = { size: 10 };
                                
                                // wrapText: true berfungsi agar teks yang berjejal, termasuk nama pastor/keterangan yang ada "\n", turun otomatis
                                cell.alignment = { vertical: 'middle', wrapText: true };
                                if (colNumber === 1 || colNumber === 10) {
                                    cell.alignment = { horizontal: 'center', vertical: 'middle', wrapText: true };
                                }
                                
                                if (colNumber === 8) cell.numFmt = '"Rp "#,##0';
                            });
                        }
                    }
                });

                // === TOTAL ===
                var totalRow = ws.addRow(['', '', '', '', '', '', 'Total Dana:', totalDana, '', '']);
                ws.mergeCells('A' + totalRow.number + ':G' + totalRow.number);
                
                var cellA = ws.getCell('A' + totalRow.number);
                cellA.value = 'Total Dana:';
                cellA.font = { bold: true };
                cellA.alignment = { horizontal: 'right' };
                
                var cellDana = ws.getCell('H' + totalRow.number);
                cellDana.value = totalDana;
                cellDana.font = { bold: true };
                cellDana.numFmt = '"Rp "#,##0';

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

                var dateFile = now.toISOString().split('T')[0];
                var safeKubName = namaKUB ? namaKUB.replace(/\s+/g, '_') : 'Wilayah_IV';
                var safeJenis = jenis !== 'all' ? '_' + jenis.replace(/\s+/g, '_') : '';
                var buffer = await workbook.xlsx.writeBuffer();
                saveAs(new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), 'Kegiatan_' + safeKubName + safeJenis + '_' + 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 menyiapkan layout Print dokumen Kegiatan yang rapi dengan kop institusi */
        async function confirmPrint() {
            let uniqueKUBs = new Set();
            let uniqueJenis = new Set();
            let lastVisibleKUBName = '';
            let lastVisibleJenis = '';

            document.querySelectorAll('#tableBody tr').forEach(row => {
                if (row.style.display !== 'none') {
                    const kubName = row.getAttribute('data-nama-kub');
                    const jenisName = row.getAttribute('data-jenis-kegiatan');
                    if (kubName) { uniqueKUBs.add(kubName); lastVisibleKUBName = kubName; }
                    if (jenisName) { uniqueJenis.add(jenisName); lastVisibleJenis = jenisName; }
                }
            });

            const namaKUB = uniqueKUBs.size === 1 ? lastVisibleKUBName : '';
            const jenis = uniqueJenis.size === 1 ? lastVisibleJenis : '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('#tableBody 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>
                        <td style="border:1px solid #000; padding:6px;">${c[7].innerText}</td>
                        <td style="border:1px solid #000; padding:6px;">${c[8].innerText}</td>
                        <td style="border:1px solid #000; padding:6px; text-align:center;">${c[9].innerText}</td>
                    </tr>`;
                }
            });

            let totalDanaPrint = 0;
            document.querySelectorAll('#tableBody tr').forEach(row => {
                if (row.style.display !== 'none') {
                    const danaText = row.cells[7].innerText;
                    totalDanaPrint += parseInt(danaText.replace(/[^0-9]/g, '')) || 0;
                }
            });
            const totalDanaPrintStr = 'Rp ' + totalDanaPrint.toLocaleString('id-ID');

            tableRows += `
                <tr style="background-color: #f0f0f0; font-weight: bold;">
                    <td colspan="7" style="border:1px solid #000; padding:6px; text-align:right;">Total Dana:</td>
                    <td style="border:1px solid #000; padding:6px; text-align:right;">${totalDanaPrintStr}</td>
                    <td colspan="2" style="border:1px solid #000; padding:6px;"></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 KEGIATAN KUB${jenis !== 'all' ? ` (${jenis.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 Kegiatan</th>
                            <th style="border:1px solid #000; padding:6px;">KUB</th>
                            <th style="border:1px solid #000; padding:6px;">Jenis Kegiatan</th>
                            <th style="border:1px solid #000; padding:6px;">Waktu/Tanggal</th>
                            <th style="border:1px solid #000; padding:6px;">Tempat</th>
                            <th style="border:1px solid #000; padding:6px;">Pengurus</th>
                            <th style="border:1px solid #000; padding:6px;">Dana</th>
                            <th style="border:1px solid #000; padding:6px;">Keterangan</th>
                            <th style="border:1px solid #000; padding:6px;">Status Paroki</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.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: 'kegiatanTable', tbodyId: 'tableBody', containerId: 'kegPagination', perPage: 10, onPageChange: calculateTotals });
            if (document.getElementById('pengurus_terlibat')) {
                tsInstance = new TomSelect('#pengurus_terlibat',{
                    plugins: ['remove_button'],
                    create: false,
                    sortField: { field: "text", direction: "asc" }
                });
            }
            calculateTotals(); // Initial load

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

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

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

            // Standalone cards (financial chart, 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>
