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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wows Mua hàng nhanh</title>
    <link rel="shortcut icon" href="1.png" type="image/x-icon">
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Thêm Select2 CSS và JS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
    <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/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
    <script src="key.js"></script>
    <style>
        /* Custom toast styles */
        .toastify {
            font-family: system-ui, -apple-system, sans-serif;
            padding: 12px 20px;
            border-radius: 8px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }

        .toast-success {
            background: linear-gradient(to right, #34d399, #10b981);
        }

        .toast-error {
            background: linear-gradient(to right, #ef4444, #dc2626);
        }

        .toast-warning {
            background: linear-gradient(to right, #f59e0b, #d97706);
        }

        .toast-info {
            background: linear-gradient(to right, #3b82f6, #2563eb);
        }

        .animate-spin {
            animation: spin 1s linear infinite;
        }

        /* Thêm style cho Select2 */
        .select2-container {
            width: 100% !important;
        }

        .select2-container--default .select2-selection--single {
            height: 42px;
            padding: 6px;
            border: 1px solid #D1D5DB;
            border-radius: 0.375rem;
        }

        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 40px;
        }

        .select2-container--default .select2-search--dropdown .select2-search__field {
            padding: 8px;
            border: 1px solid #D1D5DB;
            border-radius: 0.375rem;
        }

        .select2-dropdown {
            border: 1px solid #D1D5DB;
            border-radius: 0.375rem;
        }

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

            to {
                transform: rotate(360deg);
            }
        }

        @media print {
            body * {
                visibility: hidden;
            }

            #printArea,
            #printArea * {
                visibility: visible;
            }

            #printArea {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
            }

            .no-print {
                display: none !important;
            }
        }
    </style>
</head>

