<!DOCTYPE html>
<html lang="vi">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

    <title>Hóa Đơn Nhiệt</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <style>
        .loading-container {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 9999;
            justify-content: center;
            align-items: center;
        }

        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #1dc071;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }


        body {
            font-family: Verdana, sans-serif;
            font-size: 12px;
            line-height: 1.2;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            background-color: #f0f0f0;
        }

        #content {
            width: 80mm;
            background-color: white;
            padding: 5mm;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        .header {
            text-align: center;
            margin-bottom: 3mm;
        }

        .company-name {
            font-size: 16px;
            font-weight: bold;
        }

        .invoice-details {
            margin-bottom: 2mm;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 10px;
        }

        th,
        td {
            border-top: 0.5px solid #ddd;
            border-bottom: 0.5px solid #ddd;
            padding: 1mm;
            text-align: left;
            line-height: 1.2;
        }

        .total {
            font-weight: bold;
            text-align: right;
            margin-top: 2mm;
        }

        .footer {
            text-align: center;
            margin-top: 3mm;
            font-size: 10px;
        }

        .top-info {
            justify-content: space-between;
            font-size: 12px;
            margin-bottom: 2mm;
        }

        #print-options {
            position: fixed;
            top: 10px;
            right: 10px;
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            gap: 10px;
            padding: 20px;
            background-color: #f5f5f5;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        #print-options select,
        #print-options input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 5px;
            font-size: 14px;
        }

        #print-options button {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        #print-options button:hover {
            background-color: #0056b3;
        }

        #print-options input::placeholder {
            color: #888;
            font-style: italic;
        }


        @media print {

            html,
            body {

                height: 100%;
                position: absolute;
            }

            #content {
                box-shadow: none;
                padding: 0;
            }

            #print-options {
                display: none;
            }
        }
    </style>
    <script>
        // Vô hiệu hóa chuột phải
        document.addEventListener('contextmenu', function (e) {
            e.preventDefault();
            return false;
        });

        // Vô hiệu hóa phím F12 và các phím tắt devtools phổ biến
        document.addEventListener('keydown', function (e) {
            // Chặn F12
            if (e.key === "F12") {
                e.preventDefault();
                return false;
            }

            // Chặn Ctrl+Shift+I / Cmd+Option+I
            if ((e.ctrlKey && e.shiftKey && e.keyCode === 73) ||
                (e.metaKey && e.altKey && e.keyCode === 73)) {
                e.preventDefault();
                return false;
            }

            // Chặn Ctrl+Shift+C / Cmd+Option+C
            if ((e.ctrlKey && e.shiftKey && e.keyCode === 67) ||
                (e.metaKey && e.altKey && e.keyCode === 67)) {
                e.preventDefault();
                return false;
            }

            // Chặn Ctrl+Shift+J / Cmd+Option+J
            if ((e.ctrlKey && e.shiftKey && e.keyCode === 74) ||
                (e.metaKey && e.altKey && e.keyCode === 74)) {
                e.preventDefault();
                return false;
            }

            // Chặn Ctrl+U (xem source)
            if (e.ctrlKey && e.keyCode === 85) {
                e.preventDefault();
                return false;
            }
        });

        // Vô hiệu hóa chọn text
        document.addEventListener('selectstart', function (e) {
            e.preventDefault();
            return false;
        });

        // Thông báo khi cố gắng copy
        document.addEventListener('copy', function (e) {
            e.preventDefault();
            alert('Không được phép sao chép nội dung này!');
            return false;
        });

        // CSS để ngăn chọn text
        document.body.style.userSelect = 'none';
        document.body.style.webkitUserSelect = 'none';
        document.body.style.msUserSelect = 'none';
        document.body.style.mozUserSelect = 'none';
    </script>
</head>

