<?php
// Konfigurasi Database
// $host = 'localhost';
// $user = 'root';
// $pass = '';
// $db   = 'pos_m';

// Error reporting untuk development
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    // Koneksi dengan error handling
include_once '../data.php';
$conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        throw new Exception("Koneksi database gagal: " . $conn->connect_error);
    }
    $conn->set_charset("utf8");

    // Default range tanggal: bulan ini
    $start_date = date('Y-m-01');
    $end_date = date('Y-m-t');

    // Validasi dan sanitasi input
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['start_date']) && isset($_POST['end_date'])) {
            $start_date = filter_var($_POST['start_date'], FILTER_SANITIZE_STRING);
            $end_date = filter_var($_POST['end_date'], FILTER_SANITIZE_STRING);
        }
    }

    // Query utama
    $sql = "
    SELECT 
        j.brand, j.cab, cabang.nama AS cabang_nama, tt.nama AS tipe_nama, j.mesin, j.nomor, j.tanggal, j.jamm, j.shift, j.user AS user_jual, j.batal, 
        j.kasir, users.nama AS kasir_nama, j.register, j.deliver, p.sub, p.payment, p.tglo, p.kode, p.name AS nama_barang, p.group_name,
        CAST(p.quantity AS DECIMAL(10,2)) as quantity, CAST(p.harga AS DECIMAL(15,2)) as harga,
        CAST(p.price AS DECIMAL(15,2)) as price, CAST(p.discp AS DECIMAL(10,2)) as discp,
        CAST(p.discr AS DECIMAL(15,2)) as discr, CAST(p.netto AS DECIMAL(15,2)) as netto,
        CAST(p.disc AS DECIMAL(15,2)) as disc, CAST(p.ppn AS DECIMAL(15,2)) as ppn,
        CAST(p.pajak AS DECIMAL(15,2)) as pajak, CAST(p.serv AS DECIMAL(15,2)) as serv,
        CAST(p.service AS DECIMAL(15,2)) as service, CAST(p.jumlah AS DECIMAL(15,2)) as jumlah,
        p.meja, p.user AS user_pesani
    FROM jual j
    LEFT JOIN pesani p ON j.nomor = p.nomor
    LEFT JOIN tipe_transaksi tt ON j.tipe = tt.kode
    LEFT JOIN cabang ON j.cab = cabang.kode
    LEFT JOIN users ON j.kasir = users.kode
    WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 and p.payment < '01'
    ORDER BY j.tanggal ASC, j.nomor ASC, p.kode ASC
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $start_date, $end_date);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $data = [];
    while ($row = $result->fetch_assoc()) {
        foreach ($row as $key => $value) {
            if ($value === null) {
                $row[$key] = is_numeric($row[$key]) ? 0 : '-';
            }
        }
        $data[] = $row;
    }

    $stmt->close();
    $conn->close();
    
    $jsonData = json_encode($data, JSON_NUMERIC_CHECK);

} catch (Exception $e) {
    $error_message = $e->getMessage();
    $data = [];
    $jsonData = '[]';
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laporan Penjualan Pivot Table</title>
    <link href="material.css" rel="stylesheet" />
    <link href="pivot.css" rel="stylesheet" />
    <script src="ej2.min.js" type="text/javascript"></script>
    <style>
        
    </style>
</head>
<body>
    <div class="container">
        <h2>Laporan Penjualan Pivot Table</h2>

        <div class="filter">
            <form id="filterForm" method="POST" action="" style="display: contents;">
                <div class="form-group">
                    <label for="start_date">Tanggal Mulai:</label>
                    <input type="date" id="start_date" name="start_date" 
                           value="<?= htmlspecialchars($start_date, ENT_QUOTES, 'UTF-8') ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="end_date">Tanggal Akhir:</label>
                    <input type="date" id="end_date" name="end_date" 
                           value="<?= htmlspecialchars($end_date, ENT_QUOTES, 'UTF-8') ?>" required>
                </div>

                <div class="form-group">
                    <label for="auto_template">Template Auto:</label>
                    <select id="auto_template" name="auto_template">
                        <option value="">-- Tanpa Template --</option>
                    </select>
                </div>
                
                <div class="form-groupx">
                    <label>&nbsp;</label>
                    <button type="submit" class="btn">Tampilkan Laporan</button>
                </div>
            </form>

            <!-- <div class="form-group">
                <label for="report_list">Muat Template:</label>
                <select id="report_list">
                    <option value="">-- Pilih Template --</option>
                </select>
            </div>
            <div class="form-group">
                <label>&nbsp;</label>
                <button type="button" id="loadSelectedReportButton" class="btn load-btn">Muat</button>
            </div> -->
            <!-- <div class="form-groupx">
                <label>&nbsp;</label>
                <button type="button" id="toggleLayoutButton" class="btn toggle-btn">Tree View</button>
            </div> -->
            <div class="form-groupx">
                <label>&nbsp;</label>
                <button type="button" id="expandAllButton" class="btn">Expand All</button>
            </div>
            <div class="form-groupx">
                <label>&nbsp;</label>
                <button type="button" id="collapseAllButton" class="btn toggle-btn">Collapse All</button>
            </div>
            <div class="form-groupx">
                <label>&nbsp;</label>
                <button type="button" id="toggleGroupingButton" class="btn toggle-btn">Hide Grouping</button>
            </div>
        </div>

        <?php if (isset($error_message)): ?>
            <div class="error-message">Error: <?= htmlspecialchars($error_message) ?></div>
        <?php elseif (empty($data)): ?>
            <div class="no-data">Tidak ada data penjualan untuk rentang tanggal ini.</div>
        <?php else: ?>
            <div class="info-box">Menampilkan <?= number_format(count($data)) ?> baris data dari <?= date('d/m/Y', strtotime($start_date)) ?> sampai <?= date('d/m/Y', strtotime($end_date)) ?></div>
            <div id="loading">Memuat pivot table...</div>
            <div id="pivotTable" style="display: none;"></div>
        <?php endif; ?>
    </div>

    <?php if (!empty($data)): ?>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            let pivotData = <?php echo $jsonData; ?>;

            if (!Array.isArray(pivotData) || pivotData.length === 0) {
                document.getElementById('loading').innerHTML = 'Error: Data tidak valid atau kosong';
                return;
            }

            try {
                // Inisialisasi modul yang diperlukan
                ej.base.enableRipple(true);
                ej.pivotview.PivotView.Inject(ej.pivotview.Tree, ej.pivotview.FieldList, ej.pivotview.PivotChart, ej.pivotview.ExcelExport, ej.pivotview.PDFExport);
                
                const apiUrl = 'api_pivot.php'; // URL ke file API PHP Anda

                // Konfigurasi untuk Tree View (default)
                const treeViewSettings = {
                    dataSource: pivotData,
                    expandAll: false,
                    enableSorting: true,
                    rows: [
                        { name: 'tanggal', caption: 'Tanggal' },
                        { name: 'kasir_nama', caption: 'Kasir' }
                    ],
                    columns: [
                        { name: 'tipe_nama', caption: 'Tipe Transaksi' },
                        { name: 'group_name', caption: 'Grup Barang' }
                    ],
                    values: [
                        { name: 'quantity', caption: 'Kuantitas', type: 'Sum' },
                        { name: 'jumlah', caption: 'Total Jumlah (Rp)', type: 'Sum' }
                    ],
                    filters: [
                        { name: 'meja', caption: 'Meja' },
                        { name: 'nama_barang', caption: 'Nama Barang' }
                    ],
                    formatSettings: [
                        { name: 'jumlah', format: 'N0' },
                        { name: 'quantity', format: 'N2' }
                    ]
                };

                // Konfigurasi untuk Flat View
                const flatViewSettings = {
                    dataSource: pivotData,
                    expandAll: false,
                    enableSorting: true,
                    rows: [
                        { name: 'tanggal', caption: 'Tanggal' }
                    ],
                    columns: [
                        { name: 'tipe_nama', caption: 'Tipe Transaksi' },
                        { name: 'group_name', caption: 'Grup Barang' }
                    ],
                    values: [
                        { name: 'quantity', caption: 'Kuantitas', type: 'Sum' },
                        { name: 'jumlah', caption: 'Total Jumlah (Rp)', type: 'Sum' }
                    ],
                    filters: [
                        { name: 'meja', caption: 'Meja' },
                        { name: 'nama_barang', caption: 'Nama Barang' },
                        { name: 'kasir_nama', caption: 'Kasir' }
                    ],
                    formatSettings: [
                        { name: 'jumlah', format: 'N0' },
                        { name: 'quantity', format: 'N2' }
                    ]
                };

                let isTreeView = true; // Status awal: Tree View
                let pivotObj;

                // Fungsi untuk mengisi dropdown laporan
                async function populateReportDropdown() {
                    try {
                        const response = await fetch(`${apiUrl}?action=fetch`);
                        
                        if (!response.ok) {
                            throw new Error(`HTTP error! status: ${response.status}`);
                        }
                        
                        const reportNames = await response.json();

                        const reportListDropdown = document.getElementById('report_list');
                        const autoTemplateDropdown = document.getElementById('auto_template');
                        
                        // Populate both dropdowns
                        reportListDropdown.innerHTML = '<option value="">-- Pilih Template --</option>';
                        autoTemplateDropdown.innerHTML = '<option value="">-- Tanpa Template --</option>';

                        if (Array.isArray(reportNames) && reportNames.length > 0) {
                            reportNames.forEach(name => {
                                // Manual load dropdown
                                const option1 = document.createElement('option');
                                option1.value = name;
                                option1.textContent = name;
                                reportListDropdown.appendChild(option1);
                                
                                // Auto template dropdown
                                const option2 = document.createElement('option');
                                option2.value = name;
                                option2.textContent = name;
                                autoTemplateDropdown.appendChild(option2);
                            });
                            console.log('Daftar template berhasil dimuat:', reportNames.length, 'template');
                        } else {
                            console.log('Tidak ada template yang tersimpan');
                        }
                    } catch (error) {
                        console.error('Gagal mengambil daftar laporan:', error);
                        const reportListDropdown = document.getElementById('report_list');
                        const autoTemplateDropdown = document.getElementById('auto_template');
                        reportListDropdown.innerHTML = '<option value="">-- Error memuat template --</option>';
                        autoTemplateDropdown.innerHTML = '<option value="">-- Error memuat template --</option>';
                    }
                }

                // Fungsi untuk memuat template
                async function loadTemplateByName(templateName) {
                    if (!templateName) return false;

                    try {
                        const responseReport = await fetch(`${apiUrl}?action=load&reportName=${encodeURIComponent(templateName)}`);
                        
                        if (!responseReport.ok) {
                            throw new Error(`HTTP error! status: ${responseReport.status}`);
                        }

                        const textData = await responseReport.text();

                        if (!textData || textData.trim() === '{}' || textData.trim() === '') {
                            throw new Error('Template kosong atau tidak ditemukan');
                        }

                        const report = JSON.parse(textData);

                        if (!report.dataSourceSettings) {
                            throw new Error('Template tidak memiliki struktur dataSourceSettings yang valid');
                        }

                        // Simpan data source saat ini
                        const currentDataSource = pivotObj.dataSourceSettings.dataSource;
                        
                        // Restore data source ke template
                        report.dataSourceSettings.dataSource = currentDataSource;

                        // Apply template ke pivot table
                        pivotObj.dataSourceSettings = report.dataSourceSettings;
                        
                        console.log('Template berhasil dimuat:', templateName);
                        return true;

                    } catch (error) {
                        console.error('Error saat memuat template:', error);
                        return false;
                    }
                }

                // Inisialisasi Pivot View
                pivotObj = new ej.pivotview.PivotView({
                    dataSourceSettings: treeViewSettings,
                    showToolbar: true,
                    toolbar: ['New', 'Save', 'SaveAs', 'Rename', 'Remove', 'Load', 'Grid', 'Chart', 'Export', 'SubTotal', 'GrandTotal', 'FieldList', 'PDFExport', 'ExcelExport', 'CSVExport'],
                    showFieldList: true,
                    allowExcelExport: true,
                    allowPdfExport: true,
                    allowConditionalFormatting: true,
                    allowNumberFormatting: true,
                    showGroupingBar: true,
                    displayOption: { view: 'Both' }, // Enable both Grid and Chart views
                    height: 650,
                    
                    // Chart configuration
                    chartSettings: {
                        value: 'Amount',
                        enableExport: true,
                        chartSeries: { type: 'Column' }, // Column = vertical bars
                        primaryXAxis: { 
                            title: 'Categories',
                            labelRotation: -45 // Rotasi label jika teks panjang
                        },
                        primaryYAxis: { 
                            title: 'Values',
                            labelFormat: 'n0' // Format angka
                        },
                        title: 'Sales Analysis',
                        enableMultipleAxis: false,
                        showTooltip: true,
                        enableAnimation: true
                    },

                    // Event handler untuk menyimpan laporan
                    saveReport: function(args) {
                        try {
                            // Ekstrak hanya data yang diperlukan untuk menghindari circular references
                            let reportToSave = {
                                dataSourceSettings: {
                                    rows: pivotObj.dataSourceSettings.rows ? pivotObj.dataSourceSettings.rows.map(item => ({
                                        name: item.name,
                                        caption: item.caption,
                                        type: item.type || 'Sum',
                                        expandAll: item.expandAll || false,
                                        showSubTotals: item.showSubTotals !== false
                                    })) : [],
                                    columns: pivotObj.dataSourceSettings.columns ? pivotObj.dataSourceSettings.columns.map(item => ({
                                        name: item.name,
                                        caption: item.caption,
                                        type: item.type || 'Sum',
                                        expandAll: item.expandAll || false,
                                        showSubTotals: item.showSubTotals !== false
                                    })) : [],
                                    values: pivotObj.dataSourceSettings.values ? pivotObj.dataSourceSettings.values.map(item => ({
                                        name: item.name,
                                        caption: item.caption,
                                        type: item.type || 'Sum'
                                    })) : [],
                                    filters: pivotObj.dataSourceSettings.filters ? pivotObj.dataSourceSettings.filters.map(item => ({
                                        name: item.name,
                                        caption: item.caption,
                                        type: item.type || 'Sum'
                                    })) : [],
                                    formatSettings: pivotObj.dataSourceSettings.formatSettings ? pivotObj.dataSourceSettings.formatSettings.map(item => ({
                                        name: item.name,
                                        format: item.format,
                                        useGrouping: item.useGrouping !== false
                                    })) : [],
                                    expandAll: pivotObj.dataSourceSettings.expandAll || false,
                                    enableSorting: pivotObj.dataSourceSettings.enableSorting !== false,
                                    showSubTotals: pivotObj.dataSourceSettings.showSubTotals !== false,
                                    showRowSubTotals: pivotObj.dataSourceSettings.showRowSubTotals !== false,
                                    showColumnSubTotals: pivotObj.dataSourceSettings.showColumnSubTotals !== false,
                                    showGrandTotals: pivotObj.dataSourceSettings.showGrandTotals !== false,
                                    showRowGrandTotals: pivotObj.dataSourceSettings.showRowGrandTotals !== false,
                                    showColumnGrandTotals: pivotObj.dataSourceSettings.showColumnGrandTotals !== false,
                                    // Sengaja tidak menyimpan dataSource (data mentah)
                                    dataSource: []
                                }
                            };

                            console.log('Template yang akan disimpan:', reportToSave);

                            let formData = new FormData();
                            formData.append('action', 'save');
                            formData.append('reportName', args.reportName);
                            formData.append('report', JSON.stringify(reportToSave));
                            
                            fetch(apiUrl, { method: 'POST', body: formData })
                                .then(response => response.json())
                                .then(data => {
                                    if (data.status === 'success') {
                                        console.log('Laporan berhasil disimpan:', args.reportName);
                                        alert('Laporan berhasil disimpan: ' + args.reportName);
                                        populateReportDropdown();
                                    } else {
                                        console.error('Gagal menyimpan laporan:', data.message);
                                        alert('Gagal menyimpan laporan: ' + data.message);
                                    }
                                })
                                .catch(error => {
                                    console.error('Error saat menyimpan:', error);
                                    alert('Terjadi kesalahan saat menyimpan laporan');
                                });
                        } catch (error) {
                            console.error('Error dalam saveReport:', error);
                            alert('Gagal menyimpan template: ' + error.message);
                        }
                    },
                    
                    // Event handler untuk memuat laporan
                    loadReport: function(args) {
                        fetch(`${apiUrl}?action=load&reportName=${encodeURIComponent(args.reportName)}`)
                            .then(response => response.text()) // Ambil sebagai text dulu
                            .then(textData => {
                                console.log('loadReport received raw text:', textData);
                                
                                if (textData && textData.trim() !== '{}' && textData.trim() !== '') {
                                    try {
                                        const data = JSON.parse(textData);
                                        console.log('loadReport parsed data:', data);
                                        
                                        // Cek apakah data memiliki struktur template yang valid
                                        if (data.dataSourceSettings) {
                                            // Restore data source dari pivot table yang aktif
                                            const currentDataSource = pivotObj.dataSourceSettings.dataSource;
                                            data.dataSourceSettings.dataSource = currentDataSource;
                                            
                                            args.report = JSON.stringify(data);
                                            console.log('Template berhasil dimuat via toolbar:', args.reportName);
                                        } else {
                                            console.error('Template tidak memiliki struktur yang valid');
                                            args.report = '{}';
                                        }
                                    } catch (e) {
                                        console.error('Error parsing JSON:', e);
                                        args.report = '{}';
                                    }
                                } else {
                                    console.warn('Template kosong atau tidak ditemukan:', args.reportName);
                                    args.report = '{}';
                                }
                            })
                            .catch(error => {
                                console.error('Error saat memuat template:', error);
                                args.report = '{}';
                            });
                    },

                    // Event handler untuk rename laporan
                    renameReport: function(args) {
                        let formData = new FormData();
                        formData.append('action', 'rename');
                        formData.append('oldReportName', args.oldReportName);
                        formData.append('newReportName', args.newReportName);
                        fetch(apiUrl, { method: 'POST', body: formData })
                            .then(res => res.json())
                            .then(data => {
                                if (data.status === 'success') {
                                    console.log('Ubah nama berhasil:', data.message);
                                    populateReportDropdown();
                                } else {
                                    alert('Gagal mengubah nama: ' + data.message);
                                }
                            })
                            .catch(error => {
                                console.error('Error saat rename:', error);
                                alert('Terjadi kesalahan saat mengubah nama');
                            });
                    },
                    
                    // Event handler untuk hapus laporan
                    removeReport: function(args) {
                        let formData = new FormData();
                        formData.append('action', 'remove');
                        formData.append('reportName', args.reportName);
                        fetch(apiUrl, { method: 'POST', body: formData })
                            .then(res => res.json())
                            .then(data => {
                                if (data.status === 'success') {
                                    console.log('Hapus berhasil:', data.message);
                                    populateReportDropdown();
                                } else {
                                    alert('Gagal menghapus: ' + data.message);
                                }
                            })
                            .catch(error => {
                                console.error('Error saat remove:', error);
                                alert('Terjadi kesalahan saat menghapus');
                            });
                    },
                    
                    // Event handler untuk fetch report list
                    fetchReport: function(args) {
                        args.reportName = fetch(`${apiUrl}?action=fetch`).then(res => res.json());
                    },
                    
                    // Event saat pivot table selesai di-render
                    dataBound: function() {
                        document.getElementById('loading').style.display = 'none';
                        document.getElementById('pivotTable').style.display = 'block';
                        
                        // Check if there's a template to auto-apply after page reload
                        const autoTemplate = sessionStorage.getItem('autoApplyTemplate');
                        if (autoTemplate) {
                            sessionStorage.removeItem('autoApplyTemplate'); // Clear after use
                            setTimeout(() => {
                                loadTemplateByName(autoTemplate).then(success => {
                                    if (success) {
                                        // Set the dropdown values to show which template is active
                                        document.getElementById('auto_template').value = autoTemplate;
                                        document.getElementById('report_list').value = autoTemplate;
                                        console.log('Auto-applied template after reload:', autoTemplate);
                                    }
                                });
                            }, 1000); // Delay sedikit untuk memastikan pivot table sudah fully loaded
                        }
                    }
                });

                pivotObj.appendTo('#pivotTable');

                // Event listener untuk tombol toggle Tree/Flat View
                const toggleLayoutButton = document.getElementById('toggleLayoutButton');
                toggleLayoutButton.addEventListener('click', function() {
                    isTreeView = !isTreeView;
                    pivotObj.dataSourceSettings = isTreeView ? treeViewSettings : flatViewSettings;
                    toggleLayoutButton.textContent = isTreeView ? 'Tree View' : 'Flat View';
                });

                // Event listener untuk expand all
                const expandAllButton = document.getElementById('expandAllButton');
                expandAllButton.addEventListener('click', function() {
                    if (pivotObj) {
                        let currentSettings = pivotObj.dataSourceSettings;
                        pivotObj.dataSourceSettings = {
                            ...currentSettings,
                            expandAll: true
                        };
                    }
                });

                // Event listener untuk collapse all
                const collapseAllButton = document.getElementById('collapseAllButton');
                collapseAllButton.addEventListener('click', function() {
                    if (pivotObj) {
                        let currentSettings = pivotObj.dataSourceSettings;
                        pivotObj.dataSourceSettings = {
                            ...currentSettings,
                            expandAll: false
                        };
                    }
                });

                // Event listener untuk toggle grouping bar
                const toggleGroupingButton = document.getElementById('toggleGroupingButton');
                let isGroupingVisible = true;
                toggleGroupingButton.addEventListener('click', function() {
                    isGroupingVisible = !isGroupingVisible;
                    pivotObj.showGroupingBar = isGroupingVisible;
                    toggleGroupingButton.textContent = isGroupingVisible ? 'Hide Grouping' : 'Show Grouping';
                });

                                    // Event listener untuk auto-apply template saat dropdown berubah
                const reportListDropdown = document.getElementById('report_list');
                reportListDropdown.addEventListener('change', async function() {
                    const selectedTemplate = this.value;
                    if (selectedTemplate) {
                        const success = await loadTemplateByName(selectedTemplate);
                        if (success) {
                            // Sync dengan auto template dropdown
                            document.getElementById('auto_template').value = selectedTemplate;
                        }
                    }
                });

                // Event listener untuk auto template dropdown
                const autoTemplateDropdown = document.getElementById('auto_template');
                autoTemplateDropdown.addEventListener('change', async function() {
                    const selectedTemplate = this.value;
                    if (selectedTemplate) {
                        const success = await loadTemplateByName(selectedTemplate);
                        if (success) {
                            // Sync dengan manual load dropdown
                            document.getElementById('report_list').value = selectedTemplate;
                        }
                    }
                });

                // Event listener untuk tombol Muat Template (sekarang opsional)
                const loadSelectedReportButton = document.getElementById('loadSelectedReportButton');
                loadSelectedReportButton.addEventListener('click', async function() {
                    const chosenReport = document.getElementById('report_list').value;

                    if (!chosenReport) {
                        alert('Silakan pilih template laporan yang ingin dimuat.');
                        return;
                    }

                    // Tampilkan loading indicator
                    this.textContent = 'Loading...';
                    this.disabled = true;

                    try {
                        const success = await loadTemplateByName(chosenReport);
                        if (success) {
                            alert(`Template "${chosenReport}" berhasil dimuat dengan data saat ini.`);
                        } else {
                            alert(`Gagal memuat template "${chosenReport}"`);
                        }
                    } finally {
                        // Reset tombol
                        this.textContent = 'Muat';
                        this.disabled = false;
                    }
                });

                // Event listener untuk form submit - auto apply template yang terpilih
                const filterForm = document.getElementById('filterForm');
                if (filterForm) {
                    filterForm.addEventListener('submit', function(e) {
                        const selectedAutoTemplate = document.getElementById('auto_template').value;
                        if (selectedAutoTemplate) {
                            // Simpan template yang dipilih untuk di-apply setelah page reload
                            sessionStorage.setItem('autoApplyTemplate', selectedAutoTemplate);
                        }
                        // Form akan submit normal, page akan reload dengan data baru
                    });
                }

                // Inisialisasi dropdown saat halaman dimuat
                populateReportDropdown();

            } catch (error) {
                console.error('Error initializing pivot table:', error);
                document.getElementById('loading').innerHTML = 'Error memuat pivot table: ' + error.message;
            }
        });
    </script>
    <?php endif; ?>
</body>
</html>