<body class="bg-gray-100">
    <div id="loadingStatus" class="hidden fixed inset-0 z-50">
        <!-- Overlay nền tối -->
        <div class="absolute inset-0 bg-gray-900 opacity-50"></div>
        <!-- Container loading -->
        <div class="absolute inset-0 flex items-center justify-center">
            <div class="bg-white p-6 rounded-lg shadow-xl flex items-center gap-4">
                <svg class="w-8 h-8 animate-spin text-blue-600" xmlns="http://www.w3.org/2000/svg" fill="none"
                    viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
                    </path>
                </svg>
                <span class="text-lg font-medium text-gray-700">Đang tải dữ liệu...</span>
            </div>
        </div>
    </div>
    <div class="flex h-screen">
        <!-- Sidebar - Danh mục hàng hóa -->
        <div id="productSidebar" class="w-80 bg-white shadow-lg overflow-y-auto hidden">
            <div class="p-4">
                <h2 class="text-xl font-semibold mb-4">Danh Mục Hàng Hóa</h2>
                <div class="mb-4">
                    <input type="text" id="searchProduct" placeholder="Tìm kiếm hàng hóa..."
                        class="w-full p-2 border rounded-lg" oninput="searchProducts(this.value)">
                </div>
                <div id="productList" class="space-y-4">
                    <!-- Danh sách sản phẩm sẽ được thêm vào đây -->
                </div>
            </div>
        </div>

        <!-- Main content -->
        <div class="flex-1 p-6 overflow-y-auto">


            <!-- Form mua hàng -->
            <!-- Form mua hàng -->
            <div class="bg-white rounded-lg shadow-lg p-6 mb-6">
                <h2 class="text-xl font-semibold mb-4">Thông Tin Mua Hàng</h2>
                <form id="purchaseForm" class="grid grid-cols-4 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700">ID Mua</label>
                        <input type="text" id="idMua"
                            class="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 border" readonly>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">Số Chứng Từ</label>
                        <input type="text" id="soChungTu"
                            class="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 border" required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">Thời Gian</label>
                        <input type="datetime-local" id="thoiGian"
                            class="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 border" required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">Người Tạo</label>
                        <input type="text" id="nguoiTao"
                            class="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 border" readonly required>
                    </div>
                    <div class="col-span-2">
                        <label class="block text-sm font-medium text-gray-700">Nhà Cung Cấp</label>
                        <select id="ncc" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 border"
                            required onchange="handleSupplierChange(this.value)">
                            <option value="">Chọn nhà cung cấp</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">Diễn Giải</label>
                        <textarea type="text" id="dienGiai"
                            class="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 border"> </textarea>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">Ghi Chú</label>
                        <textarea type="text" id="ghiChu"
                            class="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 border"> </textarea>
                    </div>
                    <div class="flex items-end gap-2">
                        <!-- Reset button -->
                        <button type="button" onclick="resetForm()" title="Reset"
                            class="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600">
                            <svg style="width:15px; height:15px; fill:#ffffff" viewBox="0 0 512 512"
                                xmlns="http://www.w3.org/2000/svg">
                                <path
                                    d="M205 34.8c11.5 5.1 19 16.6 19 29.2v64H336c97.2 0 176 78.8 176 176c0 113.3-81.5 163.9-100.2 174.1c-2.5 1.4-5.3 1.9-8.1 1.9c-10.9 0-19.7-8.9-19.7-19.7c0-7.5 4.3-14.4 9.8-19.5c9.4-8.8 22.2-26.4 22.2-56.7c0-53-43-96-96-96H224v64c0 12.6-7.4 24.1-19 29.2s-25 3-34.4-5.4l-160-144C3.9 225.7 0 217.1 0 208s3.9-17.7 10.6-23.8l160-144c9.4-8.5 22.9-10.6 34.4-5.4z">
                                </path>
                            </svg>
                        </button>
                        <!-- Submit button -->
                        <button type="button" onclick="submitForm()" title="Tạo phiếu mua hàng"
                            class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">
                            <svg style="width:15px; height:15px; fill:#ffffff" viewBox="0 0 640 512"
                                xmlns="http://www.w3.org/2000/svg">
                                <path
                                    d="M144 480C64.5 480 0 415.5 0 336c0-62.8 40.2-116.2 96.2-135.9c-.1-2.7-.2-5.4-.2-8.1c0-88.4 71.6-160 160-160c59.3 0 111 32.2 138.7 80.2C409.9 102 428.3 96 448 96c53 0 96 43 96 96c0 12.2-2.3 23.8-6.4 34.6C596 238.4 640 290.1 640 352c0 70.7-57.3 128-128 128H144zm79-217c-9.4 9.4-9.4 24.6 0 33.9s24.6 9.4 33.9 0l39-39V392c0 13.3 10.7 24 24 24s24-10.7 24-24V257.9l39 39c9.4 9.4 24.6 9.4 33.9 0s9.4-24.6 0-33.9l-80-80c-9.4-9.4-24.6-9.4-33.9 0l-80 80z">
                                </path>
                            </svg>
                        </button>
                        <!-- Print button -->
                        <button type="button" onclick="printPurchaseOrder()" title="In phiếu mua hàng"
                            class="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600">
                            <svg style="width:15px; height:15px; fill:#ffffff" viewBox="0 0 512 512"
                                xmlns="http://www.w3.org/2000/svg">
                                <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>

                        <!-- Word Export button -->
                        <button type="button" onclick="exportToWord()" title="Xuất Word"
                            class="bg-blue-700 text-white px-4 py-2 rounded hover:bg-blue-800">
                            <svg style="width:15px; height:15px; fill:#ffffff;" viewBox="0 0 384 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="M64 0C28.7 0 0 28.7 0 64V448c0 35.3 28.7 64 64 64H320c35.3 0 64-28.7 64-64V160H256c-17.7 0-32-14.3-32-32V0H64zM256 0V128H384L256 0zM111 257.1l26.8 89.2 31.6-90.3c3.4-9.6 12.5-16.1 22.7-16.1s19.3 6.4 22.7 16.1l31.6 90.3L273 257.1c3.8-12.7 17.2-19.9 29.9-16.1s19.9 17.2 16.1 29.9l-48 160c-3 10-12 16.9-22.4 17.1s-19.8-6.2-23.2-16.1L192 336.6l-33.3 95.3c-3.4 9.8-12.8 16.3-23.2 16.1s-19.5-7.1-22.4-17.1l-48-160c-3.8-12.7 3.4-26.1 16.1-29.9s26.1 3.4 29.9 16.1z">
                                </path>

                            </svg>
                        </button>
                        <!-- Excel Export button -->
                        <button type="button" onclick="exportToExcel()" title="Xuất Excel"
                            class="bg-green-700 text-white px-4 py-2 rounded hover:bg-green-800">
                            <svg style="width:15px; height:15px; fill:#ffffff;" viewBox="0 0 384 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="M64 0C28.7 0 0 28.7 0 64V448c0 35.3 28.7 64 64 64H320c35.3 0 64-28.7 64-64V160H256c-17.7 0-32-14.3-32-32V0H64zM256 0V128H384L256 0zM155.7 250.2L192 302.1l36.3-51.9c7.6-10.9 22.6-13.5 33.4-5.9s13.5 22.6 5.9 33.4L221.3 344l46.4 66.2c7.6 10.9 5 25.8-5.9 33.4s-25.8 5-33.4-5.9L192 385.8l-36.3 51.9c-7.6 10.9-22.6 13.5-33.4 5.9s-13.5-22.6-5.9-33.4L162.7 344l-46.4-66.2c-7.6-10.9-5-25.8 5.9-33.4s25.8-5 33.4 5.9z">
                                </path>

                            </svg>
                        </button>

                    </div>
                </form>
            </div>

            <!-- Bảng chi tiết mua hàng -->
            <div class="bg-white rounded-lg shadow-lg p-6">
                <h2 class="text-xl font-semibold mb-4">Chi Tiết Mua Hàng</h2>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th hidden class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">ID MĐ
                                </th>
                                <th hidden class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">ID
                                    Mua</th>
                                <th hidden class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Mã
                                    Hàng</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Tên Hàng
                                </th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Số Lượng
                                </th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">ĐVT</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Quy Đổi</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">SL Nhập</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Đơn Giá</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Ghi Chú</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Thao Tác
                                </th>
                            </tr>
                        </thead>
                        <tbody id="purchaseDetails" class="bg-white divide-y divide-gray-200">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div id="printArea" class="hidden">
        <div class="p-8">
            <!-- Header with company info -->
            <div class="grid grid-cols-12 gap-4 mb-8">
                <!-- Company info (70%) -->
                <div class="col-span-2 flex items-start gap-4">
                    <img src="1.png" alt="Company Logo"
                        class="w-20 h-auto object-contain">
                </div>
                <div class="col-span-8  center">
                    <div class="flex flex-col text-center justify-center">
                        <h2 class="font-bold text-xl">TÊN CÔNG TY</h2>
                        <p class="text-sm">MST: MÃ SỐ THUẾ</p>
                        <p class="text-sm">Địa chỉ: ĐỊA CHỈ CÔNG TY</p>
                        <p class="text-sm">Hotline: 0326 132 124</p>
                        <p class="text-sm">Email: ninhphuoc@phuocnv.io.vn</p>
                    </div>
                </div>
                <!-- Document info (30%) -->
                <div class="col-span-2 text-right">
                    <p class="text-sm mb-2">Mẫu số: 01-HĐGT</p>
                    <p class="text-sm mb-2">Ký hiệu: PO/22E</p>
                    <p class="text-sm">Số: <span id="printSoHD"></span></p>
                </div>
            </div>

            <!-- Title -->
            <div class="text-center mb-6">
                <h1 class="text-2xl font-bold">PHIẾU MUA HÀNG</h1>
                <p class="text-gray-600" id="printDateTime"></p>
            </div>

            <!-- Purchase info -->
            <div class="grid grid-cols-2 gap-4 mb-6">
                <div>
                    <p><strong>Số chứng từ:</strong> <span id="printSoChungTu"></span></p>
                    <p><strong>Nhà cung cấp:</strong> <span id="printNCC"></span></p>
                    <p><strong>Địa chỉ NCC:</strong> <span id="printNCCAddress"></span></p>
                    <p><strong>MST NCC:</strong> <span id="printNCCTax"></span></p>
                </div>
                <div>
                    <p><strong>Ngày tạo:</strong> <span id="printThoiGian"></span></p>
                    <p><strong>Người tạo:</strong> <span id="printNguoiTao"></span></p>
                    <p><strong>Bộ phận:</strong> <span id="printDepartment">Phòng mua hàng</span></p>
                </div>
            </div>

            <!-- Notes -->
            <div class="mb-4">
                <p><strong>Diễn giải:</strong> <span id="printDienGiai"></span></p>
                <p><strong>Ghi chú:</strong> <span id="printGhiChu"></span></p>
            </div>

            <!-- Products table -->
            <table class="min-w-full border border-gray-200">
                <thead>
                    <tr class="bg-gray-50">
                        <th class="border p-2">STT</th>
                        <th class="border p-2">Tên Hàng</th>
                        <th class="border p-2">Số Lượng</th>
                        <th class="border p-2">ĐVT</th>
                        <th class="border p-2">Đơn Giá</th>
                        <th class="border p-2">Thành Tiền</th>
                        <th class="border p-2">Ghi Chú</th>
                    </tr>
                </thead>
                <tbody id="printTableBody"></tbody>
                <tfoot>

                </tfoot>
            </table>

            <!-- Signatures -->
            <div class="mt-8 grid grid-cols-3 gap-4 text-center">
                <div>
                    <p class="font-bold">Người lập phiếu</p>
                    <p class="text-gray-600">(Ký, họ tên)</p>
                    <div class="h-20"></div>
                    <p id="printCreatorName"></p>
                </div>
                <div>
                    <p class="font-bold">Kế toán trưởng</p>
                    <p class="text-gray-600">(Ký, họ tên)</p>
                    <div class="h-20"></div>
                    <p>Kế toán trưởng</p>
                </div>
                <div>
                    <p class="font-bold">Giám đốc</p>
                    <p class="text-gray-600">(Ký, họ tên, đóng dấu)</p>
                    <div class="h-20"></div>
                    <p>NINH VĂN PHƯỚC</p>
                </div>
            </div>

            <!-- Footer -->
            <div class="mt-8 text-sm text-gray-500">
                <p class="text-center">Devloper: Phước Ninh</p>
            </div>
        </div>
    </div>
    <script>
        // Constants
        const APP_ID = 'e483be4d-1b20-4805-8bcf-c01013ee853b';
        const ACCESS_KEY = 'V2-PelHU-a4w3r-2mlpo-wI0XW-nZvbo-Y5sLF-XoEn4-wf3Ym';
        const REGION = 'www';
        const API_URL = `https://${REGION}.appsheet.com/api/v2/apps/${APP_ID}/tables`;
        const showToast = (message, type = 'info') => {
            const toastConfig = {
                text: message,
                duration: 3000,
                gravity: "top",
                position: "right",
                className: `toast-${type}`,
                stopOnFocus: true
            };
            Toastify(toastConfig).showToast();
        };

        // Global state
        let currentPurchaseId = 'MUA' + Date.now();
        let currentSupplierProducts = [];


        // Cache object
        const dataCache = {
            suppliers: null,
            allProducts: null,
            isInitialized: false,
            loading: false
        };

        // Loading indicator functions
        const showLoading = () => {
            document.getElementById('loadingStatus').classList.remove('hidden');
        };

        const hideLoading = () => {
            document.getElementById('loadingStatus').classList.add('hidden');
        };
        function printPurchaseOrder() {
            // Get supplier name from selected option
            const nccSelect = document.getElementById('ncc');
            const selectedSupplier = dataCache.suppliers.find(s => s.MANCC === nccSelect.value);
            const supplierName = selectedSupplier ? selectedSupplier['TÊN NHÀ CUNG CẤP'] : '';
            const supplierAddress = selectedSupplier ? selectedSupplier['Điạ chỉ công ty/ nhà'] : '';
            const supplierTax = selectedSupplier ? selectedSupplier['Mã số thuế /CCDC/CMND'] : '';


            // Update print template with current values
            document.getElementById('printSoChungTu').textContent = document.getElementById('soChungTu').value;
            document.getElementById('printSoHD').textContent = document.getElementById('soChungTu').value;
            document.getElementById('printNCC').textContent = supplierName;
            document.getElementById('printNCCAddress').textContent = supplierAddress;
            document.getElementById('printNCCTax').textContent = supplierTax;
            document.getElementById('printThoiGian').textContent = new Date(document.getElementById('thoiGian').value).toLocaleString('vi-VN');
            document.getElementById('printNguoiTao').textContent = document.getElementById('nguoiTao').value;
            document.getElementById('printCreatorName').textContent = document.getElementById('nguoiTao').value;
            document.getElementById('printDienGiai').textContent = document.getElementById('dienGiai').value;
            document.getElementById('printGhiChu').textContent = document.getElementById('ghiChu').value;
            document.getElementById('printDateTime').textContent = new Date().toLocaleString('vi-VN');

            // Generate table content
            const tbody = document.getElementById('purchaseDetails');
            const printTbody = document.getElementById('printTableBody');
            printTbody.innerHTML = '';

            let totalAmount = 0;
            Array.from(tbody.children).forEach((row, index) => {
                const quantity = parseFloat(row.querySelector('[data-quantity]').value);
                const price = parseFloat(row.cells[8].querySelector('input').value);
                const amount = quantity * price;
                totalAmount += amount;

                const newRow = document.createElement('tr');
                newRow.innerHTML = `
                    <td class="border p-2 text-center">${index + 1}</td>
                    <td class="border p-2">${row.cells[3].textContent}</td>
                    <td class="border p-2 text-right">${quantity.toLocaleString('vi-VN')}</td>
                    <td class="border p-2 text-center">${row.cells[5].textContent}</td>
                    <td class="border p-2 text-right">${price.toLocaleString('vi-VN')}</td>
                    <td class="border p-2 text-right">${amount.toLocaleString('vi-VN')}</td>
                    <td class="border p-2">${row.cells[9].querySelector('input').value}</td>
                `;
                printTbody.appendChild(newRow);
            });

            // Add total row
            const totalRow = document.createElement('tr');
            totalRow.innerHTML = `
                <td colspan="5" class="border p-2 text-right font-bold">Tổng cộng:</td>
                <td class="border p-2 text-right font-bold">${totalAmount.toLocaleString('vi-VN')}</td>
                <td class="border p-2"></td>
            `;
            printTbody.appendChild(totalRow);

            // Show print template and trigger print
            document.getElementById('printArea').classList.remove('hidden');
            window.print();
            document.getElementById('printArea').classList.add('hidden');
        }

        // API Request function
        const apiRequest = async (tableName, action, data, select = {}) => {
            try {
                const response = await fetch(`${API_URL}/${tableName}/Action`, {
                    method: 'POST',
                    headers: {
                        'ApplicationAccessKey': ACCESS_KEY,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        Action: action,
                        Properties: select,
                        ...data
                    })
                });

                if (!response.ok) throw new Error('Network response was not ok');
                return await response.json();
            } catch (error) {
                console.error('API request failed:', error);
                throw error;
            }
        };

        // Initialize data
        async function initializeData() {
            if (dataCache.loading || dataCache.isInitialized) return;

            try {
                dataCache.loading = true;
                showLoading();

                // Load all data in parallel
                const [suppliersResponse, productsResponse] = await Promise.all([
                    apiRequest('NCC', 'Find', {}, { Selector: `Filter(NCC, true)` }),
                    apiRequest('NCCDE', 'Find', {}, { Selector: `Filter(NCCDE, true)` })
                ]);

                // Cache the responses
                dataCache.suppliers = suppliersResponse;
                dataCache.allProducts = productsResponse;
                dataCache.isInitialized = true;

                // Populate suppliers dropdown
                populateSuppliers();
                showToast('Dữ liệu đã được tải thành công', 'success');


            } catch (error) {
                console.error('Error initializing data:', error);
                showToast('Có lỗi khi tải dữ liệu ban đầu. Vui lòng thử lại.', 'error');
            } finally {
                dataCache.loading = false;
                hideLoading();
            }
        }

        // Populate suppliers select
        function populateSuppliers() {
            const nccSelect = $('#ncc');
            nccSelect.empty().append('<option value="">Chọn nhà cung cấp</option>');

            if (dataCache.suppliers) {
                dataCache.suppliers.forEach(supplier => {
                    const option = new Option(supplier['TÊN NHÀ CUNG CẤP'], supplier.MANCC);
                    nccSelect.append(option);
                });
            }

            // Khởi tạo Select2
            nccSelect.select2({
                placeholder: 'Chọn nhà cung cấp',
                allowClear: true,
                language: {
                    noResults: function () {
                        return "Không tìm thấy nhà cung cấp";
                    }
                },
                templateResult: formatSupplier,
                templateSelection: formatSupplier
            });
        }
        function formatSupplier(supplier) {
            if (!supplier.id) return supplier.text;
            const supplierData = dataCache.suppliers.find(s => s.MANCC === supplier.id);
            if (!supplierData) return supplier.text;

            return $(`<div class="flex items-center">
                <div>
                    <div class="font-semibold">${supplierData['TÊN NHÀ CUNG CẤP']}</div>
                    <div class="text-gray-600 text-sm">Mã: ${supplierData.MANCC}</div>
                </div>
            </div>`);
        }

        // Filter products by supplier
        function handleSupplierChange(supplierId) {
            const productSidebar = document.getElementById('productSidebar');

            if (!supplierId) {
                productSidebar.classList.add('hidden');
                currentSupplierProducts = [];
                return;
            }

            // Filter products from cache
            currentSupplierProducts = dataCache.allProducts.filter(product => product.MANCC === supplierId);
            renderProducts(currentSupplierProducts);
            productSidebar.classList.remove('hidden');
        }

        // Render products
        function renderProducts(products) {
            const productList = document.getElementById('productList');
            productList.innerHTML = '';

            if (!products || products.length === 0) {
                productList.innerHTML = '<div class="text-gray-500 text-center">Không có sản phẩm</div>';
                return;
            }

            products.forEach(product => {
                const productCard = document.createElement('div');
                productCard.className = 'border rounded-lg p-4 hover:bg-gray-50 cursor-pointer';
                productCard.onclick = () => selectProduct(product['MÃ HÀNG']);
                productCard.innerHTML = `
                    <div class="flex items-center space-x-4">
                        <img src="${product['HÌNH ẢNH'] || '/api/placeholder/100/100'}" alt="${product['TÊN HÀNG']}" 
                             class="w-16 h-16 object-cover rounded">
                        <div>
                            <h3 class="font-semibold">${product['TÊN HÀNG']}</h3>
                            <p class="text-sm text-gray-600">Mã: ${product['MÃ HÀNG']}</p>
                            <p class="text-sm text-gray-600">ĐVT: ${product['ĐƠN VỊ TÍNH']}</p>
                            <p class="text-sm text-gray-600">Đơn Giá: ${product['Giá']?.toLocaleString()} đ</p>
                        </div>
                    </div>
                `;
                productList.appendChild(productCard);
            });
        }

        // Search products
        function searchProducts(keyword) {
            if (!keyword.trim()) {
                renderProducts(currentSupplierProducts);
                return;
            }

            const filteredProducts = currentSupplierProducts.filter(product =>
                product['MÃ HÀNG']?.toLowerCase().includes(keyword.toLowerCase()) ||
                product['TÊN HÀNG']?.toLowerCase().includes(keyword.toLowerCase())
            );
            renderProducts(filteredProducts);
        }

        // Select product
        function selectProduct(maHang) {
            const product = currentSupplierProducts.find(p => p['MÃ HÀNG'] === maHang);
            if (!product) return;

            const tbody = document.getElementById('purchaseDetails');
            const existingRow = Array.from(tbody.children).find(row => {
                const maHangCell = row.querySelector('td[data-ma-hang]');
                return maHangCell && maHangCell.dataset.maHang === maHang;
            });

            if (existingRow) {
                const quantityInput = existingRow.querySelector('[data-quantity]');
                quantityInput.value = parseInt(quantityInput.value) + 1;
                updateRowCalculations(existingRow);
            } else {
                const tr = document.createElement('tr');
                const idMuaDe = 'MUADE' + Date.now();
                tr.innerHTML = `
                    <td hidden class="px-6 py-4">${idMuaDe}</td>
                    <td hidden class="px-6 py-4">${currentPurchaseId}</td>
                    <td hidden class="px-6 py-4" data-ma-hang="${product['MÃ HÀNG']}">${product['MÃ HÀNG']}</td>
                    <td class="px-6 py-4">${product['TÊN HÀNG']}</td>
                    <td class="px-6 py-4">
                        <input type="number" data-quantity class="border rounded p-1 w-20" value="1" min="1" 
                            onchange="updateRowCalculations(this.parentElement.parentElement)">
                    </td>
                    <td class="px-6 py-4">${product['ĐƠN VỊ TÍNH']}</td>
                    <td class="px-6 py-4">
                        <input type="number" data-quy-doi class="border rounded p-1 w-20" value="1" min="1"
                            onchange="updateRowCalculations(this.parentElement.parentElement)">
                    </td>
                    <td class="px-6 py-4">
                        <input type="number" data-sl-nhap class="border rounded p-1 w-20" value="1" readonly>
                    </td>
                    <td class="px-6 py-4">
                        <input type="number" class="border rounded p-1 w-28" value="${product['Giá'] || 0}">
                    </td>
                    <td class="px-6 py-4">
                        <input type="text" class="border rounded p-1 w-full" placeholder="Ghi chú">
                    </td>
                    <td class="px-6 py-4">
                        <button onclick="this.parentElement.parentElement.remove()" 
                            class="text-red-500 hover:text-red-700"><svg style="width:15px; height:15px; fill:#e60000;"  viewBox="0 0 448 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="M135.2 17.7C140.6 6.8 151.7 0 163.8 0H284.2c12.1 0 23.2 6.8 28.6 17.7L320 32h96c17.7 0 32 14.3 32 32s-14.3 32-32 32H32C14.3 96 0 81.7 0 64S14.3 32 32 32h96l7.2-14.3zM32 128H416V448c0 35.3-28.7 64-64 64H96c-35.3 0-64-28.7-64-64V128zm96 64c-8.8 0-16 7.2-16 16V432c0 8.8 7.2 16 16 16s16-7.2 16-16V208c0-8.8-7.2-16-16-16zm96 0c-8.8 0-16 7.2-16 16V432c0 8.8 7.2 16 16 16s16-7.2 16-16V208c0-8.8-7.2-16-16-16zm96 0c-8.8 0-16 7.2-16 16V432c0 8.8 7.2 16 16 16s16-7.2 16-16V208c0-8.8-7.2-16-16-16z"></path>

</svg></button>
                    </td>
                `;
                tbody.appendChild(tr);
                updateRowCalculations(tr);
            }
        }

        // Update row calculations
        function updateRowCalculations(row) {
            const quantityInput = row.querySelector('[data-quantity]');
            const quyDoiInput = row.querySelector('[data-quy-doi]');
            const slNhapInput = row.querySelector('[data-sl-nhap]');

            if (quantityInput && quyDoiInput && slNhapInput) {
                const soLuong = parseInt(quantityInput.value) || 0;
                const quyDoi = parseInt(quyDoiInput.value) || 0;
                slNhapInput.value = soLuong * quyDoi;
            }
        }

        async function submitForm() {
            try {
                showLoading();
                const phieuMua = {
                    IDMUA: document.getElementById('idMua').value,
                    "SỐ CHỨNG TỪ": document.getElementById('soChungTu').value,
                    "THỜI GIAN": document.getElementById('thoiGian').value,
                    "DIỄN GIẢI": document.getElementById('dienGiai').value,
                    "NCC": document.getElementById('ncc').value,
                    "NGƯỜI TẠO": document.getElementById('nguoiTao').value,
                    "GHI CHÚ": document.getElementById('ghiChu').value,
                    "TRẠNG THÁI": "Phiếu mới",
                };

                // Lấy chi tiết sản phẩm    
                const chiTiet = Array.from(document.getElementById('purchaseDetails').getElementsByTagName('tr'))
                    .map(row => ({
                        IDMUADE: row.cells[0].textContent,
                        IDMUA: row.cells[1].textContent,
                        "MÃ HÀNG": row.cells[2].textContent,
                        "SỐ LƯỢNG": row.querySelector('[data-quantity]').value,
                        "ĐƠN VỊ TÍNH": row.cells[5].textContent,
                        "QUY ĐỔI": row.querySelector('[data-quy-doi]').value,
                        "SỐ LƯỢNG NHẬP": row.querySelector('[data-sl-nhap]').value,
                        "ĐƠN Giá NHẬP": row.cells[8].querySelector('input').value,
                        "GHI CHÚ": row.cells[9].querySelector('input').value
                    }));

                // Kiểm tra dữ liệu trước khi gửi
                if (!chiTiet.length) {
                    showToast('Vui lòng thêm ít nhất một sản phẩm vào phiếu mua', 'warning');
                    return;
                }

                const requiredFields = {
                    "SỐ CHỨNG TỪ": "Số chứng từ",
                    "THỜI GIAN": "Thời gian",
                    "NCC": "Nhà cung cấp",
                    "NGƯỜI TẠO": "Người tạo"
                };

                for (const [field, label] of Object.entries(requiredFields)) {
                    if (!phieuMua[field]) {
                        showToast(`Vui lòng điền ${label}`, 'warning');
                        return;
                    }
                }

                try {
                    // Thêm phiếu mua chính
                    const phieuMuaResponse = await apiRequest('MUAHANG', 'Add', { Rows: [phieuMua] });

                    // Kiểm tra response của phiếu mua
                    if (!phieuMuaResponse || phieuMuaResponse.error) {
                        s
                        throw new Error('Không thể thêm phiếu mua');
                    }

                    try {
                        // Nếu phiếu mua thành công, thêm chi tiết
                        const chiTietResponse = await apiRequest('MUAHANGDE', 'Add', { Rows: chiTiet });

                        if (!chiTietResponse || chiTietResponse.error) {
                            // Nếu thêm chi tiết thất bại, có thể xem xét việc rollback phiếu mua
                            await apiRequest('MUAHANGDE', 'Delete', { Rows: [phieuMua.IDMUA] });
                            throw new Error('Không thể thêm chi tiết phiếu mua');
                        }

                        showToast('Đã lưu phiếu mua thành công!', 'success');
                        printPurchaseOrder()    
                        resetForm();
                    } catch (chiTietError) {
                        // Xử lý lỗi khi thêm chi tiết
                        console.error('Error adding details:', chiTietError);
                        showToast('Lỗi khi thêm chi tiết phiếu mua', 'error');
                        await apiRequest('PHIEUMUA', 'Delete', { Keys: [phieuMua.IDMUA] });
                        throw new Error('Lỗi khi thêm chi tiết: ' + chiTietError.message);
                    }
                } catch (phieuMuaError) {
                    console.error('Error adding main record:', phieuMuaError);
                    showToast('Lỗi khi thêm phiếu mua', 'error');
                }

            } catch (error) {
                console.error('Error in form submission:', error);
                showToast(error.message, 'error');
            } finally {
                hideLoading();
            }
        }

        async function exportToWord() {
            try {
                showLoading();

                // Lấy thông tin nhà cung cấp
                const nccSelect = document.getElementById('ncc');
                const selectedSupplier = dataCache.suppliers.find(s => s.MANCC === nccSelect.value);
                const supplierName = selectedSupplier ? selectedSupplier['TÊN NHÀ CUNG CẤP'] : '';

                // Tạo nội dung HTML
                let htmlContent = `
            <html>
                <head>
                    <meta charset="UTF-8">
                    <style>
                        body { font-family: Arial, sans-serif; }
                        .header { text-align: center; margin-bottom: 20px; }
                        .info { margin-bottom: 20px; }
                        table { width: 100%; border-collapse: collapse; }
                        th, td { border: 1px solid #000; padding: 8px; }
                        th { background-color: #f0f0f0; }
                        .total { font-weight: bold; }
                    </style>
                </head>
                <body>
                    <div class="header">
                        <h1>PHIẾU MUA HÀNG</h1>
                        <p>${new Date().toLocaleString('vi-VN')}</p>
                    </div>
                    
                    <div class="info">
                        <p><strong>Số chứng từ:</strong> ${document.getElementById('soChungTu').value}</p>
                        <p><strong>Thời gian:</strong> ${new Date(document.getElementById('thoiGian').value).toLocaleString('vi-VN')}</p>
                        <p><strong>Nhà cung cấp:</strong> ${supplierName}</p>
                        <p><strong>Người tạo:</strong> ${document.getElementById('nguoiTao').value}</p>
                    </div>
                    
                    <table>
                        <thead>
                            <tr>
                                <th>STT</th>
                                <th>Tên hàng</th>
                                <th>Số lượng</th>
                                <th>ĐVT</th>
                                <th>Đơn giá</th>
                                <th>Thành tiền</th>
                            </tr>
                        </thead>
                        <tbody>
        `;

                // Thêm dữ liệu sản phẩm
                let totalAmount = 0;
                const rows = document.getElementById('purchaseDetails').getElementsByTagName('tr');
                Array.from(rows).forEach((row, index) => {
                    const quantity = parseFloat(row.querySelector('[data-quantity]').value);
                    const price = parseFloat(row.cells[8].querySelector('input').value);
                    const amount = quantity * price;
                    totalAmount += amount;

                    htmlContent += `
                <tr>
                    <td>${index + 1}</td>
                    <td>${row.cells[3].textContent}</td>
                    <td>${quantity.toLocaleString('vi-VN')}</td>
                    <td>${row.cells[5].textContent}</td>
                    <td>${price.toLocaleString('vi-VN')}</td>
                    <td>${amount.toLocaleString('vi-VN')}</td>
                </tr>
            `;
                });

                // Thêm tổng cộng và đóng HTML
                htmlContent += `
                            <tr class="total">
                                <td colspan="5" style="text-align: right;">Tổng cộng:</td>
                                <td>${totalAmount.toLocaleString('vi-VN')}</td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <div style="margin-top: 30px; display: flex; justify-content: space-around; text-align: center;">
                        <div>
                            <p><strong>Người lập phiếu</strong></p>
                            <p><em>(Ký, họ tên)</em></p>
                        </div>
                        <div>
                            <p><strong>Người duyệt</strong></p>
                            <p><em>(Ký, họ tên)</em></p>
                        </div>
                    </div>
                </body>
            </html>
        `;

                // Chuyển đổi HTML thành Blob
                const blob = new Blob([htmlContent], { type: 'application/msword' });

                // Tạo link tải xuống
                const fileName = `PhieuMuaHang_${document.getElementById('soChungTu').value}.doc`;
                saveAs(blob, fileName);

                showToast('Xuất Word thành công!', 'success');
            } catch (error) {
                console.error('Lỗi khi xuất Word:', error);
                showToast('Có lỗi xảy ra khi xuất Word', 'error');
            } finally {
                hideLoading();
            }
        }
        async function exportToExcel() {
            try {
                showLoading();

                // Lấy thông tin nhà cung cấp
                const nccSelect = document.getElementById('ncc');
                const selectedSupplier = dataCache.suppliers.find(s => s.MANCC === nccSelect.value);
                const supplierName = selectedSupplier ? selectedSupplier['TÊN NHÀ CUNG CẤP'] : '';

                // Tạo workbook mới
                const wb = XLSX.utils.book_new();

                // Tạo worksheet đầu tiên cho thông tin chung
                const generalInfo = [
                    ['PHIẾU MUA HÀNG'],
                    [],
                    ['Số chứng từ:', document.getElementById('soChungTu').value],
                    ['Thời gian:', new Date(document.getElementById('thoiGian').value).toLocaleString('vi-VN')],
                    ['Nhà cung cấp:', supplierName],
                    ['Người tạo:', document.getElementById('nguoiTao').value],
                    []
                ];

                // Thêm tiêu đề cho bảng chi tiết
                const headers = ['STT', 'Tên hàng', 'Số lượng', 'ĐVT', 'Đơn giá', 'Thành tiền', 'Ghi chú'];
                generalInfo.push(headers);

                // Thêm dữ liệu sản phẩm
                let totalAmount = 0;
                const rows = document.getElementById('purchaseDetails').getElementsByTagName('tr');
                Array.from(rows).forEach((row, index) => {
                    const quantity = parseFloat(row.querySelector('[data-quantity]').value);
                    const price = parseFloat(row.cells[8].querySelector('input').value);
                    const amount = quantity * price;
                    totalAmount += amount;

                    generalInfo.push([
                        index + 1,
                        row.cells[3].textContent,
                        quantity,
                        row.cells[5].textContent,
                        price,
                        amount,
                        row.cells[9].querySelector('input').value
                    ]);
                });

                // Thêm tổng cộng
                generalInfo.push(['', '', '', '', 'Tổng cộng:', totalAmount]);

                // Tạo worksheet và thêm vào workbook
                const ws = XLSX.utils.aoa_to_sheet(generalInfo);

                // Thiết lập style cho worksheet
                ws['!cols'] = [
                    { wch: 5 },  // STT
                    { wch: 30 }, // Tên hàng
                    { wch: 10 }, // Số lượng
                    { wch: 10 }, // ĐVT
                    { wch: 15 }, // Đơn giá
                    { wch: 15 }, // Thành tiền
                    { wch: 20 }  // Ghi chú
                ];

                // Thêm worksheet vào workbook
                XLSX.utils.book_append_sheet(wb, ws, 'Phiếu Mua Hàng');

                // Xuất file
                const fileName = `PhieuMuaHang_${document.getElementById('soChungTu').value}.xlsx`;
                XLSX.writeFile(wb, fileName);

                showToast('Xuất Excel thành công!', 'success');
            } catch (error) {
                console.error('Lỗi khi xuất Excel:', error);
                showToast('Có lỗi xảy ra khi xuất Excel', 'error');
            } finally {
                hideLoading();
            }
        }
        // Reset form
        function resetForm() {
           
            document.getElementById('purchaseForm').reset();
            document.getElementById('purchaseDetails').innerHTML = '';
            document.getElementById('productSidebar').classList.add('hidden');
            currentSupplierProducts = [];

            const now = new Date();
            now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
            document.getElementById('thoiGian').value = now.toISOString().slice(0, 16);
            currentPurchaseId = 'MUA' + Date.now();
            document.getElementById('idMua').value = currentPurchaseId;
        }

        // Initialize the page
        document.addEventListener('DOMContentLoaded', function () {
            initializeData();
            const urlParams = new URLSearchParams(window.location.search);
            manv = urlParams.get('manv');
            document.getElementById('nguoiTao').value = manv;
            document.getElementById('idMua').value = currentPurchaseId;

            const now = new Date();
            now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
            document.getElementById('thoiGian').value = now.toISOString().slice(0, 16);
        });
    </script>

</body>

</html>