const { createApp } = Vue;

createApp({
    data() {
        return {
            isLoading: false,
            rawData: [], // Akan menyimpan data gabungan dari query
            summary: {
                totalRevenue: 0,
                totalTransactions: 0,
                totalItemsSold: 0,
            },
            dailyChart: null,
        };
    },
    methods: {
        async fetchData() {
            this.isLoading = true;
            try {
                // Query SQL yang lebih powerful untuk menggabungkan semua data yang diperlukan
                const query = `
                    SELECT 
                        t.transaction_code,
                        t.customer_name,
                        t.transaction_date,
                        p.brand_name,
                        p.category,
                        ti.product_name,
                        ti.quantity,
                        ti.price_per_item,
                        ti.item_details
                    FROM transaction_items ti
                    JOIN transactions t ON ti.transaction_id = t.id
                    LEFT JOIN products p ON ti.product_id = p.id
                    ORDER BY t.transaction_date DESC
                `;

                this.rawData = await ambil_select(query) || [];

                this.calculateSummary();
                this.renderDailyRevenueChart();
                this.renderPivotTable(); // Panggil fungsi pivot yang sudah diperbarui

            } catch (error) {
                console.error("Error fetching report data:", error);
                alert(`Gagal memuat data laporan: ${error.message}`);
            } finally {
                this.isLoading = false;
            }
        },

        calculateSummary() {
            // Kalkulasi ringkasan masih bisa menggunakan data mentah sebelum diproses lebih lanjut
            const uniqueTransactions = [...new Set(this.rawData.map(item => item.transaction_code))];
            this.summary.totalTransactions = uniqueTransactions.length;

            this.summary.totalRevenue = this.rawData.reduce((sum, t) => {
                // Kita asumsikan price_per_item sudah termasuk addon/condiment
                 return sum + (parseFloat(t.price_per_item) * parseInt(t.quantity, 10));
            }, 0);

            this.summary.totalItemsSold = this.rawData.reduce((sum, i) => sum + parseInt(i.quantity, 10), 0);
        },

        renderDailyRevenueChart() {
            const labels = [];
            const data = [];
            const dailyData = {};
            const uniqueTransactions = {}; // Untuk memastikan pendapatan per transaksi tidak dihitung ganda

             // Inisialisasi 7 hari terakhir
            for (let i = 6; i >= 0; i--) {
                const d = new Date();
                d.setDate(d.getDate() - i);
                const label = d.toISOString().split('T')[0];
                labels.push(new Intl.DateTimeFormat('id-ID', { weekday: 'short', day: 'numeric' }).format(d));
                dailyData[label] = 0;
            }

            // Agregasi data
            this.rawData.forEach(t => {
                const date = t.transaction_date.split(' ')[0];
                const revenue = parseFloat(t.price_per_item) * parseInt(t.quantity);
                if (dailyData.hasOwnProperty(date)) {
                    dailyData[date] += revenue;
                }
            });

            const ctx = document.getElementById('dailyRevenueChart').getContext('2d');
            if (this.dailyChart) {
                this.dailyChart.destroy();
            }
            this.dailyChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Pendapatan',
                        data: Object.values(dailyData),
                        backgroundColor: 'rgba(52, 152, 219, 0.7)',
                        borderColor: 'rgba(44, 62, 80, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: (value) => this.formatCurrency(value)
                            }
                        }
                    }
                }
            });
        },

        renderPivotTable() {
            // **FUNGSI UTAMA UNTUK MEMPROSES DATA MENJADI LEBIH DETAIL**
            const pivotData = this.rawData.map(item => {
                const details = JSON.parse(item.item_details || '{}');
                
                // Ekstrak detail varian
                let varianDetails = [];
                if (details.variant && details.variant.attributes) {
                    // Pastikan attributes adalah objek
                    const attrs = (typeof details.variant.attributes === 'string') 
                                ? JSON.parse(details.variant.attributes) 
                                : details.variant.attributes;
                    for (const key in attrs) {
                        if (key !== 'id' && key !== 'stock' && key !== 'image_url') {
                            varianDetails.push(`${key}: ${attrs[key]}`);
                        }
                    }
                }
                
                // Ekstrak condiments
                const condimentDetails = (details.condiments || [])
                    .map(c => c.name)
                    .join(', ');

                // Ekstrak addons
                const addonDetails = (details.addons || [])
                    .map(a => a.name)
                    .join(', ');

                return {
                    "No Transaksi": item.transaction_code,
                    "Tanggal": new Date(item.transaction_date).toLocaleDateString('id-ID'),
                    "Jam": new Date(item.transaction_date).toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' }),
                    "Nama Tamu": item.customer_name,
                    "Brand Merk": item.brand_name,
                    "Kategori": item.category,
                    "Nama Produk": item.product_name,
                    "Varian": varianDetails.join(' | ') || '-',
                    "Condiment": condimentDetails || '-',
                    "Additional/Addon": addonDetails || '-',
                    "Kuantitas": parseInt(item.quantity, 10),
                    "Pendapatan": parseFloat(item.price_per_item) * parseInt(item.quantity, 10),
                };
            });

            $("#pivotOutput").pivotUI(pivotData, {
                rows: ["Nama Produk"],
                cols: ["Tanggal"],
                vals: ["Pendapatan"],
                aggregatorName: "Sum",
                rendererName: "Table",
                 renderers: $.extend(
                    $.pivotUtilities.renderers,
                    $.pivotUtilities.c3_renderers
                )
            });
        },

        formatCurrency(value) {
            return new Intl.NumberFormat('id-ID', {
                style: 'currency',
                currency: 'IDR',
                minimumFractionDigits: 0
            }).format(value || 0);
        }
    },
    mounted() {
        this.fetchData();
    }
}).mount('#dashboardApp');
