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

<head>
    <meta charset="UTF-8">
    <title>H990 - ĐỀ NGHỊ TẠM ỨNG</title>

    <style>
        .export-button {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 10px 24px;
            background-color: #22c55e;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: background-color 0.2s;
        }

        .export-button:hover {
            background-color: #16a34a;
        }

        .print-button {
            position: fixed;
            top: 20px;
            right: 160px;
            padding: 10px 24px;
            background-color: #14b8a6;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: background-color 0.2s;
        }

        .print-button:hover {
            background-color: #0d9488;
        }

        @media print {

            .print-button,
            .export-button {
                display: none;
            }
        }
    </style>
</head>

<body
    style="font-family: 'Times New Roman', serif; max-width: 800px; margin: 0 auto; padding: 20px; line-height: 1.4; font-size: 13pt;">

    <button onclick="printDocument()" class="action-button print-button">In nhanh</button>
    <button onclick="exportToWord()" class="export-button">Xuất ra Word</button>

    <!-- Title -->
    <table style="width: 100%; border-collapse: collapse;">
        <tr>
            <td colspan="2" style="text-align: left;">
                <p style="margin: 0;"><i>Số: <span data-field="SoTamUng"></span></i></p>
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align: right;">
                <p style="margin: 0;"><i>Hà Nội, <span data-field="NgayTamUng"></span></i></p>
            </td>
        </tr>
    </table>
    <br>
    <br>
    <table style="width: 100%; border-collapse: collapse; ">

        <tr>
            <td colspan="2" style="text-align: left;">
                <b>
                    <p style="margin: 0;"><i>Kính gửi: <span data-field="NguoiDaiDienKH"></span></i></p>
                </b>
            </td>
            <td colspan="3" style="text-align: left;">
                <b>
                    <p style="margin: 0;"><i>Chức vụ: <span data-field="ChucVuKH"></span></i></p>
                </b>
            </td>
        </tr>
    </table>
    <div style="text-align: center; margin: 20px 0;">
        <h4 style="margin: 0;"><span data-field="TenKH"></span><br>
            <span data-field="DiaChiKH"></span>
        </h4>

    </div>
    <hr>
    <div style="text-align: center; margin: 20px 0;">
        <h3 style="margin: 0;">GIẤY ĐỀ NGHỊ TẠM ỨNG
        </h3>

    </div>
    <div style="margin-top: 25px;">
        <table style="width: 100%;">
            <colgroup>
                <col style="width: 5%;">
                <col style="width: 43%;">
                <col style="width: 52%;">

            </colgroup>
            <tbody>
                <tr>
                    <td style="text-align: center;">1.</td>
                    <td style="text-align: left;">Hợp đồng số:</td>
                    <td style="text-align: right;"><span data-field="SoHopDong"></span> ký <span
                            data-field="NgayHopDong"></span></td>
                </tr>
                <tr>
                    <td style="text-align: center;">2.</td>
                    <td style="text-align: left;">Phí dịch vụ (chưa bao gồm thuế GTGT)</td>
                    <td style="text-align: right;  font-weight: bold;"><span data-field="GiaHopDongChuaVAT"></span></td>
                </tr>
                <tr>
                    <td style="text-align: center;"></td>
                    <td style="text-align: left;">Thuế GTGT <span data-field="VAT"></span>%:</td>
                    <td style="text-align: right; font-weight: bold;"><span data-field="GiaTienVAT"></span></td>
                </tr>
                <tr>
                    <td style="text-align: center;"></td>
                    <td style="text-align: left;">Tổng giá trị hợp đồng:</td>
                    <td style="text-align: right; font-weight: bold;"><span data-field="TongGiaTriHopDong"></span></td>
                </tr>
                <tr>
                    <td style="text-align: center;">3.</td>
                    <td style="text-align: left;">Lũy kế số tiền đã nhận:</td>
                    <td style="text-align: right; font-weight: bold;"><span data-field="LuyKeTamUng"></span></td>
                </tr>
                <tr>
                    <td style="text-align: center;">4.</td>
                    <td style="text-align: left;">Tổng số tiền đề nghị tạm ứng đợt này:
                    <td style="text-align: right;font-weight: bold;"><span data-field="DNTU_DotNay"></span></td>
                </tr>
                <tr>
                    <td style="text-align: center;"></td>
                    <td colspan="2" id="amount-in-words"></td>
                </tr>
                <tr>
                    <td style="text-align: center;">5.</td>
                    <td colspan="2" style="text-align: left;">Chi tiết số tiền đề nghị chuyển đợt này: Theo Điều 4 Hợp
                        đồng số <span data-field="SoHopDong"></span></td>
                </tr>
                <tr>
                    <td style="text-align: center;">6.</td>
                    <td style="text-align: left;">Số tài khoản:</td>
                    <td style="text-align: left; ">0909597168888</td>
                </tr>
                <tr>
                    <td style="text-align: center;">7.</td>
                    <td style="text-align: left;">Tên Tài khoản:</td>
                    <td style="text-align: left;"><b>CÔNG TY TNHH KIỂM TOÁN IVC</b></td>
                </tr>
                <tr>
                    <td style="text-align: center;">8.</td>
                    <td style="text-align: left;">Tại Ngân hàng:</td>
                    <td style="text-align: left;">TMCP Quân Đội – Chi nhánh Hoài Đức</td>
                </tr>
                <tr>
                    <td style="text-align: center;"></td>
                    <td style="text-align: left;"></td>
                    <td style="text-align: left;"><br>
                    </td>
                </tr>
                <tr>
                    <td style="text-align: center;"></td>
                    <td colspan="2" style="text-align: center; "><b>CÔNG TY TNHH KIỂM TOÁN IVC</b></td>
                </tr>

            </tbody>
        </table>
    </div>

    <!-- Legal basis -->

    <!-- Party A -->


    <script src="https://cdnjs.cloudflare.com/ajax/libs/docx/7.8.2/docx.js"></script>
    <script>

        document.addEventListener('contextmenu', function (e) {
            e.preventDefault();
        }, false);

        document.onkeydown = function (e) {
            if (e.keyCode == 123) {
                return false;
            }
            if (e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)) {
                return false;
            }
            if (e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)) {
                return false;
            }
            if (e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)) {
                return false;
            }
        };

        const appId = '45324891-da90-4c7e-89cb-255d02772e29';
        const accessKey = 'V2-ERBuT-OvzzD-vNJDC-ODMfm-BuZyK-7yfLe-XEsob-vFasR';
        const region = 'www';

        // Add this new function for printing
        function printDocument() {
            const printButton = document.querySelector('.print-button');
            const exportButton = document.querySelector('.export-button');

            // Hide both buttons
            if (printButton) printButton.style.display = 'none';
            if (exportButton) exportButton.style.display = 'none';

            // Print the document
            window.print();

            // Show buttons again after printing
            if (printButton) printButton.style.display = 'block';
            if (exportButton) exportButton.style.display = 'block';
        }

        // Add the export function
        function exportToWord() {
            // Lấy nội dung cần xuất (bỏ qua button xuất và scripts)
            const content = document.body.cloneNode(true);
            const exportButton = content.querySelector('.export-button');
            if (exportButton) {
                exportButton.remove();
            }

            const printButton = content.querySelector('.print-button');
            if (printButton) {
                printButton.remove();
            }

            // Tạo style inline để giữ format
            const css = `
        body { font-family: 'Times New Roman', serif; }
        h3 { margin: 0; }
        .export-button { display: none; }
    `;

            // Tạo HTML tối giản
            const html = `
        <html xmlns:o='urn:schemas-microsoft-com:office:office' 
              xmlns:w='urn:schemas-microsoft-com:office:word'>
        <head>
            <meta charset='utf-8'>
            <title>H990 - ĐỀ NGHỊ TẠM ỨNG</title>
            <style>${css}</style>
        </head>
        <body>
            ${content.innerHTML}
        </body>
        </html>
    `;

            // Tạo blob với type phù hợp cho MS Word
            const blob = new Blob([html], {
                type: 'application/msword;charset=utf-8'
            });

            // Download file
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = 'de-nghi-tam-ung.doc';
            link.click();
            URL.revokeObjectURL(link.href);
        }

        function formatVietnameseDate(dateString) {
            const date = new Date(dateString);
            return `ngày ${String(date.getDate()).padStart(2, '0')} tháng ${String(date.getMonth() + 1).padStart(2, '0')} năm ${date.getFullYear()}`;
        }

        function formatVietnameseDateshort(dateString) {
            const date = new Date(dateString);
            return `${String(date.getDate()).padStart(2, '0')}/${String(date.getMonth() + 1).padStart(2, '0')}/${date.getFullYear()}`;
        }

        function formatVietnameseCurrency(amount) {
            return new Intl.NumberFormat('vi-VN', {
                style: 'currency',
                currency: 'VND',
                minimumFractionDigits: 0,
                maximumFractionDigits: 0
            }).format(amount).replace('₫', 'VND');
        }

        function numberToVietnameseText(number) {
            const UNITS = ['', 'nghìn', 'triệu', 'tỷ', 'nghìn tỷ', 'triệu tỷ'];
            const DIGITS = ['không', 'một', 'hai', 'ba', 'bốn', 'năm', 'sáu', 'bảy', 'tám', 'chín'];

            function readThreeDigits(number) {
                const hundreds = Math.floor(number / 100);
                const tens = Math.floor((number % 100) / 10);
                const ones = number % 10;

                let result = '';

                if (hundreds > 0) {
                    result += DIGITS[hundreds] + ' trăm ';
                    if (tens === 0 && ones > 0) {
                        result += 'lẻ ';
                    }
                }

                if (tens > 1) {
                    result += DIGITS[tens] + ' mươi ';
                    if (ones === 1) {
                        result += 'mốt ';
                    } else if (ones === 5) {
                        result += 'lăm ';
                    } else if (ones > 0) {
                        result += DIGITS[ones] + ' ';
                    }
                } else if (tens === 1) {
                    result += 'mười ';
                    if (ones === 5) {
                        result += 'lăm ';
                    } else if (ones > 0) {
                        result += DIGITS[ones] + ' ';
                    }
                } else if (ones > 0) {
                    if (hundreds > 0) {
                        if (ones === 5) {
                            result += 'lăm ';
                        } else {
                            result += DIGITS[ones] + ' ';
                        }
                    } else {
                        result += DIGITS[ones] + ' ';
                    }
                }

                return result.trim();
            }

            if (!number) return 'Không đồng';

            // Format the number first
            const formattedNumber = new Intl.NumberFormat('vi-VN', {
                maximumFractionDigits: 0,
                minimumFractionDigits: 0
            }).format(number);

            // Remove all non-digit characters
            const numStr = formattedNumber.replace(/\D/g, '');
            const num = parseInt(numStr);

            if (num === 0) return 'Không đồng';

            const groups = [];
            let tempNumber = Math.abs(num);

            // Split into groups of three digits
            while (tempNumber > 0) {
                groups.push(tempNumber % 1000);
                tempNumber = Math.floor(tempNumber / 1000);
            }

            let result = '';
            let hasValue = false;

            // Process each group
            for (let i = groups.length - 1; i >= 0; i--) {
                if (groups[i] !== 0) {
                    const text = readThreeDigits(groups[i]);
                    if (text) {
                        result += text + ' ' + UNITS[i] + ' ';
                        hasValue = true;
                    }
                } else if (i % 3 === 0 && hasValue) { // Add 'tỷ' for zero groups in billions
                    result += UNITS[i] + ' ';
                }
            }

            result = result.trim() + ' đồng';
            return result.charAt(0).toUpperCase() + result.slice(1);
        }

        function getContractIdFromUrl() {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get('ID_SoTamUng');
        }

        async function fetchContractData() {
            try {
                const contractId = getContractIdFromUrl();
                if (!contractId) {
                    throw new Error('Không tìm thấy số hợp đồng trong URL');
                }

                const response = await fetch(`https://${region}.appsheet.com/api/v2/apps/${appId}/tables/Advances/Action`, {
                    method: 'POST',
                    headers: {
                        'ApplicationAccessKey': accessKey,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        Action: 'Find',
                        Properties: {},
                        Selector: `Filter(Advances, ID_SoTamUng = '${contractId}')`
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();
                const contract = data.find(c => c.ID_SoTamUng === contractId);

                if (!contract) {
                    throw new Error(`Không tìm thấy hợp đồng với số: ${contractId}`);
                }

                document.querySelectorAll('[data-field]').forEach(element => {
                    const fieldName = element.getAttribute('data-field');
                    if (contract[fieldName]) {
                        if (fieldName === 'DNTU_DotNay') {
                            element.textContent = formatVietnameseCurrency(contract[fieldName]);
                            // Thêm số tiền bằng chữ
                            const amountInWords = numberToVietnameseText(contract[fieldName]);
                            document.querySelector('#amount-in-words').innerHTML = `<td colspan="2" style="text-align: left;">50% giá trị hợp đồng và chưa bao gồm thuế GTGT<br>
                        (Bằng chữ: ${amountInWords})</td>`;
                        }


                        if (fieldName === 'NgayTamUng') {
                            element.textContent = formatVietnameseDate(contract[fieldName]);

                        } else if (fieldName === 'NgayHopDong') {
                            element.textContent = formatVietnameseDateshort(contract[fieldName]);

                        } else if (fieldName === 'TenKH' && contract['MaKH']) {
                            element.textContent = contract['TenKH'].toUpperCase();

                        } else if (fieldName === 'VAT') {
                            element.textContent = (contract[fieldName] * 100);
                        }
                        else if (fieldName === 'GiaHopDongChuaVAT' || fieldName === 'TongGiaTriHopDong' || fieldName === 'GiaTienVAT' || fieldName === 'LuyKeTamUng' || fieldName === 'DNTU_DotNay') {
                            element.textContent = formatVietnameseCurrency(contract[fieldName]);

                        } else {
                            element.textContent = contract[fieldName];
                        }
                    }
                });

            } catch (error) {
                console.error('Failed to fetch data:', error);
                document.body.innerHTML = `<div style="color: red; text-align: center; padding: 20px;">
                    Lỗi khi tải dữ liệu: ${error.message}
                </div>`;
            }
        }

        window.addEventListener('load', fetchContractData);
    </script>
</body>

</html>