// crud.js - Fixed Version with proper Promise handling

function hapus(table, idField, idValue) {
    return new Promise((resolve, reject) => {
        const formData = new FormData();
        formData.append('action', 'hapus');
        formData.append('table', table);
        formData.append('idField', idField);
        formData.append('idValue', idValue);
        formData.append('xbrand', xbrand);
        formData.append('xcab', xcab);
        
        fetch('crud.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(data => {
            console.log(data);
            resolve(data);
        })
        .catch(error => {
            console.error(error);
            reject(error);
        });
    });
}

function tambahjson(table, jsonData) {
    return new Promise((resolve, reject) => {
        jsonData.brand = '001';
        jsonData.cab = '002';
        
        const formData = new FormData();
        formData.append('action', 'tambahjson');
        formData.append('table', table);
        formData.append('jsonData', JSON.stringify(jsonData));
        formData.append('xbrand', xbrand);
        formData.append('xcab', xcab);
        
        fetch('crud.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(data => {
            if (data == 0) {
                vm.pesan = 'Koneksi error';
            }
            resolve(data);
        })
        .catch(error => {
            console.error(error);
            reject(error);
        });
    });
}

function rubahjson(table, jsonData, id, ff) {
    return new Promise((resolve, reject) => {
        jsonData = JSON.stringify(jsonData);
        jsonData = jsonData.replace(/"top":/g, '"`top`":').replace(/"left":/g, '"`left`":');
        jsonData = jsonData.replace(/:null/g, ':"""');
        
        const formData = new FormData();
        formData.append('action', 'rubahjson');
        formData.append('table', table);
        formData.append('jsonData', jsonData);
        formData.append('id', id);
        formData.append('ff', ff);
        formData.append('xbrand', xbrand);
        formData.append('xcab', xcab);
        
        fetch('crud.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(data => {
            resolve(data);
        })
        .catch(error => {
            console.error(error);
            reject(error);
        });
    });
}

function ambil_select(table, sql) {
    return new Promise((resolve, reject) => {
        const formData = new FormData();
        formData.append('action', 'ambil_select');
        formData.append('sql', sql);
        formData.append('xbrand', xbrand);
        formData.append('xcab', xcab);
        
        fetch('crud.php', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.text();
        })
        .then(data => {
            try {
                // Validate JSON
                JSON.parse(data);
                resolve(data);
            } catch (e) {
                console.error("Invalid JSON from server:", data);
                resolve("[]");
            }
        })
        .catch(error => {
            console.error("Fetch Error:", error);
            resolve("[]");
        });
    });
}

function ambil(table, field, value1, value2) {
    return new Promise((resolve, reject) => {
        if (!value2) { value2 = value1; }
        
        const formData = new FormData();
        formData.append('action', 'ambil');
        formData.append('table', table);
        formData.append('field', field);
        formData.append('value', JSON.stringify([value1, value2]));
        formData.append('xbrand', xbrand);
        formData.append('xcab', xcab);
        
        fetch('crud.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            resolve(data);
        })
        .catch(error => {
            console.error(error);
            resolve([]);
        });
    });
}

function xambil(table, field, value1, value2) {
    return new Promise((resolve, reject) => {
        if (!value2) { value2 = value1; }
        
        const formData = new FormData();
        formData.append('action', 'xambil');
        formData.append('table', table);
        formData.append('field', field);
        formData.append('value', JSON.stringify([value1, value2]));
        formData.append('xbrand', xbrand);
        formData.append('xcab', xcab);
        
        fetch('crud.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            resolve(data);
        })
        .catch(error => {
            console.error(error);
            resolve([]);
        });
    });
}

function ambilakhir(table, field, value1, value2) {
    return new Promise((resolve, reject) => {
        if (!value2) { value2 = value1; }
        
        const formData = new FormData();
        formData.append('action', 'ambilakhir');
        formData.append('table', table);
        formData.append('field', field);
        formData.append('value', JSON.stringify([value1, value2]));
        formData.append('xbrand', xbrand);
        formData.append('xcab', xcab);
        
        fetch('crud.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            resolve(data);
        })
        .catch(error => {
            console.error(error);
            resolve([]);
        });
    });
}

function insertData(tableName, data) {
    return new Promise((resolve, reject) => {
        // Menampilkan loader
        const loader = document.getElementById('loader');
        const message = document.getElementById('message');
        
        if (loader) loader.style.display = 'block';
        if (message) message.innerHTML = '';
        
        const requestData = {
            table: tableName,
            data: data
        };
        
        fetch('insert_data.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            if (loader) loader.style.display = 'none';
            return response.json();
        })
        .then(result => {
            if (message) {
                if (result.success) {
                    message.innerHTML = `<div class="message success">${result.message}</div>`;
                } else {
                    message.innerHTML = `<div class="message error">${result.message}</div>`;
                }
            }
            resolve(result);
        })
        .catch(error => {
            if (loader) loader.style.display = 'none';
            if (message) {
                message.innerHTML = `<div class="message error">Error: ${error.message}</div>`;
            }
            reject(error);
        });
    });
}

function transformPesanan(pesanidata) {
    let pesanix = [];
    
    pesanidata.forEach(order => {
        // Get all fields from parent order except toppings
        const parentFields = {...order};
        delete parentFields.toppings;
        
        // Add main order
        const mainOrder = {
            ...parentFields,
            sub: '0'
        };
        pesanix.push(mainOrder);
        
        // Process toppings
        if (order.toppings) {
            order.toppings.forEach(toppingGroup => {
                if (toppingGroup.items) {
                    toppingGroup.items.forEach(item => {
                        // Buat objek topping
                        const toppingOrder = {
                            ...parentFields, // Salin properti parent
                            name: item.nama_toping, // Nama topping
                            kode: item.kode_toping, // Kode topping
                            quantity: order.quantity, // Gunakan quantity dari parent
                            harga: 0, // Harga topping
                            discp: 0, // Diskon dalam persen
                            discr: 0, // Diskon nominal
                            disc: 0, // Diskon dihitung
                            service: 0, // Biaya layanan dihitung
                            pajak: 0, // Pajak dihitung
                            netto: 0, // Netto dihitung
                            jumlah: 0,
                            sub: '1' // Menandai sebagai sub-item
                        };
        
                        // Tambahkan ke array pesan
                        pesanix.push(toppingOrder);
                    });
                }
            });
        }
    });
    
    return pesanix;
}

// Global variables
let xbrand = '001';
let xcab = '002';