  <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>
        <div class="top-info">
            <div style="text-align: center;">
                <h2><strong>PHIẾU GỬI HÀNG</strong></h2>
            </div>
            <div style="text-align: left;"> Người gửi: <span >ĐỖ THU HƯỜNG</span></div>
            <div style="text-align: left;">ĐỊA CHỈ: <span >${COMPANY_SETTINGS.address}</span></div>
        </div>
    `;
            document.querySelector('.header').innerHTML = headerHtml;
            document.getElementById('nguoinhan').textContent = getUrlParameter('nguoinhan');
            document.getElementById('sodienthoai').textContent = getUrlParameter('sodienthoai');
            document.getElementById('diachinguoinhan').textContent = getUrlParameter('diachinguoinhan');
            document.getElementById('ghichu').textContent = getUrlParameter('ghichu');

            // Lấy trạng thái từ URL
            const trangthai = getUrlParameter('trangthai');

            // Điều kiện ẩn hiện phần Thu hộ
            const thuHoElement = document.querySelector('.invoice-details div:last-child');
            if (trangthai === "Đã thanh toán") {
                thuHoElement.style.display = 'none';
            } else {
                document.getElementById('sotien').textContent = getUrlParameter('sotien');
            }
        }
        // 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;
            }
        }

        function updateUI(invoice, details) {
            // Cập nhật thông tin hóa đơn
            document.getElementById('diachi').textContent = COMPANY_SETTINGS.address || '';






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

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



        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 [148, 148];
            }
        }
        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

            } catch (error) {
                console.error('Error during initialization:', error);
                alert('Có lỗi xảy ra khi khởi tạo ứng dụng');
            }
        });
    </script>