// kitchen.js - VERSI LENGKAP DENGAN SEMUA PERBAIKAN

// Variabel global untuk menyimpan data preview sementara
let currentPreviewJobs = null;
let currentPreviewData = null;

// =======================================================================
// FUNGSI PREVIEW
// =======================================================================
async function print_kitchen_preview(data) {
    try {
        const jobs = await processAndGroupOrders(data, vm.mejao.tipe);
        const { printJobs, kdsJobs } = jobs;
        
        currentPreviewJobs = jobs;
        currentPreviewData = data;

        const kitchenData = JSON.parse(await ambil('kitchen', 'id', '1', '999'));
        const previewContainer = document.getElementById('preview-container');
        previewContainer.innerHTML = ''; 

        if (printJobs.size === 0 && kdsJobs.length === 0) {
            previewContainer.innerText = 'Tidak ada konfigurasi printer atau KDS yang cocok untuk item ini.';
            return;
        }

        printJobs.forEach((job, printerName) => {
            const formattedText = formatForPrinter(job.items, printerName);
            const wrapper = document.createElement('div');
            wrapper.classList.add('preview-wrapper');
            const preview = document.createElement('div');
            preview.classList.add('preview');
            preview.innerText = formattedText;
            wrapper.appendChild(preview);
            previewContainer.appendChild(wrapper);
        });

        kdsJobs.forEach(job => {
            const kdsInfo = kitchenData.find(k => k.lpt == job.kdsTargetId);
            const kdsName = kdsInfo ? kdsInfo.nama : `KDS #${job.kdsTargetId}`;
            const formattedText = formatForPrinter(job.items, kdsName);
            const wrapper = document.createElement('div');
            wrapper.classList.add('preview-wrapper');
            const preview = document.createElement('div');
            preview.classList.add('preview', 'kds-preview');
            preview.innerText = formattedText;
            wrapper.appendChild(preview);
            previewContainer.appendChild(wrapper);
        });

        const masterPrintButton = document.getElementById('masterPrintBtn');
        if (masterPrintButton) {
            masterPrintButton.onclick = () => executeAllPrintJobs(currentPreviewJobs, currentPreviewData);
        }

    } catch (error) {
        console.error("Error creating print preview:", error);
        vm.pesan('Gagal membuat pratinjau cetak.', 'error');
    }
}


// =======================================================================
// FUNGSI PENGIRIMAN DATA KE KDS (DATABASE)
// =======================================================================
function sendToKdsDatabase(kdsJobs) {
    return new Promise((resolve, reject) => {
        const formattedData = [];
        const now = getWaktu(); 
        // <<< PERBAIKAN 1: Buat ID unik untuk pengiriman ini >>>
        const uniqueSendId = Date.now().toString().slice(-6); 

        kdsJobs.forEach(job => {
            job.items.forEach(item => {
                if (!item.nomor || !item.meja || !item.user || !item.kode || !item.id) {
                    console.error("Data item utama tidak lengkap, dilewati:", item);
                    return; 
                }

                // --- 1. Proses Item UTAMA ---
                formattedData.push({
                    kds_id: job.kdsTargetId,
                    // <<< PERBAIKAN 1: Gunakan ID unik yang baru dibuat >>>
                    transaction_id: `${item.nomor}-${uniqueSendId}`,
                    item_uid: item.id,
                    parent_uid: null,
                    table_id: item.meja,
                    waiter: item.user,
                    order_time: now,
                    item_type: 'main',
                    item_id: item.kode,
                    item_name: item.name,
                    image_url: item.image || '',
                    quantity: item.quantity,
                    note: item.note || '',
                    kgroup: item.kgroup || '',
                    status: 'new',
                    brand: item.brand,
                    cab: item.cab
                });

                // --- 2. Proses Anggota PAKET (jika ada) ---
                if (item.paketItems && item.paketItems.length > 0) {
                    item.paketItems.forEach(paket => {
                        formattedData.push({
                            kds_id: job.kdsTargetId,
                            transaction_id: `${item.nomor}-${uniqueSendId}`,
                            item_uid: padNumberWithZeros(generateRandomNumber(), 10),
                            parent_uid: item.id,
                            table_id: item.meja,
                            waiter: item.user,
                            order_time: now,
                            item_type: 'paket',
                            item_id: paket.kode,
                            item_name: paket.name,
                            image_url: '',
                            quantity: paket.quantity,
                            note: '',
                            kgroup: '',
                            status: 'new',
                            brand: item.brand,
                            cab: item.cab
                        });
                    });
                }

                // --- 3. Proses TOPPING (jika ada) ---
                if (item.toppings && item.toppings.length > 0) {
                    item.toppings.forEach(toppingGroup => {
                        if (Array.isArray(toppingGroup.items)) {
                            toppingGroup.items.forEach(topping => {
                                formattedData.push({
                                    kds_id: job.kdsTargetId,
                                    transaction_id: `${item.nomor}-${uniqueSendId}`,
                                    item_uid: padNumberWithZeros(generateRandomNumber(), 10),
                                    parent_uid: item.id,
                                    table_id: item.meja,
                                    waiter: item.user,
                                    order_time: now,
                                    item_type: 'topping',
                                    item_id: topping.kode_toping || '',
                                    item_name: topping.nama_toping,
                                    image_url: '',
                                    quantity: item.quantity,
                                    note: '',
                                    kgroup: toppingGroup.Group || '',
                                    status: 'new',
                                    brand: item.brand,
                                    cab: item.cab
                                });
                            });
                        }
                    });
                }
            });
        });

        if (formattedData.length === 0) {
            return resolve("Tidak ada data valid untuk dikirim ke KDS.");
        }

        try {
            insertData('kds_orders', formattedData);
            resolve("Data berhasil dikirim ke KDS.");
        } catch (error) {
            reject("Gagal menyimpan data KDS via insertData: " + error);
        }
    });
}


