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

<head>
    <meta charset="UTF-8">
    <title>Phiếu Thu Thông tư 200</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="action-buttons">
        <input type="file" id="excelFile" accept=".xlsx, .xls" style="display: none;">
        <button class="action-button" onclick="document.getElementById('excelFile').click()">Import Excel</button>

        <button class="action-button" onclick="printDocument()">In Ngay</button>
        <button class="action-button" hidden onclick="exportToPDFA5NGANG()">Xuất PDF A5 khổ ngang</button>
        <button class="action-button" hidden onclick="exportToPDF()">Xuất PDF A4 khổ dọc</button>
        <button class="action-button" onclick="showGuide()">Hướng dẫn</button>
    </div>
    <div class="container">
        <div class="header">
            <div class="header-row">
                <div class="header-left">
                    Đơn vị:...................</br>
                    Địa chỉ:.................</br>
                </div>
                <div class="header-right" style="text-align: center;">
                    <b>Mẫu số 01 - TT</b></br>
                    (Ban hành theo Thông tư số: 200/2014/TT-BTC</br>
                    ngày 22/12/2014 của BTC)
                </div>
            </div>
        </div>

        <div class="title-section">
            <div class="info-right">
                Quyển số:.............</br>
                Số:...................</br>
                Nợ:...................</br>
                Có:....................</br>
            </div>
            <div class="title-center">
                <h2>PHIẾU THU</h2>
            </div>
            <div class="info-date">
                <i>Ngày .....tháng .....năm .......</i>
            </div>
        </div>

        <div class="form-content">
            <div class="form-row">
                Họ và tên người nộp tiền:................................................................
            </div>
            <div class="form-row">
                Địa chỉ:................................................................................
            </div>
            <div class="form-row">
                Lý do nộp:..............................................................................
            </div>
            <div class="form-row">
                Số tiền:.....................................(Viết bằng chữ):..............................
            </div>
            <div class="form-row">
                Kèm theo ............................ Chứng từ gốc
            </div>
        </div>

        <div class="date-line" style="text-align: right; margin: 20px 0;">
            Ngày ...... tháng ...... năm .....
        </div>

        <div class="signatures">
            <div class="signature-block">
                <div>Giám đốc</div>
                <div>(Ký, họ tên, đóng dấu)</div>
            </div>
            <div class="signature-block">
                <div>Kế toán trưởng</div>
                <div>(Ký, họ tên)</div>
            </div>
            <div class="signature-block">
                <div>Thủ quỹ</div>
                <div>(Ký, họ tên)</div>
            </div>
            <div class="signature-block">
                <div>Người lập phiếu</div>
                <div>(Ký, họ tên)</div>
            </div>
            <div class="signature-block">
                <div>Người nộp tiền</div>
                <div>(Ký, họ tên)</div>
            </div>
        </div>
        <br>
        <br>

        <div class="bottom-section">
            <div>Đã nhận đủ số tiền (viết bằng chữ) :...........................................................</div>
            <div>+ Tỷ giá ngoại tệ (vàng bạc, đá quý):........................................................</div>
            <div>+ Số tiền quy đổi:...........................................................................</div>
        </div>
    </div>

    <div id="guideModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeGuide()">&times;</span>
            <h3>Hướng dẫn sử dụng</h3>
            <p>Định dạng URL để điền thông tin:</p>
            <a href="DataPT-TT200.xlsx">File mẫu</a>
            <code
                style="display: block; white-space: pre-wrap; background: #f5f5f5; padding: 15px; margin: 10px 0; border-radius: 5px;">