<body>

    <div id="loading-screen" class="loading-container">
        <div class="loading-spinner"></div>
    </div>
    <div id="print-options">
        <select id="paper-size" hidden>
            <option value="80mm" selected>80mm x 297mm (In nhiệt)</option>
            <option value="57mm">57mm x 297mm (In nhiệt)</option>
            <option value="76mm">76mm x 297mm (In nhiệt)</option>
            <option value="a4">A4 (210mm x 297mm)</option>
            <option value="a5">A5 (148mm x 210mm)</option>
            <option value="a6">A6 (105mm x 148mm)</option>
            <option value="letter">Letter (216mm x 279mm)</option>
            <option value="legal">Legal (216mm x 356mm)</option>
        </select>
        <input hidden type="text" id="printer-ip" placeholder="Địa chỉ IP máy in">
        <input hidden type="text" id="printer-port" placeholder="Port máy in">
        <button onclick="printInvoice()"><svg style="width:15px; height:15px; fill:#ffffff;" viewBox="0 0 512 512"
                xmlns="http://www.w3.org/2000/svg">

                <!--! Font Awesome Free 6.4.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2023 Fonticons, Inc. -->
                <path
                    d="M128 0C92.7 0 64 28.7 64 64v96h64V64H354.7L384 93.3V160h64V93.3c0-17-6.7-33.3-18.7-45.3L400 18.7C388 6.7 371.7 0 354.7 0H128zM384 352v32 64H128V384 368 352H384zm64 32h32c17.7 0 32-14.3 32-32V256c0-35.3-28.7-64-64-64H64c-35.3 0-64 28.7-64 64v96c0 17.7 14.3 32 32 32H64v64c0 35.3 28.7 64 64 64H384c35.3 0 64-28.7 64-64V384zM432 248a24 24 0 1 1 0 48 24 24 0 1 1 0-48z">
                </path>

            </svg></button>
        <button onclick="exportToPDF()"><svg style="width:15px; height:15px; fill:#ffffff;" viewBox="0 0 512 512"
                xmlns="http://www.w3.org/2000/svg">

                <!--! Font Awesome Free 6.4.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2023 Fonticons, Inc. -->
                <path
                    d="M0 64C0 28.7 28.7 0 64 0H224V128c0 17.7 14.3 32 32 32H384V304H176c-35.3 0-64 28.7-64 64V512H64c-35.3 0-64-28.7-64-64V64zm384 64H256V0L384 128zM176 352h32c30.9 0 56 25.1 56 56s-25.1 56-56 56H192v32c0 8.8-7.2 16-16 16s-16-7.2-16-16V448 368c0-8.8 7.2-16 16-16zm32 80c13.3 0 24-10.7 24-24s-10.7-24-24-24H192v48h16zm96-80h32c26.5 0 48 21.5 48 48v64c0 26.5-21.5 48-48 48H304c-8.8 0-16-7.2-16-16V368c0-8.8 7.2-16 16-16zm32 128c8.8 0 16-7.2 16-16V400c0-8.8-7.2-16-16-16H320v96h16zm80-112c0-8.8 7.2-16 16-16h48c8.8 0 16 7.2 16 16s-7.2 16-16 16H448v32h32c8.8 0 16 7.2 16 16s-7.2 16-16 16H448v48c0 8.8-7.2 16-16 16s-16-7.2-16-16V432 368z">
                </path>

            </svg></button>
    </div>
    <div id="content">
        <div class="header">


        </div>

        <div class="top-info">
            <div style="text-align: center;">
                <h2><strong>Phiếu Tính tiền</strong></h2>
                <div><strong> Số: <span id="idhoahon"></span></strong></div>
                <div><strong> Ngày: <span id="date"></span></strong></div>
            </div>


        </div>


        <div class="invoice-details">
            <div>Khách hàng: <span id="makh"></span></div>
            <div>Số điện thoại: <span id="ban"></span></div>
            <div>Địa chỉ: <span id="nhanvien"></span></div>
        </div>




        <table>
            <thead>
                <tr>
                    <th>STT.</th>
                    <th>TÊN SP</th>
                    <th>ĐVT</th>
                    <th>SL</th>

                    <th>ĐƠN GIÁ</th>
                    <th>THÀNH TIỀN</th>
                </tr>



            </thead>
            <tbody id="orderDetailsBody"></tbody>
        </table>

        <div class="total">
            Tổng tiền: <span id="tongtien"></span><br>
            <p>Giảm giá: <span id="giamGia"></span><br></p>
            Thành tiền: <span id="tongcong"></span><br>
        </div>
        <i> Ghi chú: <span id="ghiChu"></span></i>
        <div class="footer">


            <hr>
            <img id="qrthanhtoan" width="200"><br>

            <i> Quý khách vui lòng giữ lại Phiếu Tính tiền. </i><br>
            <i>Xin cảm ơn và hẹn gặp lại ! </i><br>
            <i>Rất biết ơn khi tiếp nhận phải hồi của quý khách.</i>
        </div>
    </div>
    <script>
        const APP_ID = "28fd960d-e889-4eb1-b8d2-a58dc4ba0cb7";
        const ACCESS_KEY = "V2-7OrvE-EQJtL-ZtUNd-WJIZm-kM5ZJ-lIdIT-v50aT-K0e79";
        const API_BASE_URL = "https://www.appsheet.com/api/v2/apps/";
        let COMPANY_SETTINGS = {
            companyName: '',
            address: '',
            phone: '',
            taxCode: '',
            accountName: '',
            accountNo: '',
            bankId: '',
            bankName: '',
            qrTemplate: ''
        };
    </script>

    <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['Tiengiamgia'] || 0);

            const tongCong = parseFloat(invoice['Tongtien']) - parseFloat(invoice['Tiengiamgia'] || 0);
            document.getElementById('tongcong').textContent = formatCurrency(tongCong);


            document.getElementById('ghiChu').textContent = invoice['Ghichu'] || '';
            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>
</body>

</html>