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

        @media (max-width: 1000px) {
            .table-container {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }

            #productsTable th,
            #productsTable td {
                min-width: 150px;
            }

            .action-buttons {
                position: fixed;
                bottom: 0;
                left: 0;
                right: 0;
                padding: 10px;
                background: white;
                box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
                z-index: 100;
            }
        }

        #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">
                <div class="flex items-center gap-4 mb-4">
                    <input type="text" id="searchInput" placeholder="Tìm kiếm..." onkeyup="filterTable()"
                        class="px-3 py-2 border rounded">
                    <select id="filterColumn" onchange="filterTable()" class="px-2 py-1 border rounded">
                        <option value="all">Tất cả cột</option>
                        <option value="order_kd">Order KD</option>
                        <option value="ten_chi_tiet">Tên chi tiết</option>
                        <option value="tinh_chat">Tính chất</option>
                    </select>
                </div>

                <div class="flex justify-between items-center mb-4">
                    <div class="flex items-center gap-2">
                        <button onclick="deleteSelectedProducts()"
                            class="px-3 py-2 bg-red-600 text-white rounded hover:bg-red-700 flex items-center gap-1">
                            <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>
                            Xóa đã chọn
                        </button>
                        <button onclick="saveSelectedProducts()"
                            class="px-3 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 flex items-center gap-1">
                            <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 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 đã chọn
                        </button>
                    </div>
                    <div class="flex items-center gap-4">
                        <select id="pageSize" onchange="changePageSize()" class="px-2 py-1 border rounded">
                            <option value="50">50 dòng</option>
                            <option value="100">100 dòng</option>
                            <option value="200">200 dòng</option>
                            <option value="500">500 dòng</option>
                        </select>
                        
                        <div class="flex items-center gap-2">
                            <button onclick="previousPage()" class="px-2 py-1 border rounded">
                                &lt; Trước
                            </button>
                            <span id="pageInfo">Trang 1/1</span>
                            <button onclick="nextPage()" class="px-2 py-1 border rounded">
                                Sau &gt;
                            </button>
                        </div>
                    </div>
                  
                </div>
                <table id="productsTable" class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="w-10">
                                <input type="checkbox" class="w-4 h-4" onclick="toggleSelectAll(this)"
                                    title="Chọn tất cả">
                            </th>
                            <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>Ngày giao phôi SX AMJ</th> <!-- new -->
                            <th>Ngày bắt đầu gia công</th> <!-- new -->
                            <th>Gia công kết thúc</th> <!-- new -->
                            <th>Ngày giao phôi SX TXV</th> <!-- new -->
                            <th>Kết thúc TXV</th> <!-- new -->
                            <th>Ngày kết thúc về AMJ</th> <!-- new -->
                            <th>Ngày giao kho</th> <!-- new -->
                            <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: '',
            ngay_giao_phoi_sx_amj: '', // thêm
            ngay_bat_dau_gia_cong: '', // thêm  
            gia_cong_ket_thuc: '', // thêm
            ngay_giao_phoi_sx_txv: '', // thêm
            ket_thuc_txv: '', // thêm
            ngay_ket_thuc_ve_amj: '', // thêm
            ngay_giao_kho: '', // thêm
            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'],
            pagination: {
                currentPage: 1,
                pageSize: 50,
                totalPages: 1
            }
        };
        function toggleSelectAll(checkbox) {
            const checkboxes = document.querySelectorAll('tbody input[type="checkbox"]');
            checkboxes.forEach(cb => cb.checked = checkbox.checked);
        }
        function goToPage(page) {
    if (page >= 1 && page <= state.pagination.totalPages) {
        state.pagination.currentPage = page;
        updatePagination();
    }
}
        function getSelectedProductIds() {
            const selectedCheckboxes = document.querySelectorAll('tbody input[type="checkbox"]:checked');
            return Array.from(selectedCheckboxes).map(cb => cb.closest('tr').dataset.productId);
        }
        async function deleteSelectedProducts() {
            const selectedIds = getSelectedProductIds();
            if (selectedIds.length === 0) {
                toast.warning('Vui lòng chọn ít nhất một dòng để xóa');
                return;
            }

            if (!confirm(`Bạn có chắc chắn muốn xóa ${selectedIds.length} dòng đã chọn?`)) return;

            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} dòng`);
            updatePagination();
        }
        async function saveSelectedProducts() {
            const selectedIds = getSelectedProductIds();
            if (selectedIds.length === 0) {
                toast.warning('Vui lòng chọn ít nhất một dòng để lưu');
                return;
            }

            try {
                loadingUtils.show('Đang lưu dữ liệu...', true);
                const selectedProducts = selectedIds.map(id => state.products.get(id))
                    .filter(product => product && product.order_kd && product.ten_chi_tiet);

                if (selectedProducts.length === 0) {
                    toast.warning('Không có dữ liệu hợp lệ để lưu');
                    loadingUtils.hide();
                    return;
                }

                // Format và lưu dữ liệu
                const formattedProducts = selectedProducts.map(formatProduct);
                await apiRequest('Don_hang', 'Add', { Rows: formattedProducts });

                loadingUtils.hide();
                toast.success(`Đã lưu ${selectedProducts.length} dòng thành công!`);
            } catch (error) {
                loadingUtils.hide();
                console.error('Lỗi khi lưu:', error);
                toast.error('Có lỗi xảy ra khi lưu dữ liệu');
            }
        }
        function updatePagination() {
            const totalItems = state.products.size;
            state.pagination.totalPages = Math.ceil(totalItems / state.pagination.pageSize);

            // Cập nhật UI phân trang
            document.getElementById('pageInfo').textContent =
                `Trang ${state.pagination.currentPage}/${state.pagination.totalPages}`;

            // Hiển thị dữ liệu theo trang
            renderCurrentPage();
        }

        function renderCurrentPage() {
    const tbody = document.querySelector('#productsTable tbody');
    tbody.innerHTML = ''; // Clear current content
    
    const fragment = document.createDocumentFragment(); // Sử dụng fragment để tối ưu DOM
    const start = (state.pagination.currentPage - 1) * state.pagination.pageSize;
    const end = start + state.pagination.pageSize;
    
    Array.from(state.products.values())
        .slice(start, end)
        .forEach(product => {
            const row = document.createElement('tr');
            row.dataset.productId = product.id;
            row.className = 'hover:bg-gray-50 border-b border-gray-200';
            row.innerHTML = generateRowHTML(product);
            fragment.appendChild(row);
        });
    
    tbody.appendChild(fragment);
    
    // Cập nhật thông tin phân trang
    document.getElementById('pageInfo').textContent = 
        `Trang ${state.pagination.currentPage}/${state.pagination.totalPages} | Tổng số: ${state.products.size}`;
}
function initVirtualScroll() {
    const tableContainer = document.querySelector('.table-container');
    let lastScrollTop = 0;

    tableContainer.addEventListener('scroll', () => {
        const scrollTop = tableContainer.scrollTop;
        const direction = scrollTop > lastScrollTop ? 'down' : 'up';
        lastScrollTop = scrollTop;

        // Load more data when scrolling near bottom
        if (direction === 'down' && 
            scrollTop + tableContainer.clientHeight >= tableContainer.scrollHeight - 200) {
            loadMoreData();
        }
    });
}
function generateRowHTML(product) {
    return `
        <td class="w-10 text-center border-r border-gray-200">
            <input type="checkbox" 
                   class="w-4 h-4"
                   onchange="updateSelectedCount()">
        </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.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="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.sll || ''}"
                   placeholder="SLL"
                   onchange="handleInputChange(event, '${product.id}', 'sll')">
        </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.thoi_han || ''}"
                   placeholder="Thời hạn"
                   onchange="handleInputChange(event, '${product.id}', 'thoi_han')">
        </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.ngay_nhan_phoi || ''}"
                   placeholder="Ngày nhận phôi"
                   onchange="handleInputChange(event, '${product.id}', 'ngay_nhan_phoi')">
        </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.tinh_chat || ''}"
                   placeholder="Tính chất"
                   onchange="handleInputChange(event, '${product.id}', 'tinh_chat')">
        </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.gia_cong_moi || ''}"
                   placeholder="Gia công mới"
                   onchange="handleInputChange(event, '${product.id}', 'gia_cong_moi')">
        </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">
            <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.ngay_giao_phoi_sx_amj || ''}"
                   placeholder="Ngày giao phôi SX AMJ"
                   onchange="handleInputChange(event, '${product.id}', 'ngay_giao_phoi_sx_amj')">
        </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.ngay_bat_dau_gia_cong || ''}"
                   placeholder="Ngày bắt đầu gia công"
                   onchange="handleInputChange(event, '${product.id}', 'ngay_bat_dau_gia_cong')">
        </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.gia_cong_ket_thuc || ''}"
                   placeholder="Gia công kết thúc"
                   onchange="handleInputChange(event, '${product.id}', 'gia_cong_ket_thuc')">
        </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.ngay_giao_phoi_sx_txv || ''}"
                   placeholder="Ngày giao phôi SX TXV"
                   onchange="handleInputChange(event, '${product.id}', 'ngay_giao_phoi_sx_txv')">
        </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.ket_thuc_txv || ''}"
                   placeholder="Kết thúc TXV"
                   onchange="handleInputChange(event, '${product.id}', 'ket_thuc_txv')">
        </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.ngay_ket_thuc_ve_amj || ''}"
                   placeholder="Ngày kết thúc về AMJ"
                   onchange="handleInputChange(event, '${product.id}', 'ngay_ket_thuc_ve_amj')">
        </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.ngay_giao_kho || ''}"
                   placeholder="Ngày giao kho"
                   onchange="handleInputChange(event, '${product.id}', 'ngay_giao_kho')">
        </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.uu_tien || ''}"
                   placeholder="Ưu tiên"
                   onchange="handleInputChange(event, '${product.id}', 'uu_tien')">
        </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.trang_thai || ''}"
                   placeholder="Trạng thái"
                   onchange="handleInputChange(event, '${product.id}', 'trang_thai')">
        </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>
    `;
}
        function changePageSize() {
            state.pagination.pageSize = parseInt(document.getElementById('pageSize').value);
            state.pagination.currentPage = 1;
            updatePagination();
        }

        function previousPage() {
            if (state.pagination.currentPage > 1) {
                state.pagination.currentPage--;
                updatePagination();
            }
        }

        function nextPage() {
            if (state.pagination.currentPage < state.pagination.totalPages) {
                state.pagination.currentPage++;
                updatePagination();
            }
        }
        // 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="w-10 text-center border-r border-gray-200">
            <input type="checkbox" 
                   class="w-4 h-4"
                   onchange="updateSelectedCount()">
        </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.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="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="SLL"
                   onchange="handleInputChange(event, '${productId}', 'sll')">
        </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="Thời hạn"
                   onchange="handleInputChange(event, '${productId}', 'thoi_han')">
        </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="Ngày nhận phôi"
                   onchange="handleInputChange(event, '${productId}', 'ngay_nhan_phoi')">
        </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ính chất"
                   onchange="handleInputChange(event, '${productId}', 'tinh_chat')">
        </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="Gia công mới"
                   onchange="handleInputChange(event, '${productId}', 'gia_cong_moi')">
        </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">
            <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="Ngày giao phôi SX AMJ"
                   onchange="handleInputChange(event, '${productId}', 'ngay_giao_phoi_sx_amj')">
        </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="Ngày bắt đầu gia công"
                   onchange="handleInputChange(event, '${productId}', 'ngay_bat_dau_gia_cong')">
        </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="Gia công kết thúc"
                   onchange="handleInputChange(event, '${productId}', 'gia_cong_ket_thuc')">
        </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="Ngày giao phôi SX TXV"
                   onchange="handleInputChange(event, '${productId}', 'ngay_giao_phoi_sx_txv')">
        </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="Kết thúc TXV"
                   onchange="handleInputChange(event, '${productId}', 'ket_thuc_txv')">
        </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="Ngày kết thúc về AMJ"
                   onchange="handleInputChange(event, '${productId}', 'ngay_ket_thuc_ve_amj')">
        </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="Ngày giao kho"
                   onchange="handleInputChange(event, '${productId}', 'ngay_giao_kho')">
        </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="Ưu tiên"
                   onchange="handleInputChange(event, '${productId}', 'uu_tien')">
        </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="Trạng thái"
                   onchange="handleInputChange(event, '${productId}', 'trang_thai')">
        </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);
        }


        function handleInputChange(event, productId, field) {
            let value = event.target.value.toString();

            // Format ngày tháng đúng chuẩn cho các trường date
            if (field === 'thoi_han' || field === 'ngay_nhan_phoi') {
                if (value) {
                    const date = new Date(value);
                    value = date.toISOString().split('T')[0]; // Format YYYY-MM-DD
                }
            }

            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;
                }
                if (productsArray.length === 0) {
                    toast.warning('Không có dữ liệu để lưu');
                    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?.toString() || '',
                    "ten_chi_tiet": product.ten_chi_tiet?.toString() || '',
                    "so_file": product.so_file?.toString() || '',
                    "sll": product.sll?.toString() || '',
                    "thoi_han": product.thoi_han || '',
                    "ngay_nhan_phoi": product.ngay_nhan_phoi || '',
                    "tinh_chat": product.tinh_chat?.toString() || '',
                    "gia_cong_moi": product.gia_cong_moi?.toString() || '',
                    "noi_gia_cong": product.noi_gia_cong?.toString() || '',
                    "ngay_giao_phoi_sx_amj": product.ngay_giao_phoi_sx_amj?.toString() || '',
                    "ngay_bat_dau_gia_cong": product.ngay_bat_dau_gia_cong?.toString() || '',
                    "gia_cong_ket_thuc": product.gia_cong_ket_thuc?.toString() || '',
                    "ngay_giao_phoi_sx_txv": product.ngay_giao_phoi_sx_txv?.toString() || '',
                    "ket_thuc_txv": product.ket_thuc_txv?.toString() || '',
                    "ngay_ket_thuc_ve_amj": product.ngay_ket_thuc_ve_amj?.toString() || '',
                    "ngay_giao_kho": product.ngay_giao_kho?.toString() || '',
                    "uu_tien": product.uu_tien?.toString() || '',
                    "trang_thai": product.trang_thai?.toString() || ''
                }));

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


        // Thêm hàm formatDate
        function formatDate(value) {
            if (!value) return '';

            // Xử lý nếu là số (Excel serial number)
            if (typeof value === 'number') {
                // Excel bắt đầu đếm từ ngày 1/1/1900
                const date = new Date((value - 25569) * 86400 * 1000);
                const day = date.getDate().toString().padStart(2, '0');
                const month = (date.getMonth() + 1).toString().padStart(2, '0');
                const year = date.getFullYear();
                return `${day}/${month}/${year}`;
            }

            // Xử lý nếu là chuỗi
            if (typeof value === 'string') {
                // Kiểm tra nếu là chuỗi rỗng
                if (!value.trim()) return '';

                // Parse date từ string
                const date = new Date(value);
                if (isNaN(date.getTime())) return value; // Trả về nguyên gốc nếu không parse được

                const day = date.getDate().toString().padStart(2, '0');
                const month = (date.getMonth() + 1).toString().padStart(2, '0');
                const year = date.getFullYear();
                return `${day}/${month}/${year}`;
            }

            return value;
        }

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

        loadingUtils.show(`Đang xử lý ${data.length} dòng dữ liệu...`, true);
        
        // Xử lý theo chunks để tránh treo browser
        const chunkSize = 100; // Số dòng xử lý mỗi lần
        let processed = 0;
        
        const processChunk = async (startIndex) => {
            const chunk = data.slice(startIndex, startIndex + chunkSize);
            
            chunk.forEach(row => {
                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()).toString(),
                        ten_chi_tiet: (row['TÊN CHI TIẾT'] || '').toString(),
                        so_file: (row['SỐ FILE'] || '').toString(),
                        sll: (row['SLL'] || '').toString(),
                        thoi_han: formatDate(row['THỜI HẠN']),
                        ngay_nhan_phoi: formatDate(row['NGÀY NHẬN PHÔI']),
                        tinh_chat: (row['TÍNH CHẤT'] || '').toString(),
                        gia_cong_moi: (row['GIA CÔNG MỚI'] || '').toString(),
                        noi_gia_cong: (row['NƠI GIA CÔNG'] || '').toString(),
                        ngay_giao_phoi_sx_amj: formatDate(row['NGÀY GIAO PHÔI SX AMJ']),
                        ngay_bat_dau_gia_cong: formatDate(row['NGÀY BẮT ĐẦU GIA CÔNG']),
                        gia_cong_ket_thuc: formatDate(row['GIA CÔNG KẾT THÚC']),
                        ngay_giao_phoi_sx_txv: formatDate(row['NGÀY GIAO PHÔI SX TXV']),
                        ket_thuc_txv: formatDate(row['KẾT THÚC TXV']),
                        ngay_ket_thuc_ve_amj: formatDate(row['NGÀY KẾT THÚC VỀ AMJ']),
                        ngay_giao_kho: formatDate(row['NGÀY GIAO KHO']),
                        uu_tien: (row['ƯU TIÊN'] || '').toString(),
                        trang_thai: (row['TRẠNG THÁI'] || '').toString()
                    };
                    state.products.set(productId, product);
                }
            });

            processed += chunk.length;
            const progress = Math.round((processed / data.length) * 100);
            loadingUtils.updateProgress(progress);

            // Nếu còn dữ liệu, tiếp tục xử lý chunk tiếp theo
            if (processed < data.length) {
                await new Promise(resolve => setTimeout(resolve, 0)); // Cho phép UI cập nhật
                await processChunk(processed);
            } else {
                // Hoàn thành, render trang đầu tiên
                state.pagination.currentPage = 1;
                updatePagination();
                toast.success(`Đã import ${processed} dòng dữ liệu`);
            }
        };

        await processChunk(0);
        input.value = '';
        loadingUtils.hide();

    } 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="w-10 text-center border-r border-gray-200">
            <input type="checkbox" 
                   class="w-4 h-4"
                   onchange="updateSelectedCount()">
        </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.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="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.sll || ''}"
                   placeholder="SLL"
                   onchange="handleInputChange(event, '${product.id}', 'sll')">
        </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.thoi_han || ''}"
                   placeholder="Thời hạn"
                   onchange="handleInputChange(event, '${product.id}', 'thoi_han')">
        </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.ngay_nhan_phoi || ''}"
                   placeholder="Ngày nhận phôi"
                   onchange="handleInputChange(event, '${product.id}', 'ngay_nhan_phoi')">
        </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.tinh_chat || ''}"
                   placeholder="Tính chất"
                   onchange="handleInputChange(event, '${product.id}', 'tinh_chat')">
        </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.gia_cong_moi || ''}"
                   placeholder="Gia công mới"
                   onchange="handleInputChange(event, '${product.id}', 'gia_cong_moi')">
        </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">
            <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.ngay_giao_phoi_sx_amj || ''}"
                   placeholder="Ngày giao phôi SX AMJ"
                   onchange="handleInputChange(event, '${product.id}', 'ngay_giao_phoi_sx_amj')">
        </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.ngay_bat_dau_gia_cong || ''}"
                   placeholder="Ngày bắt đầu gia công"
                   onchange="handleInputChange(event, '${product.id}', 'ngay_bat_dau_gia_cong')">
        </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.gia_cong_ket_thuc || ''}"
                   placeholder="Gia công kết thúc"
                   onchange="handleInputChange(event, '${product.id}', 'gia_cong_ket_thuc')">
        </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.ngay_giao_phoi_sx_txv || ''}"
                   placeholder="Ngày giao phôi SX TXV"
                   onchange="handleInputChange(event, '${product.id}', 'ngay_giao_phoi_sx_txv')">
        </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.ket_thuc_txv || ''}"
                   placeholder="Kết thúc TXV"
                   onchange="handleInputChange(event, '${product.id}', 'ket_thuc_txv')">
        </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.ngay_ket_thuc_ve_amj || ''}"
                   placeholder="Ngày kết thúc về AMJ"
                   onchange="handleInputChange(event, '${product.id}', 'ngay_ket_thuc_ve_amj')">
        </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.ngay_giao_kho || ''}"
                   placeholder="Ngày giao kho"
                   onchange="handleInputChange(event, '${product.id}', 'ngay_giao_kho')">
        </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.uu_tien || ''}"
                   placeholder="Ưu tiên"
                   onchange="handleInputChange(event, '${product.id}', 'uu_tien')">
        </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.trang_thai || ''}"
                   placeholder="Trạng thái"
                   onchange="handleInputChange(event, '${product.id}', 'trang_thai')">
        </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
        // Xóa các event listener khi xóa row
        function deleteProduct(productId) {
            const row = document.querySelector(`tr[data-product-id="${productId}"]`);
            if (row) {
                // Remove all event listeners
                const newRow = row.cloneNode(true);
                row.parentNode.replaceChild(newRow, row);
                // Then remove the row
                newRow.remove();
                state.products.delete(productId);
            }
        }



        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>