// =======================================================================
// FUNGSI INTI UNTUK MEMPROSES DAN MENGELOMPOKKAN PESANAN
// =======================================================================
async function processAndGroupOrders(orderData, orderType = '1') {
    let filterColumn = 'dinein';
    if (orderType === '2') filterColumn = 'takeaway';
    if (orderType === '3') filterColumn = 'delivery';
    
    const bprinterData = JSON.parse(await xambil('bprinter', 'ya', '1', '1'));
    const kitchenData = JSON.parse(await xambil('kitchen', 'id', '1', '999'));

    const kitchenMap = new Map(kitchenData.map(k => [k.kode, { 
        name: k.nama, 
        port: `LPT${k.lpt}`, 
        windowsName: k.windows,
        lpt: k.lpt
    }]));
    
    const printJobs = new Map();
    const kdsJobsMap = new Map();

    orderData.forEach(item => {
        const rules = bprinterData.filter(bp => bp.barang === item.kode && bp[filterColumn] === '1');
        rules.forEach(rule => {
            const printerInfo = kitchenMap.get(rule.printer);
            if (printerInfo) {
                if (printerInfo.name.toUpperCase().startsWith('KDS')) {
                    const kdsId = printerInfo.lpt;
                    if (!kdsJobsMap.has(kdsId)) {
                        kdsJobsMap.set(kdsId, { kdsTargetId: kdsId, items: [] });
                    }
                    kdsJobsMap.get(kdsId).items.push(item);
                } 
                else {
                    if (!printJobs.has(printerInfo.name)) {
                        printJobs.set(printerInfo.name, { items: [], port: printerInfo.port, windowsName: printerInfo.windowsName });
                    }
                    printJobs.get(printerInfo.name).items.push(item);
                }
            }
        });
    });

    const kdsJobs = Array.from(kdsJobsMap.values());
    return { printJobs, kdsJobs };
}


