// =======================================================================
// FUNGSI BANTUAN UNTUK FORMATTING TEKS
// =======================================================================
function formatCurrency(amount) {
    // Memastikan pembulatan dan format yang benar
    const number = Math.round(Number(amount));
    return number.toLocaleString('id-ID');
}
function centerText(text, width) {
    const padding = Math.max(0, width - text.length);
    const leftPad = Math.floor(padding / 2);
    const rightPad = padding - leftPad;
    return ' '.repeat(leftPad) + text + ' '.repeat(rightPad);
}
function alignLeftRight(left, right, width) {
    const padding = Math.max(0, width - left.length - right.length);
    return left + ' '.repeat(padding) + right;
}
function alignColumns(cols, widths) {
    let line = '';
    for (let i = 0; i < cols.length; i++) {
        const text = cols[i] || '';
        const width = widths[i];
        if (i === 0) {
            // Kolom pertama rata kiri
            line += text.padEnd(width);
        } else {
            // Kolom berikutnya rata kanan
            line += text.padStart(width);
        }
    }
    return line;
}

// =======================================================================
// FUNGSI UTAMA UNTUK MEMBUAT STRUK PEMBAYARAN
// =======================================================================
function generateBill(data) {
    const width = 42;
    // Asumsi 'vm' dan 'vm.pos' tersedia di scope global
    const pos = vm.pos; 
    const mejao = vm.mejao; // Ambil data meja aktif dari vm
    let bill = [];
    const firstItem = data.find(item => item.tglo);

    // --- HEADER ---
    bill.push(centerText(`~~~ ${pos.nama || 'Nama Resto Anda'} ~~~`, width));
    bill.push(centerText(pos.alamat || 'Slogan Resto Anda', width));
    bill.push(centerText(pos.alamat2 || 'Alamat Resto Anda', width));
    bill.push(centerText(`Telp: ${pos.kota || 'Telepon Anda'}`, width));
    bill.push(''.padStart(width, '='));

    // --- INFO TRANSAKSI ---
    const dateTime = firstItem.tglo;
    const date = dateTime ? dateTime.substring(0, 10) : 'N/A';
    const time = dateTime ? dateTime.substring(11, 16) : 'N/A';
    
    bill.push(alignLeftRight(`No: ${firstItem.nomor}`, `Table: ${firstItem.meja}`, width));
    bill.push(alignLeftRight(`Date: ${date}`, `Time: ${time}`, width));
    bill.push(alignLeftRight(`Cashier: ${firstItem.user}`, '', width));
    bill.push(''.padStart(width, '-'));

    // --- FILTER & PROSES ITEM MENU ---
    const menuItems = data.filter(item => 
        (item.payment === '' || item.payment === null || item.payment === undefined) &&
        (item.sub !== '1') 
    );    
    
    let subtotal = 0;
    let serviceCharge = 0;
    let tax = 0;

    menuItems.forEach(mainItem => {
        subtotal += mainItem.jumlah || 0;
        serviceCharge += mainItem.service || 0;
        tax += mainItem.pajak || 0;
        
        bill.push(alignColumns([
            `${mainItem.quantity} ${mainItem.name}`,
            formatCurrency(mainItem.jumlah)
        ], [32, 10]));

        const subItems = data.filter(item => 
            item.sub === '1' && (item.nocard === mainItem.kode || item.id === mainItem.id)
        );
        subItems.forEach(subItem => {
            if ((subItem.price > 0 || subItem.harga > 0) || (subItem.name && subItem.name.includes('Paket'))) {
                bill.push(alignColumns([
                    `  - ${subItem.name}`,
                    subItem.price > 0 ? formatCurrency(subItem.price * subItem.quantity) : ''
                ], [32, 10]));
            } else {
                 bill.push(`  - ${subItem.name}`);
            }
        });
    });
    bill.push(''.padStart(width, '-'));

    const billDiscountItem = data.find(item => item.payment === '06' && item.harga < 0);
    const totalDiscount = billDiscountItem ? Math.abs(billDiscountItem.harga) : 0; 
    const discountLabel = billDiscountItem ? billDiscountItem.name : 'Total Discount Item';

    // --- BAGIAN TOTAL ---
    const finalSubtotal = subtotal;
    const finalService = serviceCharge;
    const finalTax = tax;
    const grandTotal = finalSubtotal - totalDiscount + finalService + finalTax;

    bill.push(alignLeftRight('Subtotal', formatCurrency(finalSubtotal), width));
    if (totalDiscount > 0) {
        bill.push(alignLeftRight(discountLabel, `-${formatCurrency(totalDiscount)}`, width));
    }
    bill.push(alignLeftRight(`Service Charge (${pos.service || 0}%)`, formatCurrency(finalService), width));
    bill.push(alignLeftRight(`Tax (${pos.pajak || 0}%)`, formatCurrency(finalTax), width));
    bill.push(''.padStart(width, '='));
    bill.push(alignLeftRight('TOTAL', formatCurrency(grandTotal), width));

    // --- PEMBAYARAN ---
    const payments = data.filter(item => item.payment && item.payment !== '06' && item.payment !== 'x' );
    let totalPayment = 0;
    
    payments.forEach(p => {
        totalPayment += p.harga;
        bill.push(alignLeftRight(p.name.toUpperCase(), formatCurrency(p.harga), width));
    });

    const change = totalPayment - grandTotal;
    bill.push(alignLeftRight('CHANGE', formatCurrency(change), width));
    bill.push(''.padStart(width, '='));
   
    // --- AWAL MODIFIKASI ---
    // Tambahkan blok informasi member jika ada member di meja aktif
    if (mejao && mejao.nama_member) {
        const memberPointRule = parseFloat(pos.member_point) || 0;
        let poinDidapat = 0;
        
        if (memberPointRule > 0) {
            poinDidapat = Math.floor(grandTotal / memberPointRule);
        }

        const poinAwal = parseInt(mejao.point) || 0;
        const poinAkhir = poinAwal + poinDidapat;

        bill.push(alignLeftRight('Member', `: ${mejao.nama_member}`, width));
        bill.push(alignLeftRight('Poin Awal', `: ${formatCurrency(poinAwal)}`, width));
        bill.push(alignLeftRight('Poin Didapat', `: ${formatCurrency(poinDidapat)}`, width));
        bill.push(alignLeftRight('Poin Akhir', `: ${formatCurrency(poinAkhir)}`, width));
        bill.push(''.padStart(width, '='));
    }
    // --- AKHIR MODIFIKASI ---

    // --- FOOTER & QR CODE ---
    const qrCodeData = 'https://bepos.my.id/mobile/';
    const qrCodeSize = '\x08';
    const qrCodeCommands = [
        '\x1B\x61\x00', 
        '\x1B\x61\x01', 
        '\x1D\x28\x6B\x04\x00\x31\x41\x32\x00',
        `\x1D\x28\x6B\x03\x00\x31\x43${qrCodeSize}`,
        '\x1D\x28\x6B\x03\x00\x31\x45\x30',
        `\x1D\x28\x6B${String.fromCharCode((qrCodeData.length + 3) % 256)}${String.fromCharCode(Math.floor((qrCodeData.length + 3) / 256))}\x31\x50\x30${qrCodeData}`,
        '\x1D\x28\x6B\x03\x00\x31\x51\x30',
        '\x1B\x61\x00' 
    ];

    bill.push(centerText('Follow Kami & Share Momenmu!', width));
    bill.push(centerText(pos.medsos_resto || '@akunmedsos', width));
    bill.push(qrCodeCommands.join(''));
    bill.push(centerText('SCAN DI SINI UNTUK', width));
    bill.push(centerText('REVIEW & PROMO', width));
    bill.push(centerText('Terima Kasih Atas Kunjungan Anda!', width));

    return bill.join('\n');
}