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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TAT THÊM HÀNG HÓA</title>
    <link rel="shortcut icon"
        href="https://vienthongvina.com/assets/single/1/1/original/oNoWdRJ6Y6YneKeo7wa1X3ONVdJx86YNoCJPpZid.png"
        type="image/x-icon">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.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="key.js"></script>
    <style>
        /* Custom scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        ::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #666;
        }

        /* Table styles */
        #productsTable {
            border-collapse: collapse;
        }

        .drop-zone:focus {
            outline: none;
        }

        .drop-zone:focus-visible {
            ring: 2px solid #3b82f6;
        }

        #productsTable th {
            background-color: #f8f9fa;
            border-bottom: 2px solid #dee2e6;
            border-right: 1px solid #dee2e6;
            padding: 8px;
            font-weight: 600;
            text-align: left;
            position: sticky;
            top: 0;
            z-index: 10;
        }

        .drop-zone {
            outline: none;
            transition: all 0.2s ease-in-out;
        }

        .drop-zone:focus-visible {
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.5);
        }

        .drop-zone.ring-2 {
            box-shadow: 0 0 0 2px #3b82f6;
        }

        #productsTable input:focus,
        #productsTable select:focus {
            outline: none;
            background-color: #f0f7ff;
        }
    </style>
</head>

