const { createApp } = Vue;

createApp({
    data() {
        return {
            products: [],
            currentProduct: this.getEmptyProduct(),
            isFormVisible: false,
            formMode: 'tambah', // 'tambah' atau 'edit'
            isLoading: false,
        };
    },
    methods: {
        // --- Fungsi Utama untuk Mengambil Data ---
        async fetchProducts() {
            this.isLoading = true;
            try {
                // Mengambil semua produk dengan menyortir berdasarkan ID
                const response = await ambil_select("SELECT * FROM products ORDER BY id ASC");
                if (response && Array.isArray(response)) {
                    this.products = response;
                } else {
                    alert('Gagal mengambil data produk atau format tidak sesuai.');
                    this.products = [];
                }
            } catch (error) {
                console.error("Error fetching products:", error);
                alert(`Terjadi kesalahan saat mengambil data produk: ${error.message}`);
            } finally {
                this.isLoading = false;
            }
        },

        // --- Fungsi untuk Mengelola Form ---
        showAddForm() {
            this.currentProduct = this.getEmptyProduct();
            this.formMode = 'tambah';
            this.isFormVisible = true;
        },

        async showEditForm(product) {
            this.isLoading = true;
            this.formMode = 'edit';
            try {
                // Ambil data produk utama
                const mainProductData = (await ambil('products', 'id', product.id))[0];
                if (!mainProductData) {
                    throw new Error("Produk tidak ditemukan.");
                }

                // Ambil data anak (variants, addons, condiment groups & options)
                const variants = await ambil('product_variants', 'product_id', product.id);
                const addons = await ambil('product_addons', 'product_id', product.id);
                const condiment_groups = await ambil('condiment_groups', 'product_id', product.id);

                // Ambil options untuk setiap group
                for (const group of condiment_groups) {
                    group.options = await ambil('condiment_options', 'group_id', group.id);
                }

                // Gabungkan semua data ke dalam currentProduct
                this.currentProduct = {
                    ...mainProductData,
                    is_best_seller: Boolean(mainProductData.is_best_seller),
                    variants: variants || [],
                    addons: addons || [],
                    condiment_groups: condiment_groups || [],
                };

                this.isFormVisible = true;
            } catch (error) {
                console.error("Error fetching product details:", error);
                alert(`Gagal memuat detail produk: ${error.message}`);
            } finally {
                this.isLoading = false;
            }
        },

        closeForm() {
            this.isFormVisible = false;
        },

        getEmptyProduct() {
            return {
                id: null,
                name: '',
                brand_name: '',
                category: '',
                base_price: 0,
                description: '',
                is_best_seller: false,
                variants: [],
                addons: [],
                condiment_groups: [],
            };
        },

        // --- Fungsi CRUD (Create, Update, Delete) ---
        async saveProduct() {
            this.isLoading = true;
            try {
                if (this.formMode === 'tambah') {
                    await this.createProduct();
                } else {
                    await this.updateProduct();
                }
                await this.fetchProducts(); // Refresh list
                this.closeForm();
                alert(`Produk berhasil ${this.formMode === 'tambah' ? 'ditambahkan' : 'diperbarui'}!`);
            } catch (error) {
                console.error("Error saving product:", error);
                alert(`Gagal menyimpan produk: ${error.message}`);
            } finally {
                this.isLoading = false;
            }
        },

        async createProduct() {
            const productData = { ...this.currentProduct };
            // Hapus data relasi sebelum insert ke tabel master
            delete productData.variants;
            delete productData.addons;
            delete productData.condiment_groups;
            
            productData.is_best_seller = productData.is_best_seller ? 1 : 0;

            const response = await tambahjson('products', productData);
            if (!response.success) throw new Error(response.error || 'Gagal menambahkan produk utama.');

            const newProductId = response.id;
            
            // Simpan data anak dengan ID produk yang baru
            await this.saveChildData(newProductId);
        },

        async updateProduct() {
            const productData = { ...this.currentProduct };
            const productId = productData.id;

            // Hapus data relasi sebelum update ke tabel master
            delete productData.variants;
            delete productData.addons;
            delete productData.condiment_groups;

            productData.is_best_seller = productData.is_best_seller ? 1 : 0;

            const response = await rubahjson('products', productData, productId);
            if (!response.success) throw new Error(response.error || 'Gagal memperbarui produk utama.');

            // Hapus semua data anak yang lama
            await hapus('product_variants', 'product_id', productId);
            await hapus('product_addons', 'product_id', productId);
            await hapus('condiment_groups', 'product_id', productId); // Cascade delete akan menghapus options

            // Simpan kembali data anak dari form
            await this.saveChildData(productId);
        },
        
        async saveChildData(productId) {
            // Save variants
            for (const variant of this.currentProduct.variants) {
                // Pastikan atribut adalah JSON string yang valid
                try {
                    JSON.parse(variant.attributes);
                } catch (e) {
                    variant.attributes = '{}'; // Default ke objek kosong jika tidak valid
                }
                await tambahjson('product_variants', { ...variant, product_id: productId });
            }
            // Save addons
            for (const addon of this.currentProduct.addons) {
                await tambahjson('product_addons', { ...addon, product_id: productId });
            }
            // Save condiment groups and their options
            for (const group of this.currentProduct.condiment_groups) {
                const groupData = { ...group, product_id: productId };
                delete groupData.options;
                groupData.is_required = groupData.is_required ? 1 : 0;

                const groupResponse = await tambahjson('condiment_groups', groupData);
                if (!groupResponse.success) continue; // Lanjut ke grup berikutnya jika gagal

                const newGroupId = groupResponse.id;
                for (const option of group.options) {
                    await tambahjson('condiment_options', { ...option, group_id: newGroupId });
                }
            }
        },

        async deleteProduct(productId) {
            if (!confirm(`Apakah Anda yakin ingin menghapus produk dengan ID ${productId}? Semua data terkait (varian, addon, dll) juga akan dihapus.`)) {
                return;
            }
            this.isLoading = true;
            try {
                const response = await hapus('products', 'id', productId);
                if (!response.success) {
                    throw new Error(response.error || 'Gagal menghapus produk.');
                }
                await this.fetchProducts(); // Refresh list
                alert('Produk berhasil dihapus.');
            } catch (error) {
                console.error("Error deleting product:", error);
                alert(`Gagal menghapus produk: ${error.message}`);
            } finally {
                this.isLoading = false;
            }
        },

        // --- Helper untuk Form Dinamis ---
        addVariant() { this.currentProduct.variants.push({ attributes: '{"key":"value"}', stock: 0, image_url: '' }); },
        removeVariant(index) { this.currentProduct.variants.splice(index, 1); },

        addAddon() { this.currentProduct.addons.push({ name: '', price: 0 }); },
        removeAddon(index) { this.currentProduct.addons.splice(index, 1); },

        addCondimentGroup() { this.currentProduct.condiment_groups.push({ title: '', type: 'radio', is_required: false, options: [] }); },
        removeCondimentGroup(index) { this.currentProduct.condiment_groups.splice(index, 1); },

        addCondimentOption(groupIndex) { this.currentProduct.condiment_groups[groupIndex].options.push({ name: '', price: 0 }); },
        removeCondimentOption(groupIndex, optionIndex) { this.currentProduct.condiment_groups[groupIndex].options.splice(optionIndex, 1); },

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