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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quản lý Đơn Hàng</title>
    <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;
        }

        #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;
        }

        #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">
                <h1 class="text-2xl font-bold text-gray-800">Quản lý đơn hàng</h1>
                <div class="flex items-center space-x-4">
                    <button hidden id="toggleBatchMode" onclick="toggleBatchMode()"
                        class="px-4 py-2 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors">
                        Chọn nhiều
                    </button>
                    <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>Order KD</th>
                            <th>Tên chi tiết</th>
                            <th>Số file</th>
                            <th>SLL</th>
                            <th>Thời hạn</th>
                            <th>Ngày nhận phôi</th>
                            <th>Tính chất</th>
                            <th>Gia công mới</th>
                            <th>Nơi gia công</th>
                            <th>Ưu tiên</th>
                            <th>Trạng thái</th>
                            <th>Thao tác</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Batch Actions -->


    <!-- 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 = '006e80f4-248c-4b31-99df-a5c860c84ccf';
        const ACCESS_KEY = 'V2-tkExJ-FiFcC-LMbUy-kBrAL-jaUws-OVrAd-4VOko-jzEUI';
        const REGION = 'www';
        const API_URL = `https://${REGION}.appsheet.com/api/v2/apps/${APP_ID}/tables`;

        // Product template 
        const PRODUCT_TEMPLATE = {
            order_kd: '',
            ten_chi_tiet: '',
            so_file: '',
            sll: '',
            thoi_han: '',
            ngay_nhan_phoi: '',
            tinh_chat: '',
            gia_cong_moi: '',
            noi_gia_cong: '',
            uu_tien: '',
            trang_thai: ''
        };
        // State Management
        const state = {
            lastProductId: 0,
            products: new Map(),
            tinhChat: ['Gấp', 'Bình thường'],
            uuTien: ['Cao', 'Trung bình', 'Thấp'],
            trangThai: ['Mới', 'Đang xử lý', 'Hoàn thành']
        };

        // 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();
            }
        };

        // 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;
            },



        };


        // Keyboard Shortcuts
        document.addEventListener('keydown', (e) => {
            if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
                e.preventDefault();
                addNewRow();
            }
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                e.preventDefault();
                saveAllProducts();
            }
        });


        function addNewRow() {
            const tbody = document.querySelector('#productsTable tbody');
            const productId = utils.createUniqueId();
            const product = {
                id: productId,
                ...PRODUCT_TEMPLATE,
                order_kd: ''
            };
            state.products.set(productId, product);

            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="${product.order_kd}"
                  placeholder="Order KD"
                  onchange="handleInputChange(event, '${productId}', 'order_kd')">
       </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"
                  placeholder="Tên chi tiết"
                  onchange="handleInputChange(event, '${productId}', 'ten_chi_tiet')">
       </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"
                  placeholder="Số file" 
                  onchange="handleInputChange(event, '${productId}', 'so_file')">
       </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"
                  placeholder="SLL"
                  onchange="handleInputChange(event, '${productId}', 'sll')">
       </td>
       <td class="border-r border-gray-200 p-0">
           <input type="date"
                  class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                  onchange="handleInputChange(event, '${productId}', 'thoi_han')">
       </td>
       <td class="border-r border-gray-200 p-0">
           <input type="date"
                  class="w-full h-full px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:bg-blue-50"
                  onchange="handleInputChange(event, '${productId}', 'ngay_nhan_phoi')">
       </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}', 'tinh_chat')">
               <option value="">Chọn tính chất</option>
               ${state.tinhChat.map(opt => `<option value="${opt}">${opt}</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}', 'gia_cong_moi')">
               <option value="">Chọn loại</option>
               <option value="Có">Có</option>
               <option value="Không">Không</option>
           </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"
                  placeholder="Nơi gia công"
                  onchange="handleInputChange(event, '${productId}', 'noi_gia_cong')">
       </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}', 'uu_tien')">
               <option value="">Chọn độ ưu tiên</option>
               ${state.uuTien.map(opt => `<option value="${opt}">${opt}</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}', 'trang_thai')">
               <option value="">Chọn trạng thái</option>
               ${state.trangThai.map(opt => `<option value="${opt}">${opt}</option>`).join('')}
           </select>
       </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 đơn hàng">
                   <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>
           </div>
       </td>
   `;

            tbody.appendChild(row);
        }


        // 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) {
                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
                // Validate data
                const invalidProducts = productsArray.filter(p => !p.order_kd || !p.ten_chi_tiet);
                if (invalidProducts.length > 0) {
                    toast.warning('Vui lòng điền đầy đủ Order KD và tên chi tiết cho tất cả đơn hàng');
                    loadingUtils.hide();
                    return;
                }

                // Calculate total steps
                const productsWithNewImages = productsArray.filter(p => p.imageBase64 && !p.image);
                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.image = 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.name}"`);
                                return 'https://i.ibb.co/cYHCSgp/image.png';
                            })
                    );

                    await Promise.all(uploadPromises);
                }

                // Format data
                loadingUtils.updateProgress(80);
                const formattedProducts = productsArray.map(product => ({
                    "order_kd": product.order_kd,
                    "ten_chi_tiet": product.ten_chi_tiet,
                    "so_file": product.so_file,
                    "sll": product.sll,
                    "thoi_han": product.thoi_han,
                    "ngay_nhan_phoi": product.ngay_nhan_phoi,
                    "tinh_chat": product.tinh_chat,
                    "gia_cong_moi": product.gia_cong_moi,
                    "noi_gia_cong": product.noi_gia_cong,
                    "uu_tien": product.uu_tien,
                    "trang_thai": product.trang_thai
                }));

                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('Don_hang', '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 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['ORDER KD'] || row['TÊN CHI TIẾT']) {
                        const productId = utils.createUniqueId();
                        const product = {
                            id: productId,
                            order_kd: row['ORDER KD'] || utils.generateOrderCode(),
                            ten_chi_tiet: row['TÊN CHI TIẾT'] || '',
                            so_file: row['SỐ FILE'] || '',
                            sll: row['SLL'] || '',
                            thoi_han: row['THỜI HẠN'] || '',
                            ngay_nhan_phoi: row['NGÀY NHẬN PHÔI'] || '',
                            tinh_chat: row['TÍNH CHẤT'] || '',
                            gia_cong_moi: row['GIA CÔNG MỚI'] || '',
                            noi_gia_cong: row['NƠI GIA CÔNG'] || '',
                            uu_tien: row['ƯU TIÊN'] || '',
                            trang_thai: row['TRẠNG THÁI'] || ''
                        };
                        state.products.set(productId, product);
                        addExistingProduct(product);
                        importCount++;
                    }
                });

                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 = '';

            // Reset state
            state.products.clear();
            state.lastProductId = 0;

            // Reset batch mode
            if (state.batchMode) {
                toggleBatchMode();
            }

            // Add one empty row
            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 = `
       
        <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.order_kd || ''}"
                   placeholder="Order KD"
                   onchange="handleInputChange(event, '${product.id}', 'order_kd')">
        </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.ten_chi_tiet || ''}"
                   placeholder="Tên chi tiết"
                   onchange="handleInputChange(event, '${product.id}', 'ten_chi_tiet')">
        </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.so_file || ''}"
                   placeholder="Số file"
                   onchange="handleInputChange(event, '${product.id}', 'so_file')">
        </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.sll || ''}"
                   placeholder="SLL"
                   onchange="handleInputChange(event, '${product.id}', 'sll')">
        </td>
        <td class="border-r border-gray-200 p-0">
            <input type="date"
                   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.thoi_han || ''}"
                   onchange="handleInputChange(event, '${product.id}', 'thoi_han')">
        </td>
        <td class="border-r border-gray-200 p-0">
            <input type="date"
                   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.ngay_nhan_phoi || ''}"
                   onchange="handleInputChange(event, '${product.id}', 'ngay_nhan_phoi')">
        </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}', 'tinh_chat')">
                <option value="">Chọn tính chất</option>
                ${state.tinhChat.map(opt => `
                    <option value="${opt}" ${product.tinh_chat === opt ? 'selected' : ''}>
                        ${opt}
                    </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}', 'gia_cong_moi')">
                <option value="">Chọn loại</option>
                <option value="Có" ${product.gia_cong_moi === 'Có' ? 'selected' : ''}>Có</option>
                <option value="Không" ${product.gia_cong_moi === 'Không' ? 'selected' : ''}>Không</option>
            </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.noi_gia_cong || ''}"
                   placeholder="Nơi gia công"
                   onchange="handleInputChange(event, '${product.id}', 'noi_gia_cong')">
        </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}', 'uu_tien')">
                <option value="">Chọn độ ưu tiên</option>
                ${state.uuTien.map(opt => `
                    <option value="${opt}" ${product.uu_tien === opt ? 'selected' : ''}>
                        ${opt}
                    </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}', 'trang_thai')">
                <option value="">Chọn trạng thái</option>
                ${state.trangThai.map(opt => `
                    <option value="${opt}" ${product.trang_thai === opt ? 'selected' : ''}>
                        ${opt}
                    </option>
                `).join('')}
            </select>
        </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 đơn hàng">
                    <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>
            </div>
        </td>
    `;

            tbody.appendChild(row);
        }


        // 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 dòng  này?')) return;

            const row = document.querySelector(`tr[data-product-id="${productId}"]`);
            if (row) {
                row.remove();
                state.products.delete(productId);
                toast.success('Bạn có chắc chắn muốn xóa dòng này');


            }
        }




        const utils = {

            generateOrderCode() {
                state.lastProductId++;
                return `DH${String(state.lastProductId).padStart(5, '0')}`;
            },
            createUniqueId() {
                return Date.now().toString(36) + Math.random().toString(36).substr(2);
            },

            validateProduct(product) {
                return product.name?.trim() && product.unit?.trim();
            }
        };

    </script>

</body>

</html>