https://mauin.toolapp.name.vn/phieuthuTT200.html?
donvi={Nhập đơn vị}
&diachi={Nhập địa chỉ}
&quyenso={Nhập quyển số}
&so={Nhập số}
&no={Nhập nợ}
&co={Nhập có}
&nguoinop={Nhập người nộp}
&diachinop={Nhập địa chỉ nộp}
&lydo={Nhập lý do}
&sotien={Nhập số tiền}
&kemtheo={Nhập kèm theo}
&ngay={Nhập ngày}
&thang={Nhập tháng}
&nam={Nhập năm}
        </code>
            <p>Ví dụ: Để điền "Công ty ABC" vào trường đơn vị, thay "{Nhập đơn vị}" bằng "Công ty ABC"</p>
        </div>
    </div>
    <!-- Script section giữ nguyên như cũ, chỉ cần đổi tên file xuất -->
    <script>
        function handleExcelImport() {
            document.getElementById('excelFile').addEventListener('change', function (e) {
                const file = e.target.files[0];
                const reader = new FileReader();

                reader.onload = function (e) {
                    const data = new Uint8Array(e.target.result);
                    const workbook = XLSX.read(data, { type: 'array' });
                    const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
                    const jsonData = XLSX.utils.sheet_to_json(firstSheet);

                    // Tạo div wrapper mới với class 'receipts-container'
                    const receiptsContainer = document.createElement('div');
                    receiptsContainer.className = 'receipts-container';

                    jsonData.forEach((row, index) => {
                        const receiptDiv = document.createElement('div');
                        receiptDiv.className = 'container';
                        // Clone nội dung từ template
                        receiptDiv.innerHTML = document.querySelector('.container').innerHTML;

                        // Điền dữ liệu vào phiếu
                        fillReceiptData(receiptDiv, row);

                        // Thêm page break
                        if (index < jsonData.length - 1) {
                            receiptDiv.style.pageBreakAfter = 'always';
                        }

                        receiptsContainer.appendChild(receiptDiv);
                    });

                    // Thay thế container cũ bằng container mới
                    const oldContainer = document.querySelector('.container');
                    oldContainer.parentNode.replaceChild(receiptsContainer, oldContainer);
                };

                reader.readAsArrayBuffer(file);
            });
        }

        function fillReceiptData(receiptElement, data) {
            // Cập nhật các trường thông tin trong phiếu
            receiptElement.querySelector('.header-left').innerHTML = `
        <b>${data.donvi || '..................'}</b><br>
        <b>${data.diachi || '..................'}</b>
    `;

            receiptElement.querySelector('.info-right').innerHTML = `
        Quyển số: ${data.quyenso || '..........'}<br>
        Số: ${data.so || '..........'}<br>
        Nợ: ${data.no || '..........'}<br>
        Có: ${data.co || '..........'}
    `;

            const formRows = receiptElement.querySelectorAll('.form-row');
            const soTien = data.sotien || '';
            const formattedAmount = formatCurrency(soTien);
            const bangChu = soTien ? numberToWords(parseInt(soTien)) : '';

            formRows[0].innerHTML = `Họ và tên người nộp tiền: ${data.nguoinop || '...................................'}`;
            formRows[1].innerHTML = `Địa chỉ: ${data.diachinop || '...................................'}`;
            formRows[2].innerHTML = `Lý do nộp: ${data.lydo || '...................................'}`;
            formRows[3].innerHTML = `Số tiền: ${formattedAmount} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <i>(Viết bằng chữ): ${bangChu}</i>`;
            formRows[4].innerHTML = `Kèm theo ${data.kemtheo || '........................'} Chứng từ gốc`;

            // Cập nhật ngày tháng năm
            const dateString = `Ngày ${data.ngay || '...'} tháng ${data.thang || '...'} năm ${data.nam || '...'}`;
            receiptElement.querySelector('.info-date').innerHTML = `<i>${dateString}</i>`;
            receiptElement.querySelector('.date-line').innerHTML = `<i>${dateString}</i>`;

            // Cập nhật phần cuối
            receiptElement.querySelector('.bottom-section').firstElementChild.innerHTML =
                `Đã nhận đủ số tiền (viết bằng chữ): ${bangChu}`;
        }

        function showGuide() {
            document.getElementById('guideModal').style.display = "block";
        }

        function closeGuide() {
            document.getElementById('guideModal').style.display = "none";
        }
        // Click outside modal to close
        window.onclick = function (event) {
            if (event.target.className === 'modal') {
                event.target.style.display = "none";
            }
        }

        function printDocument() {
            window.print();
        }

        function exportToPDF() {
            const element = document.querySelector('.receipts-container') || document.querySelector('.container');
            const opt = {
                margin: 1,
                filename: 'phieu-thu.pdf',
                image: { type: 'jpeg', quality: 0.98 },
                html2canvas: { scale: 2 },
                jsPDF: { unit: 'cm', format: 'a4', orientation: 'portrait' }
            };

            html2pdf().set(opt).from(element).save();
        }

        function exportToPDFA5NGANG() {
            const element = document.querySelector('.receipts-container') || document.querySelector('.container');
            const opt = {
                margin: 1,
                filename: 'phieu-thu.pdf',
                image: { type: 'jpeg', quality: 0.98 },
                html2canvas: { scale: 2 },
                jsPDF: { unit: 'cm', format: 'a5', orientation: 'landscape' }
            };

            html2pdf().set(opt).from(element).save();
        }

        // Hàm format số tiền theo định dạng VND
        function formatCurrency(number) {
            if (!number) return '';
            return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + " VNĐ";
        }

        // Hàm chuyển số thành chữ
        function numberToWords(number) {
            const units = ["", "một", "hai", "ba", "bốn", "năm", "sáu", "bảy", "tám", "chín"];
            const positions = ["", "nghìn", "triệu", "tỷ"];

            if (number === 0) return "không";

            function readGroup(group) {
                let result = "";
                let hundreds = Math.floor(group / 100);
                let tens = Math.floor((group % 100) / 10);
                let ones = group % 10;

                if (hundreds > 0) {
                    result += units[hundreds] + " trăm ";
                }

                if (tens > 0) {
                    if (tens === 1) {
                        result += "mười ";
                    } else {
                        result += units[tens] + " mươi ";
                    }
                }

                if (ones > 0) {
                    if (tens === 0 && hundreds !== 0) {
                        result += "lẻ ";
                    }
                    if (ones === 1 && tens > 1) {
                        result += "mốt ";
                    } else if (ones === 5 && tens > 0) {
                        result += "lăm ";
                    } else {
                        result += units[ones] + " ";
                    }
                }

                return result;
            }

            let result = "";
            let groupCount = 0;
            let temp = number;

            while (temp > 0) {
                let group = temp % 1000;
                if (group !== 0) {
                    result = readGroup(group) + positions[groupCount] + " " + result;
                }
                temp = Math.floor(temp / 1000);
                groupCount++;
            }

            // Chuẩn hóa chuỗi
            result = result.trim();
            result = result.charAt(0).toUpperCase() + result.slice(1);
            result += " đồng";
            return result;
        }

        window.onload = function () {
            handleExcelImport();
            const urlParams = new URLSearchParams(window.location.search);

            // Thêm xử lý ngày tháng năm
            const ngay = urlParams.get('ngay') || '.....';
            const thang = urlParams.get('thang') || '.....';
            const nam = urlParams.get('nam') || '.......';

            // Cập nhật ngày tháng năm ở phần title
            document.querySelector('.info-date').innerHTML = `
        <i>Ngày ${ngay} tháng ${thang} năm ${nam}</i>
    `;

            // Cập nhật ngày tháng năm ở phần chữ ký
            document.querySelector('.date-line').innerHTML = `
        <i>Ngày ${ngay} tháng ${thang} năm ${nam}</i>
    `;

            // Điền thông tin từ URL vào form
            document.querySelector('.header-left').innerHTML = `
        <b>${urlParams.get('donvi') || '..................'}</b><br>
        <b>${urlParams.get('diachi') || '..................'}</b>
    `;

            document.querySelector('.info-right').innerHTML = `
        Quyển số: ${urlParams.get('quyenso') || '..........'}<br>
        Số: ${urlParams.get('so') || '..........'}<br>
        Nợ: ${urlParams.get('no') || '..........'}<br>
        Có: ${urlParams.get('co') || '..........'}
    `;

            // Lấy số tiền và chuyển đổi thành chữ
            const soTien = urlParams.get('sotien') || '';
            const formattedAmount = formatCurrency(soTien);
            const bangChu = soTien ? numberToWords(parseInt(soTien)) : '';

            // Điền thông tin người nộp và các trường khác
            const formRows = document.querySelectorAll('.form-row');
            formRows[0].innerHTML = `Họ và tên người nộp tiền: ${urlParams.get('nguoinop') || '...................................'}`;
            formRows[1].innerHTML = `Địa chỉ: ${urlParams.get('diachinop') || '...................................'}`;
            formRows[2].innerHTML = `Lý do nộp: ${urlParams.get('lydo') || '...................................'}`;
            formRows[3].innerHTML = `Số tiền: ${formattedAmount} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <i>(Viết bằng chữ): ${bangChu}</i>`;
            formRows[4].innerHTML = `Kèm theo ${urlParams.get('kemtheo') || '........................'} Chứng từ gốc`;

            // Cập nhật phần đã nhận đủ số tiền ở cuối phiếu
            const bottomSection = document.querySelector('.bottom-section');
            bottomSection.firstElementChild.innerHTML = `Đã nhận đủ số tiền (viết bằng chữ): ${bangChu}`;
        }
    </script>
</body>

</html>