
function hapus(table, idField, idValue) {
    let result = 0;

    $.ajax({
        type: "POST",
        async: false,
        url: "crud.php",
        data: {
            action: 'hapus',
            table: table,
            idField: idField,
            idValue: idValue,
            xbrand : xbrand,
            xcab   : xcab

        },
        success: function(response) {
            console.log(response);
            result = response;
        },
        error: function(error) {
            console.error(error);
        }
    });

    return result;
}

function tambahjson(table, jsonData) {
    let result = 0;
    jsonData.brand=xbrand;
    jsonData.cab=xcab;
    jsonData = JSON.stringify(jsonData);

    $.ajax({
        type: "POST",
        async: false,
        url: "crud.php",
        data: {
            action: 'tambahjson',
            table: table,
            jsonData: jsonData,
            xbrand : xbrand,
            xcab   : xcab

        },

        success: function(response) {
            // console.log(response);
            result = response;
        },
        error: function(error) {
            console.error(error);
        }
    });
    if ( result==0 ) {
        vm.pesan='Koneksi error '
    };

    return result;
}


function rubahjson(table, jsonData,id,ff) {
    // if (umeja) {
    // alert(999+' '+table+' '+JSON.stringify(jsonData)+' '+id);
    // return;
    // };

    let result = 0;
    jsonData = JSON.stringify(jsonData);
    jsonData = jsonData.replace(/"top":/g, '"`top`":').replace(/"left":/g, '"`left`":');


    jsonData = jsonData.replace(/:null/g, ':""');
    
    
    // jsonData = jsonData.replace(/:null/g, ':""'); // Mengganti semua `null` menjadi `""`
    // jsonData = jsonData.replace(/"\\""/g, '""');  // Memperbaiki escape karakter
           
    $.ajax({
        type: "POST",
        async: false,
        url: "crud.php",
        data: {
            action: 'rubahjson',
            table: table,
            jsonData: jsonData,
            id:id,
            ff:ff,
            xbrand : xbrand,
            xcab   : xcab

        },

        success: function(response) {
            result = response;
        },
        error: function(error) {
            console.error(error);
        }
    });

    return result;
}

function ambil_select(table, sql) {
    let result = "[]";
    $.ajax({
        type: "POST",
        async: false,
        url: "crud.php",
        data: {
            action: 'ambil_select',
            sql: sql,
            xbrand: xbrand,
            xcab: xcab
        },
        success: function(response) {
            try {
                // Pastikan response adalah JSON valid
                JSON.parse(response);
                result = response;
            } catch (e) {
                console.error("Invalid JSON from server:", response);
                result = "[]";
            }
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", error);
            console.log("Response:", xhr.responseText);
            result = "[]";
        }
    });
    return result;
}

function yambil_select(table, sql) {
    
    let result = "[]";
    
    $.ajax({
        type: "POST",
        async: false,
        url: "crud.php",
        data: {
            action: 'yambil_select',
            sql: sql,
            xbrand: '',
            xcab: ''
        },
        success: function(response) {
            try {
                // Pastikan response adalah JSON valid
                JSON.parse(response);
                result = response;
            } catch (e) {
                console.error("Invalid JSON from server:", response);
                result = "[]";
            }
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", error);
            console.log("Response:", xhr.responseText);
            result = "[]";
        }
    });
    return result;
}

function ambil(table, field, value1, value2) {
    
    let result = [];
    if (!value2) {value2=value1};
        $.ajax({
        type: "POST",
        async: false,
        url: "crud.php",
        data: {
            action: 'ambil',
            table: table,
            field: field,
            value: [value1, value2],
            xbrand : xbrand,
            xcab   : xcab
        },
        success: function(response) {
            // console.log(response);
            result = response;
        },
        error: function(error) {
            console.error(error);
        }
    });

    return result;
}

function xambil(table, field, value1, value2) {
    
    let result = [];
    if (!value2) {value2=value1};
        $.ajax({
        type: "POST",
        async: false,
        url: "crud.php",
        data: {
            action: 'xambil',
            table: table,
            field: field,
            value: [value1, value2],
            xbrand : xbrand,
            xcab   : xcab
        },
        success: function(response) {
            // console.log(response);
            result = response;
        },
        error: function(error) {
            console.error(error);
        }
    });

    return result;
}

function ambilakhir(table, field, value1, value2) {
    let result = [];
    if (!value2) {value2=value1};
        $.ajax({
        type: "POST",
        async: false,
        url: "crud.php",
        data: {
            action: 'ambilakhir',
            table: table,
            field: field,
            value: [value1, value2],
            xbrand : xbrand,
            xcab   : xcab

        },
        success: function(response) {
            // console.log(response);
            result = response;
        },
        error: function(error) {
            console.error(error);
        }
    });

    return result;
}

function insertData(tableName, data) {
    // Menampilkan loader
    document.getElementById('loader').style.display = 'block';
    document.getElementById('message').innerHTML = '';

    // Membuat data permintaan
    const requestData = {
        table: tableName,
        data: data
    };
    // Mengirim data ke server menggunakan fetch
    fetch('insert_data.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestData)
    })
        .then(response => {
            // Menyembunyikan loader
            document.getElementById('loader').style.display = 'none';

            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            // return response.json();
        })
        .then(result => {
            // Menampilkan pesan sukses atau error
            if (result.success) {
        
                document.getElementById('message').innerHTML = 
                    `<div class="message success">${result.message}</div>`;
            } else {
                document.getElementById('message').innerHTML = 
                    `<div class="message error">${result.message}</div>`;
            }
        })
        .catch(error => {
            // Menyembunyikan loader dan menampilkan pesan error
            document.getElementById('loader').style.display = 'none';
            document.getElementById('message').innerHTML = 
                `<div class="message error">Error: ${error.message}</div>`;
        });
}


function transformPesanan(pesanidata) {
    // alert('crud  '+JSON.stringify(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 => {
                        // // Pastikan nilai default untuk diskon dan lainnya
                        // const discp = parseFloat(order.diskp) || 0;
                        // const serv = parseFloat(order.serv) || 0;
                        // const ppn = parseFloat(order.ppn) || 0;
                        // const quantity = parseInt(item.quantity, 10) || 0;
                        // const harga = parseFloat(item.harga) || 0;
        
                        // // Perhitungan yang aman
                        // const disc = quantity * harga * discp / 100;
                        // const service = quantity * harga * (1 - discp / 100) * serv / 100;
                        // const pajak = quantity * harga * (1 - discp / 100) * (1 + serv / 100) * ppn / 100;
                        // const netto = quantity * harga * (1 - discp / 100) * (1 + serv / 100) * (1 + ppn / 100);
        
                        // 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);
                    });
                }
            });
        }


    });
    // alert('pesani '+JSON.stringify(pesanix));
    return pesanix;
}