// =======================================================================
// FUNGSI KOORDINATOR
// =======================================================================
async function executeAllPrintJobs(jobs, originalItems) {
    const { printJobs, kdsJobs } = jobs;
    const printButton = document.getElementById('masterPrintBtn');
    if(printButton) {
        printButton.innerText = 'Mengirim...';
    }

    const promises = [];

    Array.from(printJobs.entries()).forEach(([printerName, job]) => {
        const formattedText = formatForPrinter(job.items, printerName);
        const printerInfo = { printerName: job.windowsName, port: job.port };

        const printAndLogJob = async () => {
            try {
                const now = new Date();
                const dataLog = {
                    tanggal: now.toISOString().slice(0, 10),
                    jam: now.toTimeString().slice(0, 8),
                    tipe: 2,
                    preview: formattedText,
                    printer_info: JSON.stringify(printerInfo),
                    brand: xbrand,
                    cab: xcab
                };
                tambahjson('cetak', dataLog);
                await sendToPrintServer(job.windowsName, job.port, formattedText);
            } catch (error) {
                throw new Error(`Gagal pada printer ${printerName}: ${error}`);
            }
        };
        
        promises.push(printAndLogJob());
    });

    if (kdsJobs.length > 0) {
        promises.push(sendToKdsDatabase(kdsJobs));
    }

    try {
        await Promise.all(promises);
        handleSuccessfulPrint(originalItems);
    } catch (error) {
        vm.pesan(`Gagal mengirim pesanan: ${error}`, 'error');
        if(printButton) {
            printButton.disabled = false;
            printButton.innerText = 'Kirim Semua Pesanan';
        }
    }
}

// =======================================================================
// FUNGSI CETAK LANGSUNG
// =======================================================================
async function print_kitchen_direct(data, orderType) {
    try {
        const jobs = await processAndGroupOrders(data, orderType);
        if (jobs.printJobs.size === 0 && jobs.kdsJobs.length === 0) {
            vm.pesan('Tidak ada konfigurasi printer atau KDS yang cocok.', 'info');
            return;
        }
        await executeAllPrintJobs(jobs, data);
    } catch (error) {
        console.error('Error pada proses kirim langsung:', error);
    }
}


// =======================================================================
// FUNGSI BANTUAN
// =======================================================================

function handleSuccessfulPrint(printedItems) {
    printedItems.forEach(itemToUpdate => {
        const itemInCart = vm.pesant.find(p => p.id === itemToUpdate.id);
        if (itemInCart) {
            itemInCart.cetak = '1';
        }
    });
    vm.updatecart2();
    vm.pesan('Pesanan berhasil dikirim!', 'success');
    closePreviewModal();
}

function formatForPrinter(items, printerName) {
    if (!items || items.length === 0) return '';
    const firstItem = items[0];
    const datetime = firstItem.tglo || new Date().toISOString();
    const date = datetime.substring(0, 10);
    const time = datetime.substring(11, 19);
    
    let output = '================================\n';
    output += `${printerName}   #${firstItem.nomor}\n`;
    output += '================================\n\n';
    output += `Table  : ${firstItem.meja}/${vm.mejao.guest || ''}\n`;
    output += `Waiter : ${firstItem.user}\n`;
    output += `Time   : ${date} ${time}\n\n`;
    
    const orderTypes = { '1': 'DINE IN', '2': 'TAKE AWAY', '3': 'DELIVERY' };
    const orderTypeName = orderTypes[vm.mejao.tipe] || 'DINE IN';
    
    output += `          ** ${orderTypeName} ** \n\n`;
    output += '--------------------------------\n';
    
    items.forEach(item => {
      if (!['CASH', 'BNI'].includes(item.name)) {
        output += `${item.quantity}x ${item.name}\n`;

        // <<< PERBAIKAN 2: Tambahkan blok untuk menampilkan item paket >>>
        if (item.paketItems && item.paketItems.length > 0) {
            item.paketItems.forEach(paket => {
                output += `   + ${paket.quantity}x ${paket.name}\n`;
            });
        }
        
        if (item.toppings && item.toppings.length > 0) {
          item.toppings.forEach(topping => {
            if(topping.items) {
              topping.items.forEach(t => {
                if (t.checked) {
                  output += `   - ${t.nama_toping}\n`;
                }
              });
            }
          });
        }
        
        if (item.note && item.note !== '-') {
          output += `   * ${item.note}\n`;
        }
        output += '\n';
      }
    });
    
    output += '--------------------------------\n';
    output += `Printed: ${new Date().toLocaleString()}\n`;
    output += '================================\n';

    // <<< PERBAIKAN 3: Tambahkan 4 baris kosong dan kode auto-cut >>>
    output += '\n\n\n\n'; // 4 baris kosong
    output += '\x1d\x56\x00'; // Perintah ESC/POS untuk full cut
    
    return output;
}

function closePreviewModal() {
    const modal = document.getElementById('frame-modal');
    if (modal) modal.style.display = 'none';
}