<body class="bg-gray-50">
    <!-- Loading Overlay -->
    <div id="loadingOverlay" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-white p-6 rounded-lg shadow-xl">
            <div class="flex items-center space-x-3">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                <div id="loadingText" class="text-gray-700">Đang xử lý...</div>
            </div>
            <div id="progressContainer" class="mt-4 hidden">
                <div class="w-full bg-gray-200 rounded-full h-2.5">
                    <div id="progressBar" class="bg-blue-600 h-2.5 rounded-full transition-all duration-300"
                        style="width: 0%"></div>
                </div>
                <div id="progressText" class="text-sm text-gray-600 mt-1 text-center">0%</div>
            </div>
        </div>
    </div>

    <!-- Main Container -->
    <div class="mx-auto px-4 py-8">
        <div class="bg-white rounded-lg shadow-lg p-6">
            <!-- Header Section -->
            <div class="flex justify-between items-center mb-6">
                <img src="https://vienthongvina.com/assets/single/1/1/original/oNoWdRJ6Y6YneKeo7wa1X3ONVdJx86YNoCJPpZid.png"
                    alt="" width="50">
                <h1 class="text-2xl font-bold text-gray-800">Viễn thông VINA Quản lý sản phẩm</h1>
                <div class="flex items-center space-x-4">

                    <button id="addNewRow" onclick="addNewRow()"
                        class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors flex items-center gap-2">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                        </svg>
                        Thêm dòng
                    </button>
                    <button id="saveAll" onclick="saveAllProducts()"
                        class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors flex items-center gap-2">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
                        </svg>
                        Lưu tất cả
                    </button>
                </div>
            </div>

            <!-- Import Section -->
            <div class="mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200">
                <h2 class="text-lg font-semibold mb-3">Import từ Excel</h2>
                <div class="flex items-center gap-4">
                    <div class="flex-1">
                        <label for="excelFile"
                            class="block w-full p-4 border-2 border-dashed border-gray-300 rounded-lg text-center cursor-pointer hover:border-blue-500 transition-colors">
                            <span class="text-gray-600">Kéo thả file Excel hoặc click để chọn file</span>
                            <input type="file" id="excelFile" accept=".xlsx, .xls, .csv" class="hidden"
                                onchange="handleFileSelect(this)" />
                        </label>
                    </div>
                    <button onclick="importExcel()"
                        class="px-6 py-4 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                        </svg>
                        Import
                    </button>
                </div>
            </div>

            <!-- Products Table -->
            <div class="overflow-x-auto border border-gray-200 rounded-lg">
                <table id="productsTable" class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Mã sản phẩm (SKU)</th>

                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Danh mục</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Thông tin bổ sung</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Hãng</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Mô tả chung</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Mô tả sản phẩm</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Bảo hành</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Đơn vị</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Ghi chú</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Đơn giá nhập VND</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Tình trạng</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Hình ảnh</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                NPP</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Thao tác</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Batch Actions -->
    <div id="batchActions"
        class="hidden fixed bottom-8 left-1/2 transform -translate-x-1/2 bg-white px-6 py-4 rounded-lg shadow-xl flex items-center gap-4">
        <span class="text-gray-600" id="selectedCount">Đã chọn: 0</span>
        <button onclick="deleteBatchProducts()"
            class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors flex items-center gap-2">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
            </svg>
            Xóa đã chọn
        </button>
        <button onclick="copyBatchProducts()"
            class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors flex items-center gap-2">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
            </svg>
            Nhân bản
        </button>
    </div>

    <!-- Floating Action Buttons -->
    <div id="floatingButtons" class="fixed bottom-6 right-6 flex flex-col gap-3">
        <button onclick="addNewRow()"
            class="bg-green-600 hover:bg-green-700 text-white rounded-full p-4 shadow-lg transition-all hover:scale-105">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
        </button>
        <button onclick="saveAllProducts()"
            class="bg-blue-600 hover:bg-blue-700 text-white rounded-full p-4 shadow-lg transition-all hover:scale-105">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
            </svg>
        </button>
    </div>

    <script>
        // Constants
        const APP_ID = '488f53fb-4101-4c48-b66f-de46b6b970a8';
        const ACCESS_KEY = 'V2-WbXPl-IDhvX-EtG2O-7hMVJ-xV4al-R9dKt-7pjLp-BQ4jU';
        const REGION = 'www';
        const API_URL = `https://${REGION}.appsheet.com/api/v2/apps/${APP_ID}/tables`;
        const IMGBB_API_KEY = '7267d539a8c541130ce4524afdc69ad3';
        const statusOptions = [
            'Hết hàng',
            'Bỏ mẫu'
        ];
        // State Management
        const state = {
            lastProductId: 0,
            products: new Map(),
            categories: [],
            brands: [],
            units: ['Cái', 'Bộ', 'Chiếc', 'Hộp', 'Cuốn', 'Mét', 'Kg', 'Gram', 'Lít', 'Chai', 'Gói', 'Túi', 'Thùng', 'Tấm', 'Bình'],
            batchMode: false
        };
        const warrantyOptions = [
            { value: '12 tháng', label: '12 tháng' },
            { value: '24 tháng', label: '24 tháng' },
            { value: '03 tháng', label: '03 tháng' },
            { value: '06 tháng', label: '06 tháng' }
        ];
        // Toast Utilities
        const toast = {
            success(message) {
                Toastify({
                    text: message,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    style: { background: "#4CAF50" },
                }).showToast();
            },
            error(message) {
                Toastify({
                    text: message,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    style: { background: "#f44336" },
                }).showToast();
            },
            warning(message) {
                Toastify({
                    text: message,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    style: { background: "#ff9800" },
                }).showToast();
            },
            info(message) {
                Toastify({
                    text: message,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    style: { background: "#2196F3" },
                }).showToast();
            }
        };
        // Hàm để lấy danh sách phân nhóm từ CAIDAT_HH
        async function fetchCategories() {
            try {
                const response = await apiRequest('Danh mục sản phẩm', 'Find', {}, {});
                if (response && Array.isArray(response)) {
                    state.categories = response.map(item => item['Danh mục']).filter(Boolean);
                    updateCategorySelectBoxes();
                }
            } catch (error) {
                console.error('Error fetching categories:', error);
                toast.error('Cannot load categories');
            }
        }
        async function fetchBrands() {
            try {
                const response = await apiRequest('Cài đặt', 'Find', {},
                    { "Selector": `Filter(Cài đặt, AND([Nhóm]="Quản lý sản phẩm",[Hạng mục]="Thương hiệu"))`, });
                if (response && Array.isArray(response)) {
                    state.brands = response.map(item => item.ID).filter(Boolean);
                    updateBrandSelectBoxes();
                }
            } catch (error) {
                console.error('Error fetching brands:', error);
                toast.error('Cannot load brands');
            }
        }
        async function initialize() {
            try {
                loadingUtils.show('Đang tải dữ liệu...', true);
                await Promise.all([
                    fetchCategories(),
                    fetchBrands()
                ]);
                loadingUtils.hide();
                addNewRow();
            } catch (error) {
                loadingUtils.hide();
                console.error('Error initializing:', error);
                toast.error('Error initializing application');
            }
        }
        function updateCategorySelectBoxes() {
            const selects = document.querySelectorAll('select[onchange*="nhom_hang_hoa"]');
            selects.forEach(select => {
                const currentValue = select.value;
                select.innerHTML = `
            <option value="">Phân loại</option>
            ${state.categories.map(cat => `
                <option value="${cat}" ${currentValue === cat ? 'selected' : ''}>
                    ${cat}
                </option>
            `).join('')}
        `;
            });
        }
        function updateBrandSelectBoxes() {
            const selects = document.querySelectorAll('select[onchange*="hang"]');
            selects.forEach(select => {
                const currentValue = select.value;
                select.innerHTML = `
            <option value="">Chọn hãng</option>
            ${state.brands.map(brand => `
                <option value="${brand}" ${currentValue === brand ? 'selected' : ''}>
                    ${brand}
                </option>
            `).join('')}
        `;
            });
        }
        // Loading Utilities
        const loadingUtils = {
            overlay: null,
            progressBar: null,
            progressText: null,
            progressContainer: null,
            loadingText: null,

            init() {
                this.overlay = document.getElementById('loadingOverlay');
                this.progressBar = document.getElementById('progressBar');
                this.progressText = document.getElementById('progressText');
                this.progressContainer = document.getElementById('progressContainer');
                this.loadingText = document.getElementById('loadingText');
            },

            show(message = 'Đang xử lý...', showProgress = false) {
                if (!this.overlay) this.init();
                this.loadingText.textContent = message;
                this.overlay.classList.remove('hidden');
                if (showProgress) {
                    this.progressContainer.classList.remove('hidden');
                    this.updateProgress(0);
                } else {
                    this.progressContainer.classList.add('hidden');
                }
            },

            hide() {
                if (!this.overlay) this.init();
                this.overlay.classList.add('hidden');
                this.progressContainer.classList.add('hidden');
            },

            updateProgress(percent) {
                if (!this.progressBar) this.init();
                this.progressBar.style.width = `${percent}%`;
                this.progressText.textContent = `${percent}%`;
            }
        };

        // DOM Utilities
        const dom = {
            getProductRow(element) {
                return element.closest('tr');
            },

            getProductId(row) {
                return row.dataset.productId;
            },





        };

        // Event Handlers
        const handlers = {
            async handleImageUpload(event, productId) {
                const file = event.target.files[0];
                if (!file) return;

                const row = document.querySelector(`tr[data-product-id="${productId}"]`);
                const imgPreview = row.querySelector('.image-preview');
                const dropZone = row.querySelector('.drop-zone');

                try {
                    const base64 = await this.fileToBase64(file);
                    imgPreview.src = base64;
                    imgPreview.classList.remove('hidden');
                    dropZone.classList.add('has-image');

                    const product = state.products.get(productId);
                    if (product) {
                        product.imageBase64 = base64;
                        product.image = '';
                        state.products.set(productId, product);
                    }
                } catch (error) {
                    console.error('Error handling image:', error);
                    toast.error('Lỗi khi xử lý ảnh. Vui lòng thử lại.');
                }
            },

            fileToBase64(file) {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.readAsDataURL(file);
                    reader.onload = () => resolve(reader.result);
                    reader.onerror = error => reject(error);
                });
            },



        };

        // Sửa lại hàm setupDragAndDrop để thêm focus handling
        function setupDragAndDrop(row) {
            const dropZone = row.querySelector('.drop-zone');
            if (!dropZone) return;

            // Thêm khả năng focus
            dropZone.setAttribute('tabindex', '0');

            // Thêm visual feedback cho focus
            dropZone.addEventListener('focus', () => {
                dropZone.classList.add('ring-2', 'ring-blue-500');
            });

            dropZone.addEventListener('blur', () => {
                dropZone.classList.remove('ring-2', 'ring-blue-500');
            });

            // Xử lý các sự kiện drag & drop
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                dropZone.addEventListener(eventName, (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                });
            });

            // Highlight khi drag over
            ['dragenter', 'dragover'].forEach(eventName => {
                dropZone.addEventListener(eventName, () => {
                    dropZone.classList.add('bg-blue-50');
                });
            });

            // Remove highlight
            ['dragleave', 'drop'].forEach(eventName => {
                dropZone.addEventListener(eventName, () => {
                    dropZone.classList.remove('bg-blue-50');
                });
            });

            // Xử lý drop
            dropZone.addEventListener('drop', (e) => {
                const file = e.dataTransfer.files[0];
                if (file?.type.startsWith('image/')) {
                    const productId = row.dataset.productId;
                    handlers.handleImageUpload({ target: { files: [file] } }, productId);
                }
            });
        }

        async function addNewRow() {
            const tbody = document.querySelector('#productsTable tbody');
            const productId = utils.createUniqueId();
            const productCode = utils.generateProductCode();

            const product = {
                id: productId,
                'Mã sản phẩm (SKU)': '',
                'Danh mục': '',
                'Thông tin bổ sung': '',
                'Hãng': '',
                'Mô tả chung sản phẩm': '',
                'Mô tả sản phẩm': '',
                'Bảo hành': '',
                'Đơn vị': '',
                'Ghi chú / Note': '',
                'Đơn giá nhập VND': 0,
                'Tình trạng': '',
                'Hình ảnh': '',
                'NPP': ''
            };
            state.products.set(productId, product);

            // Row template
            const row = document.createElement('tr');
            row.dataset.productId = productId;
            row.className = 'hover:bg-gray-50 border-b border-gray-200';

            row.innerHTML = `
        <td class="border-r border-gray-200 p-0">
            <input type="text" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value=""
                   placeholder="Nhập mã SP"
                   onchange="handleInputChange(event, '${productId}', 'Mã sản phẩm (SKU)')">
        </td>
   
        <td class="border-r border-gray-200 p-0">
            <select class="w-full h-full px-2 py-1 border-0 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                    onchange="handleInputChange(event, '${productId}', 'Danh mục')">
                <option value="">Chọn danh mục</option>
                ${state.categories.map(cat => `<option value="${cat}">${cat}</option>`).join('')}
            </select>
        </td>
        <td class="border-r border-gray-200 p-0">
            <textarea type="text" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value=""
                   placeholder="Nhập thông tin bổ sung"
                   onchange="handleInputChange(event, '${productId}', 'Thông tin bổ sung')"></textarea>
        </td>
        <td class="border-r border-gray-200 p-0">
            <select class="w-full h-full px-2 py-1 border-0 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                    onchange="handleInputChange(event, '${productId}', 'Hãng')">
                <option value="">Chọn hãng</option>
                ${state.brands.map(brand => `<option value="${brand}">${brand}</option>`).join('')}
            </select>
        </td>
       <td class="border-r border-gray-200 p-0">
    <textarea
        class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50 resize-y min-h-[38px]"
        placeholder="Nhập mô tả chung"
        onchange="handleInputChange(event, '${product.id}', 'Mô tả chung sản phẩm')"
    >${product['Mô tả chung sản phẩm'] || ''}</textarea>
</td>
        <td class="border-r border-gray-200 p-0">
            <textarea type="text" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value=""
                   placeholder="Nhập mô tả sản phẩm"
                   onchange="handleInputChange(event, '${productId}', 'Mô tả sản phẩm')"></textarea>
        </td>
        <td class="border-r border-gray-200 p-0">
            <select class="w-full h-full px-2 py-1 border-0 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                    onchange="handleInputChange(event, '${productId}', 'Bảo hành')">
                <option value="">Chọn bảo hành</option>
                ${warrantyOptions.map(opt => `<option value="${opt.value}">${opt.label}</option>`).join('')}
            </select>
        </td>
        <td class="border-r border-gray-200 p-0">
            <select class="w-full h-full px-2 py-1 border-0 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                    onchange="handleInputChange(event, '${productId}', 'Đơn vị')">
                <option value="">Chọn đơn vị</option>
                ${state.units.map(unit => `<option value="${unit}">${unit}</option>`).join('')}
            </select>
        </td>
        <td class="border-r border-gray-200 p-0">
            <input type="text" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value=""
                   placeholder="Nhập ghi chú"
                   onchange="handleInputChange(event, '${productId}', 'Ghi chú / Note')">
        </td>
        <td class="border-r border-gray-200 p-0">
            <input type="number" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value="0"
                   placeholder="Nhập đơn giá"
                   onchange="handleInputChange(event, '${productId}', 'Đơn giá nhập VND')">
        </td>
        <td class="border-r border-gray-200 p-0">
            <select class="w-full h-full px-2 py-1 border-0 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                    onchange="handleInputChange(event, '${productId}', 'Tình trạng')">
                <option value="">Chọn tình trạng</option>
                ${statusOptions.map(status => `<option value="${status}">${status}</option>`).join('')}
            </select>
        </td>
       <td class="border-r border-gray-200 p-2">
    <div class="drop-zone flex items-center justify-center gap-2 rounded border border-dashed border-gray-300 hover:border-blue-500 transition-colors min-h-[100px] min-w-[150px]">
        <img class="image-preview w-20 h-20 object-cover rounded ${product['Hình ảnh'] ? '' : 'hidden'}" 
             src="${product['Hình ảnh'] || ''}" alt="Preview">
        <label class="cursor-pointer flex-1 text-center py-3 px-4">
            <input type="file" 
                   accept="image/*" 
                   class="hidden" 
                   onchange="handlers.handleImageUpload(event, '${product.id}')">
            <span class="text-blue-600 hover:text-blue-700">Chọn ảnh</span>
        </label>
    </div>
</td>
        <td class="border-r border-gray-200 p-0">
            <input type="text" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value=""
                   placeholder="Nhập NPP"
                   onchange="handleInputChange(event, '${productId}', 'NPP')">
        </td>
        <td class="p-1 text-center">
            <div class="flex items-center justify-center gap-1">
                <button onclick="deleteProduct('${productId}')" 
                        class="text-gray-400 hover:text-red-600 transition-colors p-1"
                        title="Xóa sản phẩm">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                              d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                    </svg>
                </button>
                <button onclick="duplicateProduct('${productId}')" 
                        class="text-gray-400 hover:text-blue-600 transition-colors p-1"
                        title="Nhân bản sản phẩm">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                              d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                    </svg>
                </button>
            </div>
        </td>`;

            tbody.appendChild(row);
            setupDragAndDrop(row);

            const skuInput = row.querySelector('input[placeholder="Nhập mã SP"]');
            if (skuInput) skuInput.focus();
        }

        // Thêm hàm xử lý thay đổi input
        function handleInputChange(event, productId, field) {
            const value = event.target.value;
            const product = state.products.get(productId);
            if (product) {
                // Xử lý đặc biệt cho các trường số
                if (['he_so_quy_doi', 'gia_mua_si', 'gia_mua_le', 'gia_ban_si', 'gia_ban_le'].includes(field)) {
                    product[field] = parseFloat(value) || 0;
                } else {
                    product[field] = value;
                }
                state.products.set(productId, product);
            }
        }
        async function saveAllProducts() {
            try {
                loadingUtils.show('Đang xử lý dữ liệu...', true);
                const productsArray = Array.from(state.products.values());

                // Validate data
                const invalidProducts = productsArray.filter(p => !p['Mã sản phẩm (SKU)']);
                if (invalidProducts.length > 0) {
                    toast.warning('Vui lòng điền đầy đủ tên và mã sản phẩm cho tất cả sản phẩm');
                    loadingUtils.hide();
                    return;
                }

                // Calculate total steps
                const productsWithNewImages = productsArray.filter(p => p.imageBase64 && !p['Hình ảnh']);
                const totalSteps = productsWithNewImages.length + 2;
                let currentStep = 0;

                // Upload images
                if (productsWithNewImages.length > 0) {
                    toast.info(`Đang xử lý ${productsWithNewImages.length} ảnh...`);

                    const uploadPromises = productsWithNewImages.map((product, index) =>
                        uploadToImgbb(product.imageBase64)
                            .then(url => {
                                product['Hình ảnh'] = url;
                                delete product.imageBase64;
                                loadingUtils.updateProgress(Math.round((index + 1) / productsWithNewImages.length * 60));
                                return url;
                            })
                            .catch(error => {
                                console.error('Error uploading image:', error);
                                toast.error(`Lỗi khi tải ảnh cho sản phẩm "${product['Mã sản phẩm (SKU)']}"`);
                                return 'https://i.ibb.co/cYHCSgp/image.png';
                            })
                    );

                    await Promise.all(uploadPromises);
                }

                loadingUtils.updateProgress(80);
                const formattedProducts = productsArray.map(product => ({
                    'Mã sản phẩm (SKU)': product['Mã sản phẩm (SKU)'],
                    'Danh mục': product['Danh mục'],
                    'Thông tin bổ sung': product['Thông tin bổ sung'],
                    'Hãng': product['Hãng'],
                    'Mô tả chung sản phẩm': product['Mô tả chung sản phẩm'],
                    'Mô tả sản phẩm': product['Mô tả sản phẩm'],
                    'Bảo hành': product['Bảo hành'],
                    'Đơn vị': product['Đơn vị'],
                    'Ghi chú / Note': product['Ghi chú / Note'],
                    'Đơn giá nhập VND': parseFloat(product['Đơn giá nhập VND']) || 0,
                    'Tình trạng': product['Tình trạng'],
                    'Link ảnh Sản phẩm': product['Hình ảnh'] || 'https://i.ibb.co/cYHCSgp/image.png',
                    'NPP': product['NPP']
                }));

                if (formattedProducts.length === 0) {
                    toast.warning('Không có sản phẩm nào để lưu');
                    loadingUtils.hide();
                    return;
                }

                // Save data
                loadingUtils.updateProgress(90);
                await apiRequest('Sản phẩm', 'Add', { Rows: formattedProducts });

                loadingUtils.updateProgress(100);
                setTimeout(() => {
                    loadingUtils.hide();
                    toast.success('Lưu sản phẩm thành công!');
                    resetAfterSave();
                }, 500);

            } catch (error) {
                loadingUtils.hide();
                console.error('Lỗi khi lưu sản phẩm:', error);
                toast.error('Có lỗi xảy ra khi lưu dữ liệu: ' + error.message);
            }
        }


        const uploadToImgbb = async (base64Image) => {
            const base64Data = base64Image.split(',')[1];

            try {
                const formData = new FormData();
                formData.append('image', base64Data);

                const response = await axios.post('https://api.imgbb.com/1/upload', formData, {
                    params: {
                        key: IMGBB_API_KEY,
                    },
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });

                return response.data.data.url;
            } catch (error) {
                throw new Error('Lỗi khi upload ảnh');
            }
        };
        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;
            }
        };

        async function importExcel() {
            const input = document.getElementById('excelFile');
            const file = input.files[0];

            if (!file) {
                toast.warning('Vui lòng chọn file Excel');
                return;
            }

            try {
                loadingUtils.show('Đang đọc file Excel...', true);
                loadingUtils.updateProgress(30);

                const data = await readExcelFile(file);
                if (data.length === 0) {
                    toast.warning('File Excel không có dữ liệu');
                    loadingUtils.hide();
                    return;
                }

                let importCount = 0;
                data.forEach((row, index) => {
                    if (row['Tên hàng hóa'] || row['Mã sản phẩm (SKU)']) {
                        const productId = utils.createUniqueId();
                        const product = {
                            id: productId,
                            'Mã sản phẩm (SKU)': row['Mã sản phẩm (SKU)'] || '',
                            'Danh mục': row['Danh mục'] || '',
                            'Thông tin bổ sung': row['Thông tin bổ sung'] || '',
                            'Hãng': row['Hãng'] || '',
                            'Mô tả chung sản phẩm': row['Mô tả chung sản phẩm'] || '',
                            'Mô tả sản phẩm': row['Mô tả sản phẩm'] || '',
                            'Bảo hành': row['Bảo hành'] || '',
                            'Đơn vị': row['Đơn vị'] || '',
                            'Ghi chú / Note': row['Ghi chú / Note'] || '',
                            'Đơn giá nhập VND': parseFloat(row['Đơn giá nhập VND']) || 0,
                            'Tình trạng': row['Tình trạng'] || '',
                            'Hình ảnh': '',
                            'NPP': row['NPP'] || ''
                        };
                        state.products.set(productId, product);
                        addExistingProduct(product);
                        importCount++;
                    }
                    const progress = Math.min(30 + Math.round((index + 1) / data.length * 70), 100);
                    loadingUtils.updateProgress(progress);
                });

                input.value = '';
                setTimeout(() => {
                    loadingUtils.hide();
                    toast.success(`Đã import ${importCount} sản phẩm`);
                }, 500);

            } catch (error) {
                loadingUtils.hide();
                console.error('Error importing Excel:', error);
                toast.error('Có lỗi xảy ra khi import file Excel');
            }
        }



        // Reset after save function
        function resetAfterSave() {
            // Clear the table
            const tbody = document.querySelector('#productsTable tbody');
            tbody.innerHTML = '';

            state.products.clear();
            state.lastProductId = 0;
            addNewRow();
        }

        // Duplicate product function
        function duplicateProduct(productId) {
            const originalProduct = state.products.get(productId);
            if (!originalProduct) return;

            const newProduct = {
                ...originalProduct,
                id: utils.createUniqueId(),
                code: utils.generateProductCode()
            };

            // Add to state
            state.products.set(newProduct.id, newProduct);

            addExistingProduct(newProduct);
            toast.success('Đã nhân bản sản phẩm thành công');
        }

        function addExistingProduct(product) {
            const tbody = document.querySelector('#productsTable tbody');
            const row = document.createElement('tr');
            row.dataset.productId = product.id;
            row.className = 'hover:bg-gray-50 border-b border-gray-200';

            row.innerHTML = `
        ${state.batchMode ? `
            <td class="border-r border-gray-200 p-0">
                <input type="checkbox" class="form-checkbox h-4 w-4 text-blue-600 rounded m-2"
                       onchange="updateBatchActionVisibility()">
            </td>
        ` : ''}
        <td class="border-r border-gray-200 p-0">
            <input type="text" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value="${product['Mã sản phẩm (SKU)'] || ''}"
                   placeholder="Nhập mã SP"
                   onchange="handleInputChange(event, '${product.id}', 'Mã sản phẩm (SKU)')">
        </td>
    
        <td class="border-r border-gray-200 p-0">
            <select class="w-full h-full px-2 py-1 border-0 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                    onchange="handleInputChange(event, '${product.id}', 'Danh mục')">
                <option value="">Chọn danh mục</option>
                ${state.categories.map(cat => `
                    <option value="${cat}" ${product['Danh mục'] === cat ? 'selected' : ''}>
                        ${cat}
                    </option>
                `).join('')}
            </select>
        </td>
        <td class="border-r border-gray-200 p-0">
            <textarea type="text" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value="${product['Thông tin bổ sung'] || ''}"
                   placeholder="Nhập thông tin bổ sung"
                   onchange="handleInputChange(event, '${product.id}', 'Thông tin bổ sung')"></textarea>
        </td>
        <td class="border-r border-gray-200 p-0">
            <select class="w-full h-full px-2 py-1 border-0 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                    onchange="handleInputChange(event, '${product.id}', 'Hãng')">
                <option value="">Chọn hãng</option>
                ${state.brands.map(brand => `
                    <option value="${brand}" ${product['Hãng'] === brand ? 'selected' : ''}>
                        ${brand}
                    </option>
                `).join('')}
            </select>
        </td>
        <td class="border-r border-gray-200 p-0">
            <textarea 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value="${product['Mô tả chung sản phẩm'] || ''}"
                   placeholder="Nhập mô tả chung"
                   onchange="handleInputChange(event, '${product.id}', 'Mô tả chung sản phẩm')"> </textarea>
        </td>
        <td class="border-r border-gray-200 p-0">
            <textarea type="text" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value="${product['Mô tả sản phẩm'] || ''}"
                   placeholder="Nhập mô tả sản phẩm"
                   onchange="handleInputChange(event, '${product.id}', 'Mô tả sản phẩm')"> </textarea>
        </td>
        <td class="border-r border-gray-200 p-0">
            <select class="w-full h-full px-2 py-1 border-0 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                    onchange="handleInputChange(event, '${product.id}', 'Bảo hành')">
                <option value="">Chọn bảo hành</option>
                ${warrantyOptions.map(opt => `
                    <option value="${opt.value}" ${product['Bảo hành'] === opt.value ? 'selected' : ''}>
                        ${opt.label}
                    </option>
                `).join('')}
            </select>
        </td>
        <td class="border-r border-gray-200 p-0">
            <select class="w-full h-full px-2 py-1 border-0 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                    onchange="handleInputChange(event, '${product.id}', 'Đơn vị')">
                <option value="">Chọn đơn vị</option>
                ${state.units.map(unit => `
                    <option value="${unit}" ${product['Đơn vị'] === unit ? 'selected' : ''}>
                        ${unit}
                    </option>
                `).join('')}
            </select>
        </td>
        <td class="border-r border-gray-200 p-0">
            <input type="text" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value="${product['Ghi chú / Note'] || ''}"
                   placeholder="Nhập ghi chú"
                   onchange="handleInputChange(event, '${product.id}', 'Ghi chú / Note')">
        </td>
        <td class="border-r border-gray-200 p-0">
            <input type="number" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value="${product['Đơn giá nhập VND'] || '0'}"
                   placeholder="Nhập đơn giá"
                   onchange="handleInputChange(event, '${product.id}', 'Đơn giá nhập VND')">
        </td>
        <td class="border-r border-gray-200 p-0">
            <select class="w-full h-full px-2 py-1 border-0 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                    onchange="handleInputChange(event, '${product.id}', 'Tình trạng')">
                <option value="">Chọn tình trạng</option>
                ${statusOptions.map(status => `
                    <option value="${status}" ${product['Tình trạng'] === status ? 'selected' : ''}>
                        ${status}
                    </option>
                `).join('')}
            </select>
        </td>
    <td class="border-r border-gray-200 p-2">
    <div class="drop-zone flex items-center justify-center gap-2 rounded border border-dashed border-gray-300 hover:border-blue-500 transition-colors min-h-[100px] min-w-[150px]">
        <img class="image-preview w-20 h-20 object-cover rounded ${product['Hình ảnh'] ? '' : 'hidden'}" 
             src="${product['Hình ảnh'] || ''}" alt="Preview">
        <label class="cursor-pointer flex-1 text-center py-3 px-4">
            <input type="file" 
                   accept="image/*" 
                   class="hidden" 
                   onchange="handlers.handleImageUpload(event, '${product.id}')">
            <span class="text-blue-600 hover:text-blue-700">Chọn ảnh</span>
        </label>
    </div>
</td>
        <td class="border-r border-gray-200 p-0">
            <input type="text" 
                   class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                   value="${product['NPP'] || ''}"
                   placeholder="Nhập NPP"
                   onchange="handleInputChange(event, '${product.id}', 'NPP')">
        </td>
        <td class="p-1 text-center">
            <div class="flex items-center justify-center gap-1">
                <button onclick="deleteProduct('${product.id}')" 
                        class="text-gray-400 hover:text-red-600 transition-colors p-1"
                        title="Xóa sản phẩm">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                              d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                    </svg>
                </button>
                <button onclick="duplicateProduct('${product.id}')" 
                        class="text-gray-400 hover:text-blue-600 transition-colors p-1"
                        title="Nhân bản sản phẩm">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                              d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                    </svg>
                </button>
            </div>
        </td>
    `;

            tbody.appendChild(row);
            setupDragAndDrop(row);
        }


        // Hàm xử lý paste toàn cục
        async function handleGlobalPaste(event) {
            const items = event.clipboardData?.items;
            if (!items) return;

            // Tìm và xử lý ảnh từ clipboard
            for (const item of items) {
                if (item.type.startsWith('image/')) {
                    const blob = item.getAsFile();
                    if (!blob) continue;

                    // Tìm drop zone đang được focus
                    const dropZone = document.activeElement?.closest('.drop-zone');
                    if (!dropZone) {
                        toast.info('Vui lòng chọn ô ảnh trước khi paste');
                        return;
                    }

                    try {
                        const row = dropZone.closest('tr');
                        if (!row) return;

                        const productId = row.dataset.productId;
                        if (!productId) return;

                        // Xử lý ảnh
                        await handlePastedImage(blob, productId);
                        toast.success('Đã paste ảnh thành công');
                    } catch (error) {
                        console.error('Error handling pasted image:', error);
                        toast.error('Có lỗi khi paste ảnh');
                    }
                    break;
                }
            }
        }

        // Hàm xử lý ảnh sau khi paste
        async function handlePastedImage(blob, productId) {
            // Chuyển blob thành base64
            const base64 = await blobToBase64(blob);

            // Cập nhật preview và lưu vào state
            const row = document.querySelector(`tr[data-product-id="${productId}"]`);
            if (!row) return;

            const imgPreview = row.querySelector('.image-preview');
            const dropZone = row.querySelector('.drop-zone');

            if (imgPreview && dropZone) {
                imgPreview.src = base64;
                imgPreview.classList.remove('hidden');
                dropZone.classList.add('has-image');

                const product = state.products.get(productId);
                if (product) {
                    product.imageBase64 = base64;
                    product.image = '';
                    state.products.set(productId, product);
                }
            }
        }

        // Hàm chuyển blob thành base64
        function blobToBase64(blob) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = () => resolve(reader.result);
                reader.onerror = reject;
                reader.readAsDataURL(blob);
            });
        }

        document.addEventListener('paste', handleGlobalPaste);
        // Function to handle file select for Excel import
        function handleFileSelect(input) {
            const file = input.files[0];
            if (file) {
                const fileName = file.name;
                const fileExt = fileName.split('.').pop().toLowerCase();

                if (!['xlsx', 'xls', 'csv'].includes(fileExt)) {
                    toast.error('Vui lòng chọn file Excel (.xlsx, .xls) hoặc CSV');
                    input.value = '';
                    return;
                }

                const fileLabel = input.parentElement.querySelector('span');
                fileLabel.textContent = fileName;
            }
        }

        // Function to read Excel file
        function readExcelFile(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();

                reader.onload = (e) => {
                    try {
                        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);
                        resolve(jsonData);
                    } catch (error) {
                        reject(error);
                    }
                };

                reader.onerror = (error) => reject(error);
                reader.readAsArrayBuffer(file);
            });
        }

        // Delete product function
        function deleteProduct(productId) {
            if (!confirm('Bạn có chắc chắn muốn xóa sản phẩm này?')) return;

            const row = document.querySelector(`tr[data-product-id="${productId}"]`);
            if (row) {
                row.remove();
                state.products.delete(productId);
                toast.success('Đã xóa sản phẩm');

                // Update batch actions visibility if in batch mode
                if (state.batchMode) {
                    updateBatchActionVisibility();
                }
            }
        }


        function toggleAllProducts(checkbox) {
            const table = document.getElementById('productsTable');
            table.querySelectorAll('tbody tr input[type="checkbox"]')
                .forEach(cb => cb.checked = checkbox.checked);
            updateBatchActionVisibility();
        }

        function updateBatchActionVisibility() {
            const batchActions = document.getElementById('batchActions');
            const checkedBoxes = document.querySelectorAll('tbody tr input[type="checkbox"]:checked');
            const selectedCount = document.getElementById('selectedCount');

            selectedCount.textContent = `Đã chọn: ${checkedBoxes.length}`;
            batchActions.classList.toggle('hidden', checkedBoxes.length === 0);
        }

        function getSelectedProducts() {
            const selectedRows = document.querySelectorAll('tbody tr input[type="checkbox"]:checked');
            return Array.from(selectedRows).map(checkbox => dom.getProductId(dom.getProductRow(checkbox)));
        }

        function deleteBatchProducts() {
            const selectedIds = getSelectedProducts();
            if (!selectedIds.length) return;

            if (confirm(`Bạn có chắc chắn muốn xóa ${selectedIds.length} sản phẩm đã chọn?`)) {
                selectedIds.forEach(id => {
                    const row = document.querySelector(`tr[data-product-id="${id}"]`);
                    if (row) {
                        row.remove();
                        state.products.delete(id);
                    }
                });
                toast.success(`Đã xóa ${selectedIds.length} sản phẩm`);
                updateBatchActionVisibility();
            }
        }

        function copyBatchProducts() {
            const selectedIds = getSelectedProducts();
            if (!selectedIds.length) return;

            selectedIds.forEach(id => {
                const originalProduct = state.products.get(id);
                if (originalProduct) {
                    const newProduct = { ...originalProduct };
                    newProduct.id = utils.createUniqueId();
                    newProduct.code = utils.generateProductCode();
                    state.products.set(newProduct.id, newProduct);
                    addExistingProduct(newProduct);
                }
            });

            toast.success(`Đã nhân bản ${selectedIds.length} sản phẩm`);
        }

        // Utility Functions
        const utils = {
            generateProductCode() {
                state.lastProductId++;
                return `SP${String(state.lastProductId).padStart(5, '0')}`;
            },

            createUniqueId() {
                return Date.now().toString(36) + Math.random().toString(36).substr(2);
            },

            validateProduct(product) {
                return (
                    product['Mã sản phẩm (SKU)']?.trim() &&
                    product['Tên hàng hóa']?.trim() &&
                    product['Danh mục']?.trim() &&
                    product['Đơn vị']?.trim() &&
                    product['Đơn giá nhập VND'] >= 0
                );
            }
        };
        document.addEventListener('DOMContentLoaded', initialize);

        // Event Listeners
    </script>

</body>

</html>