 <script>

        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.search);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
        }
        // Function to fetch settings from SETTING table
        async function fetchCompanySettings() {
            try {
                const settingsResponse = await callAppSheetApi("SETTING", "Find", {}, [{ "Id": "1" }]);

                if (!settingsResponse || settingsResponse.length === 0) {
                    throw new Error("Không tìm thấy thông tin cài đặt");
                }

                const settings = settingsResponse[0];

                // Update global settings object
                COMPANY_SETTINGS = {
                    companyName: settings['Tencty'] || '',
                    address: settings['Diachi'] || '',
                    phone: settings['Dienthoai'] || '',
                    taxCode: settings['MST'] || '',
                    accountName: settings['Hovaten'] || '',
                    accountNo: settings['Sotk'] || '',
                    bankId: settings['MaBinNganhang'] || '',
                    bankName: settings['Nganhang'] || '',
                    qrTemplate: settings['Template VietQR'] || 'compact2',
                    Logo: settings['Link']
                };

                // Update header information
                updateHeaderWithSettings();

                // Update the constants used for QR code generation
                updateQRConstants();

            } catch (error) {
                console.error("Error fetching company settings:", error);
                alert(`Lỗi khi lấy thông tin cài đặt: ${error.message}`);
            }
        }
        // Function to update header with settings
        function updateHeaderWithSettings() {
            const headerHtml = `
        <div class="company-name">
            <strong>
                <img src="${COMPANY_SETTINGS.Logo}" style="width: 40px; vertical-align: middle; margin-right: 5px;" alt="Logo">
                ${COMPANY_SETTINGS.companyName}
            </strong>
        </div>
        <div><strong>${COMPANY_SETTINGS.address}</strong></div>
        <div>SĐT: ${COMPANY_SETTINGS.phone}</div>
    `;
            document.querySelector('.header').innerHTML = headerHtml;
        }
        // Function to update QR constants
        function updateQRConstants() {
            // Update the global constants used for QR generation
            window.BANK_ID = COMPANY_SETTINGS.bankId;
            window.ACCOUNT_NO = COMPANY_SETTINGS.accountNo;
            window.ACCOUNT_NAME = COMPANY_SETTINGS.accountName;
            window.TEMPLATE = COMPANY_SETTINGS.qrTemplate;
        }
        async function callAppSheetApi(tableName, action, properties = {}, rows = []) {
            const url = `${API_BASE_URL}${APP_ID}/tables/${encodeURIComponent(tableName)}/Action`;

            let body = {
                Action: action,
                Properties: {
                    Locale: "vi-VN",
                    Timezone: "Asia/Ho_Chi_Minh"
                    ,
                    ...properties
                },
                Rows: rows
            };

            console.log('API Request:', JSON.stringify(body));  // Log request để debug

            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'ApplicationAccessKey': ACCESS_KEY
                    },
                    body: JSON.stringify(body)
                });

                if (!response.ok) {
                    const responseText = await response.text();
                    console.error('Full API Response:', responseText);
                    throw new Error(`HTTP error! status: ${response.status}, body: ${responseText}`);
                }

                return await response.json();
            } catch (error) {
                console.error(`Error calling AppSheet API for ${tableName}:`, error);
                throw error;
            }
        }
        async function getInvoiceData(invoiceId) {
            showLoading();
            try {
                console.log('Fetching invoice data for ID:', invoiceId);

                // Truy vấn bảng HOADON
                const invoiceDataResponse = await callAppSheetApi("T_HANG_BAN", "Find", {}, [{ "IDT": invoiceId }]);

                if (!invoiceDataResponse || invoiceDataResponse.length === 0) {
                    throw new Error("Không tìm thấy hóa đơn");
                }

                const invoiceData = invoiceDataResponse[0];
                console.log('Invoice Data:', invoiceData);

                // Truy vấn bảng HOADONDETAIL
                const invoiceDetailsResponse = await callAppSheetApi("CT_HANG_BAN", "Find", {
                    Selector: `Filter(CT_HANG_BAN, [ID_TO] = "${invoiceId}")`
                }, []);

                console.log('Invoice Details:', invoiceDetailsResponse);

                updateUI(invoiceData, invoiceDetailsResponse);
            } catch (error) {
                console.error("Error in getInvoiceData:", error);
                alert(`Lỗi khi lấy dữ liệu hóa đơn: ${error.message}`);
            } finally {
                hideLoading();
            }
        }
        function updateUI(invoice, details) {
            // Cập nhật thông tin hóa đơn
            document.getElementById('idhoahon').textContent = invoice.IDT || '';
            document.getElementById('date').textContent = invoice.Ngay ? new Date(invoice.Ngay).toLocaleDateString('en-GB', {
                day: '2-digit',
                month: '2-digit',
                year: 'numeric'
            }).split('/').join('/') : '';
            document.getElementById('makh').textContent = invoice['Tenkh'] || '';
            document.getElementById('ban').textContent = invoice.Sodt || '';
            document.getElementById('nhanvien').textContent = invoice['Diachi'] || '';
            // Cập nhật bảng chi tiết sản phẩm
            const tableBody = document.getElementById('orderDetailsBody');
            tableBody.innerHTML = '';
            details.forEach((item, index) => {
                const row = tableBody.insertRow();
                row.innerHTML = `
            <td>${index + 1}</td>
            <td>${item['Tenhangban'] || ''}</td>
             <td>${item['Dvtinh'] || ''}</td>
            <td>${item['Soluong'] || ''}</td>
            <td style="text-align: right;">${formatCurrency(item['Dongia'])}</td>
           <td style="text-align: right;">${formatCurrency(item['Thanhtien'])}</td>
        `;
            });

            // Cập nhật tổng tiền và các thông tin khác
            document.getElementById('tongtien').textContent = formatCurrency(invoice['Tongtien']);
            document.getElementById('giamGia').textContent = formatCurrency(invoice['Giảm giá'] || 0);

            const tongCong = parseFloat(invoice['Tongtien']) - parseFloat(invoice['Giảm giá'] || 0);
            document.getElementById('tongcong').textContent = formatCurrency(tongCong);


            document.getElementById('ghiChu').textContent = invoice['Ghi chú'] || '';
            updateQRCode();
            // Thêm thông tin nhân viên nếu cần
            // document.getElementById('nhanvien').textContent = invoice['Nhân viên'] || '';
        }
        function showLoading() {
            document.getElementById('loading-screen').style.display = 'flex';
        }

        function hideLoading() {
            document.getElementById('loading-screen').style.display = 'none';
        }

        function generateVietQRUrl(amount, thongtin) {
            const encodedName = encodeURIComponent(COMPANY_SETTINGS.accountName);
            const thongtin1 = encodeURIComponent("Thanh toan hoa don so " + thongtin);
            const encodedAmount = encodeURIComponent(amount.toString());

            return `https://img.vietqr.io/image/${COMPANY_SETTINGS.bankId}-${COMPANY_SETTINGS.accountNo}-${COMPANY_SETTINGS.qrTemplate}.png?amount=${encodedAmount}&addInfo=${thongtin1}&accountName=${encodedName}`;
        }
        function updateQRCode() {
            const tongCongElement = document.getElementById('tongcong');
            const qrElement = document.getElementById('qrthanhtoan');
            const thongtin = document.getElementById('idhoahon').textContent;
            if (tongCongElement && qrElement) {
                const amount = parseFloat(tongCongElement.textContent.replace(/[^\d]/g, ''));
                const qrUrl = generateVietQRUrl(amount, thongtin);
                qrElement.src = qrUrl;
            }
        }
        function getPaperSizeInMM(size) {
            switch (size) {
                case '80mm':
                    return [80, 297];
                case '57mm':
                    return [57, 297];
                case '76mm':
                    return [76, 297];
                case 'a4':
                    return [210, 297];
                case 'a5':
                    return [148, 210];
                case 'a6':
                    return [105, 148];
                case 'letter':
                    return [216, 279];
                case 'legal':
                    return [216, 356];
                default:
                    return [80, 297];
            }
        }
        function calculatePageHeight() {
            const content = document.getElementById('content');
            return content.scrollHeight;
        }
        function applyPaperSize(size) {
            const [width, height] = getPaperSizeInMM(size);
            const contentHeight = calculatePageHeight();
            var style = document.createElement('style');
            style.innerHTML = `@page { size: ${width}mm ${height}mm; } #content { width: ${width - 5}mm; height: ${contentHeight}px; }`;
            var oldStyle = document.getElementById('print-style');
            if (oldStyle) {
                oldStyle.remove();
            }
            style.id = 'print-style';
            document.head.appendChild(style);
        }
        document.getElementById('paper-size').addEventListener('change', function () {
            applyPaperSize(this.value);
        });

        function printInvoice() {
            var selectedSize = document.getElementById('paper-size').value;
            var printerIP = document.getElementById('printer-ip').value;
            var printerPort = document.getElementById('printer-port').value;

            applyPaperSize(selectedSize);

            if (printerIP && printerPort) {
                // Gửi yêu cầu in đến máy chủ
                fetch(`http://${printerIP}:${printerPort}/api/print`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        content: document.getElementById('content').innerHTML
                    }),
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('In thành công qua máy in: ' + printerIP + ':' + printerPort);
                        } else {
                            alert('Lỗi khi in qua mạng. Chuyển sang in mặc định.');
                            window.print();
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('Lỗi khi in qua mạng. Chuyển sang in mặc định.');
                        window.print();
                    });
            } else {
                // In mặc định nếu không có IP hoặc port
                window.print();
            }
        }

        function formatCurrency(value) {
            if (!value) return '0 ₫';
            return new Intl.NumberFormat('vi-VN', { style: 'currency', currency: 'VND' }).format(value);
        }
        function exportToPDF() {
            var element = document.getElementById('content');
            var selectedSize = document.getElementById('paper-size').value;
            var [width, _] = getPaperSizeInMM(selectedSize);
            var height = calculatePageHeight();

            html2canvas(element, {
                scale: 5,
                backgroundColor: '#ffffff',
                logging: false,
                useCORS: true,
                windowWidth: element.offsetWidth,
                height: height
            }).then(canvas => {
                var imgData = canvas.toDataURL('image/png', 1.0);
                var pdf = new jspdf.jsPDF({
                    orientation: 'portrait',
                    unit: 'px',
                    format: [element.offsetWidth * 5, height * 5]
                });

                pdf.addImage(imgData, 'PNG', 0, 0, element.offsetWidth * 5, height * 5, '', 'FAST');
                pdf.save("hoa-don.pdf");
            });
        }
        // Update the DOMContentLoaded event listener to include settings fetch
        document.addEventListener('DOMContentLoaded', async () => {
            const urlParams = new URLSearchParams(window.location.search);
            const invoiceId = urlParams.get('IDHOADON');
            console.log('Invoice ID from URL:', invoiceId);

            try {
                // First fetch settings
                await fetchCompanySettings();

                // Then proceed with invoice data if ID exists
                if (invoiceId) {
                    await getInvoiceData(invoiceId);
                    updateQRCode();
                } else {
                    alert('Vui lòng cung cấp ID hóa đơn trong URL (ví dụ: ?IDHOADON=HD001)');
                }
            } catch (error) {
                console.error('Error during initialization:', error);
                alert('Có lỗi xảy ra khi khởi tạo ứng dụng');
            }
        });
    </script>