<!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ý Kho - Modern UI</title>
    <link rel="shortcut icon" href="1.png" type="image/x-icon">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.6.2/axios.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <!-- Thêm vào phần head -->
    <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>
        .animate-spin {
            animation: spin 1s linear infinite;
        }

        .loading-overlay {
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(4px);
        }
    </style>
</head>

<body class="bg-gray-50 min-h-screen">
    <!-- Loading Overlay -->
    <div id="loadingOverlay" class="loading-overlay fixed inset-0 z-50 hidden flex items-center justify-center">
        <div class="bg-white p-5 rounded-lg shadow-xl flex items-center space-x-4">
            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
            <span class="text-gray-700">Đang xử lý...</span>
        </div>
    </div>

    <!-- Main Container -->
    <div class="flex min-h-screen">
        <!-- Sidebar -->
        <div id="sidebar"
            class="w-96 bg-white shadow-lg flex flex-col h-screen sticky top-0 transition-all duration-300 transform">
            <!-- Sidebar Header -->
            <div class="p-4 border-b border-gray-200">
                <h2 class="text-xl font-semibold flex items-center space-x-2">
                    <img src="1.png" width="30" alt="">
                    <span>Danh Mục Hàng Hóa</span>
                </h2>
            </div>

            <!-- Search Box -->
            <div class="p-4 border-b border-gray-200">
                <div class="relative">
                    <input type="text" id="searchProduct"
                        class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        placeholder="Tìm kiếm hàng hóa...">
                    <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                </div>
            </div>

            <!-- Category Tags -->
            <div class="p-4 border-b border-gray-200">
                <div id="categoryTags" class="flex flex-wrap gap-2"></div>
            </div>

            <!-- Product List -->
            <div class="flex-1 overflow-y-auto p-4">
                <div id="productList" class="space-y-3"></div>
            </div>
        </div>

        <!-- Main Content -->
        <div class="flex-1 p-6">
            <!-- Header -->
            <div class="mb-6">
                <h1 class="text-2xl font-bold text-gray-800 flex items-center space-x-3">
                 
                    <span>Phiếu Nhập Xuất Kho</span>
                </h1>
            </div>

            <!-- Form Section -->
            <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
                <form id="warehouseForm" class="space-y-6">
                    <!-- Form Grid -->
                    <div class="grid grid-cols-3 gap-6">
                        <!-- ID Phiếu -->
                        <div class="space-y-2">
                            <label class="text-sm font-medium text-gray-700 block">ID phiếu</label>
                            <input type="text" id="IDPHIEUNXT"
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-50" readonly>
                        </div>

                        <!-- Số Chứng Từ -->
                        <div class="space-y-2">
                            <label class="text-sm font-medium text-gray-700 block">Số Chứng Từ</label>
                            <input type="text" id="soChungTu"
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                required>
                        </div>

                        <!-- Thời Gian -->
                        <div class="space-y-2">
                            <label class="text-sm font-medium text-gray-700 block">Thời Gian</label>
                            <input type="datetime-local" id="thoiGian"
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                required>
                        </div>

                        <!-- Kho Xuất -->
                        <div class="space-y-2">
                            <label class="text-sm font-medium text-gray-700 block">Kho Xuất</label>
                            <select id="khoXuat"
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                required>
                                <option value="">Chọn kho xuất</option>
                            </select>
                        </div>

                        <!-- Kho Nhận -->
                        <div class="space-y-2">
                            <label class="text-sm font-medium text-gray-700 block">Kho Nhận</label>
                            <select id="khoNhan"
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                required>
                                <option value="">Chọn kho nhận</option>
                            </select>
                        </div>

                        <!-- Diễn Giải -->
                        <div class="space-y-2">
                            <label class="text-sm font-medium text-gray-700 block">Diễn Giải</label>
                            <input type="text" id="dienGiai"
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        </div>
                    </div>

                    <!-- Loại Phiếu -->
                    <div class="space-y-2">
                        <label class="text-sm font-medium text-gray-700 block">Loại Phiếu</label>
                        <div id="loaiPhieuTags" class="flex flex-wrap gap-3">
                            <!-- Nhóm Nhập -->
                            <div class="space-x-4">
                                <label
                                    class="inline-flex items-center px-4 py-2 rounded-full border cursor-pointer hover:bg-blue-50 transition-colors">
                                    <input type="radio" name="loaiPhieu" value="Nhập tồn kho" class="hidden peer">
                                    <span class="text-sm peer-checked:text-blue-600 peer-checked:font-medium">
                                        <i class="fas fa-download mr-2"></i>Nhập tồn kho
                                    </span>
                                </label>
                                <label
                                    class="inline-flex items-center px-4 py-2 rounded-full border cursor-pointer hover:bg-blue-50 transition-colors">
                                    <input type="radio" name="loaiPhieu" value="Nhập mua hàng" class="hidden peer">
                                    <span class="text-sm peer-checked:text-blue-600 peer-checked:font-medium">
                                        <i class="fas fa-shopping-cart mr-2"></i>Nhập mua hàng
                                    </span>
                                </label>
                                <label
                                    class="inline-flex items-center px-4 py-2 rounded-full border cursor-pointer hover:bg-blue-50 transition-colors">
                                    <input type="radio" name="loaiPhieu" value="Nhập chuyển kho" class="hidden peer">
                                    <span class="text-sm peer-checked:text-blue-600 peer-checked:font-medium">
                                        <i class="fas fa-exchange-alt mr-2"></i>Nhập chuyển kho
                                    </span>
                                </label>
                                <label
                                    class="inline-flex items-center px-4 py-2 rounded-full border cursor-pointer hover:bg-blue-50 transition-colors">
                                    <input type="radio" name="loaiPhieu" value="Nhập trả hàng" class="hidden peer">
                                    <span class="text-sm peer-checked:text-blue-600 peer-checked:font-medium">
                                        <i class="fa-regular fa-share-from-square"></i> Nhập trả hàng
                                    </span>
                                </label>

                            </div>

                            <!-- Nhóm Xuất -->
                            <div class="space-x-4">
                                <label
                                    class="inline-flex items-center px-4 py-2 rounded-full border cursor-pointer hover:bg-blue-50 transition-colors">
                                    <input type="radio" name="loaiPhieu" value="Xuất bán" class="hidden peer">
                                    <span class="text-sm peer-checked:text-blue-600 peer-checked:font-medium">
                                        <i class="fa-solid fa-cart-shopping"></i> Xuất bán
                                    </span>
                                </label>
                                <label
                                    class="inline-flex items-center px-4 py-2 rounded-full border cursor-pointer hover:bg-blue-50 transition-colors">
                                    <input type="radio" name="loaiPhieu" value="Xuất chuyển kho" class="hidden peer">
                                    <span class="text-sm peer-checked:text-blue-600 peer-checked:font-medium">
                                        <i class="fas fa-exchange-alt mr-2"></i>Xuất chuyển kho
                                    </span>
                                </label>
                            </div>
                        </div>
                        <input type="hidden" id="loaiNhap" name="loaiNhap">
                    </div>

                    <!-- Bottom Form Row -->
                    <div class="grid grid-cols-3 gap-6">
                        <div class="space-y-2">
                            <label class="text-sm font-medium text-gray-700 block">Người Tạo</label>
                            <input type="text" id="nguoiTao"
                                class="w-full px-3 py-2 border bg-gray-50 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                readonly>
                        </div>
                        <div class="space-y-2">
                            <label class="text-sm font-medium text-gray-700 block">Ghi Chú</label>
                            <input type="text" id="ghiChu"
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        </div>
                        <div class="flex items-end space-x-3">
                            <button type="button" onclick="resetForm()"
                                class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors flex items-center">
                                <i class="fas fa-redo mr-2"></i>Reset
                            </button>
                            <button type="button" onclick="submitForm()"
                                class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors flex-1 flex items-center justify-center">
                                <i class="fas fa-save mr-2"></i>Lưu Phiếu
                            </button>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Products Table -->
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-xl font-semibold text-gray-800">Chi Tiết Nhập Xuất Kho</h2>
                    <div class="text-sm text-gray-500">
                        Tổng số mặt hàng: <span id="productCount" class="font-medium">0</span>
                    </div>
                </div>

                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead>
                            <tr>
                                <th hidden>ID NK Chi Tiết</th>
                                <th hidden>ID Nhập Kho</th>
                                <th hidden>Mã Hàng</th>
                                <th
                                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Tên Hàng
                                </th>
                                <th
                                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Số Lượng
                                </th>
                                <th
                                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    ĐVT
                                </th>
                                <th
                                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Quy Đổi
                                </th>
                                <th
                                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider dongianhap">
                                    Đơn Giá Nhập
                                </th>
                                <th
                                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider dongiaxuat">
                                    Đơn Giá Xuất
                                </th>
                                <th
                                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Ghi Chú
                                </th>
                                <th
                                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Thao Tác
                                </th>
                            </tr>
                        </thead>
                        <tbody id="warehouseDetails"
                            class="bg-white divide-y divide-gray-200 text-sm font-medium text-gray-900">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>

        const API_CONFIG = {
            APP_ID: 'e483be4d-1b20-4805-8bcf-c01013ee853b',
            ACCESS_KEY: 'V2-PelHU-a4w3r-2mlpo-wI0XW-nZvbo-Y5sLF-XoEn4-wf3Ym',
            REGION: 'www',
            BASE_URL: 'https://www.appsheet.com/api/v2/apps'
        };
        let state = {
            currentWarehouseId: 'NK' + Date.now(),
            products: [],
            warehouses: [],
            selectedCategories: [],
            loading: false
        };
        // Loading Management
        const showLoading = () => {
            document.getElementById('loadingOverlay').style.display = 'flex';
            state.loading = true;
        };

        const hideLoading = () => {
            document.getElementById('loadingOverlay').style.display = 'none';
            state.loading = false;
        };

        const apiService = {
            createAxiosInstance() {
                return axios.create({
                    baseURL: `${API_CONFIG.BASE_URL}/${API_CONFIG.APP_ID}/tables`,
                    headers: {
                        'ApplicationAccessKey': API_CONFIG.ACCESS_KEY,
                        'Content-Type': 'application/json'
                    }
                });
            },

            async request(tableName, action, data = {}, select = {}) {
                try {
                    showLoading();
                    const api = this.createAxiosInstance();
                    const response = await api.post(`/${tableName}/Action`, {
                        Action: action,
                        Properties: select,
                        ...data
                    });
                    return response.data;
                } catch (error) {
                    console.error('API request failed:', error);
                    throw error;
                } finally {
                    hideLoading();
                }
            }
        };
        const debounce = (func, wait) => {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        };
        // Trong hàm loadWarehouses, bạn đang sử dụng apiRequest không được định nghĩa
        async function loadWarehouses() {
            try {
                // Sửa thành
                const response = await apiService.request('KHO', 'Find', {}, {
                    Selector: `Filter(KHO, true)`
                });
                state.warehouses = response; // Cập nhật vào state
                renderWarehouses();
            } catch (error) {
                console.error('Error loading warehouses:', error);
            }
        }
        function renderWarehouses() {
            const khoXuat = document.getElementById('khoXuat');
            const khoNhan = document.getElementById('khoNhan');

            state.warehouses.forEach(warehouse => {
                const option = document.createElement('option');
                option.value = warehouse['MÃ KHO'];
                option.textContent = warehouse['TÊN KHO'];

                khoXuat.appendChild(option.cloneNode(true));
                khoNhan.appendChild(option);
            });
        }
        async function loadProducts() {
            try {
                const response = await apiService.request('DMHH', 'Find', {}, {
                    Selector: 'Filter(DMHH, true)'
                });
                state.products = response;
                renderProducts(state.products);
                renderCategoryTags(state.products);
            } catch (error) {
                console.error('Error loading products:', error);
            }
        }

        const debounceSearch = debounce((value) => {
            searchProducts(value);
        }, 300);

        function toggleProductSidebar() {
            const sidebar = document.getElementById('productSidebar');
            loadProducts();

        }
        // Hàm render tags từ danh sách sản phẩm
        function renderCategoryTags(products) {
            const categories = [...new Set(products.map(p => p['PHÂN LOẠI']))].filter(Boolean);
            const tagsContainer = document.getElementById('categoryTags');
            tagsContainer.innerHTML = '';

            // Add "All" tag
            const allTag = createCategoryTag('Tất cả', products.length, state.selectedCategories.length === 0);
            allTag.onclick = () => {
                state.selectedCategories = [];
                renderProducts(state.products);
                renderCategoryTags(state.products);
            };
            tagsContainer.appendChild(allTag);

            // Add category tags
            categories.forEach(category => {
                const count = products.filter(p => p['PHÂN LOẠI'] === category).length;
                const tag = createCategoryTag(category, count, state.selectedCategories.includes(category));
                tag.onclick = () => toggleCategory(category);
                tagsContainer.appendChild(tag);
            });
        }

        function createCategoryTag(name, count, isActive) {
            const tag = document.createElement('button');
            tag.className = `px-3 py-1.5 rounded-full text-sm font-medium flex items-center space-x-2 transition-colors
                ${isActive ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-800 hover:bg-gray-200'}`;

            tag.innerHTML = `
                <span>${name}</span>
                <span class="px-2 py-0.5 text-xs rounded-full 
                    ${isActive ? 'bg-blue-400 text-white' : 'bg-gray-200 text-gray-600'}">
                    ${count}
                </span>
            `;
            return tag;
        }

        function toggleCategory(category) {
            if (state.selectedCategories.includes(category)) {  // Sửa chỗ này
                state.selectedCategories = state.selectedCategories.filter(c => c !== category);
            } else {
                state.selectedCategories.push(category);
            }

            const filteredProducts = state.selectedCategories.length === 0  // Sửa chỗ này
                ? state.products  // Sửa chỗ này
                : state.products.filter(p => state.selectedCategories.includes(p['PHÂN LOẠI']));  // Sửa chỗ này

            renderProducts(filteredProducts);
            renderCategoryTags(state.products);  // Sửa chỗ này
        }
        function renderProducts(productsToRender) {
            const productList = document.getElementById('productList');
            productList.innerHTML = '';

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

            productsToRender.forEach(product => {
                const productCard = document.createElement('div');
                productCard.className = 'border rounded-lg p-4 hover:bg-gray-50 cursor-pointer';
                productCard.onclick = () => selectProduct(product['MÃ HÀNG']);

                // Xử lý URL hình ảnh
                const imageUrl = getImageUrl(product['HÌNH ẢNH']);

                productCard.innerHTML = `
            <div class="flex items-center space-x-4">
                <img src="${imageUrl}" 
                     alt="${product['TÊN HÀNG']}" 
                     class="w-16 h-16 object-cover rounded"
                     onerror="this.src='https://i.ibb.co/cYHCSgp/image.png'"
                >
                <div>
                    <h3 class="font-semibold">${product['TÊN HÀNG']}</h3>
                    <p class="text-sm text-gray-600">Mã: ${product['MÃ HÀNG']}</p>
                    <p class="text-sm text-gray-600">ĐVT: ${product['ĐƠN VỊ TÍNH']}</p>
                    <p class="text-sm text-gray-600">Phân loại: ${product['PHÂN LOẠI'] || 'Chưa phân loại'}</p>
                </div>
            </div>
        `;
                productList.appendChild(productCard);
            });
        }
        function getImageUrl(imagePath) {
            // Kiểm tra nếu đường dẫn bắt đầu bằng DMHH_Images/
            if (imagePath && imagePath.startsWith('DMHH_Images/')) {
                const baseUrl = 'https://www.appsheet.com/template/gettablefileurl';
                const appName = encodeURIComponent("WowsKho-852393027"); // Sử dụng APP_ID đã định nghĩa
                const tableName = encodeURIComponent('DMHH');
                const fileName = encodeURIComponent(imagePath);
                return `${baseUrl}?appName=${appName}&tableName=${tableName}&fileName=${fileName}`;
            }
            // Nếu không phải định dạng DMHH_Images, trả về đường dẫn gốc hoặc placeholder
            return imagePath || 'https://i.ibb.co/cYHCSgp/image.png';
        }
        const searchProducts = debounce((value) => {
            if (!value.trim()) {
                renderProducts(state.products);
                return;
            }

            const filtered = state.products.filter(product =>
                product['MÃ HÀNG']?.toLowerCase().includes(value.toLowerCase()) ||
                product['TÊN HÀNG']?.toLowerCase().includes(value.toLowerCase())
            );
            renderProducts(filtered);
        }, 300);

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

            const loaiPhieu = document.getElementById('loaiNhap').value;
            const isNhap = loaiPhieu.toLowerCase().includes('nhập');

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

            if (existingRow) {
                const quantityInput = existingRow.querySelector('[data-quantity]');
                quantityInput.value = parseInt(quantityInput.value) + 1;
                updateRowCalculations(existingRow);
            } else {
                const tr = document.createElement('tr');
                tr.className = 'hover:bg-gray-50 transition-colors';
                const IDPHIEUNXTDe = 'NKDE' + Date.now();

                tr.innerHTML = `
                    <td hidden>${IDPHIEUNXTDe}</td>
                    <td hidden>${state.currentWarehouseId}</td>
                    <td hidden data-ma-hang="${product['MÃ HÀNG']}">${product['MÃ HÀNG']}</td>
                  <td class="px-6 py-4">
    <div class="flex items-center space-x-3">
        <div class="flex-shrink-0 w-12 h-12">
            <img src="${getImageUrl(product['HÌNH ẢNH'])}" 
                 alt="${product['TÊN HÀNG']}" 
                 class="w-12 h-12 object-cover rounded-lg"
                 onerror="this.src='https://i.ibb.co/cYHCSgp/image.png'">
        </div>
        <div>
            <div class="font-medium text-gray-900">${product['TÊN HÀNG']}</div>
            <div class="text-sm text-gray-500">${product['MÃ HÀNG']}</div>
        </div>
    </div>
</td>
                    <td class="px-6 py-4">
                        <input type="number" data-quantity 
                               class="w-20 px-3 py-1 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent" 
                               value="1" min="1" 
                               onchange="updateRowCalculations(this.parentElement.parentElement)">
                    </td>
                    <td class="px-6 py-4">${product['ĐƠN VỊ TÍNH']}</td>
                    <td class="px-6 py-4">
                        <input type="number" data-quy-doi 
                               class="w-20 px-3 py-1 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent" 
                               value="1" min="1"
                               onchange="updateRowCalculations(this.parentElement.parentElement)">
                    </td>
                    <td class="px-6 py-4 dongianhap">
                        <input type="number" data-dongia-nhap 
                               class="w-24 px-3 py-1 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent" 
                               value="${product['ĐƠN GIÁ NHẬP'] || 0}" ${!isNhap ? 'readonly' : ''}>
                    </td>
                    <td class="px-6 py-4 dongiaxuat">
                        <input type="number" data-dongia-xuat 
                               class="w-24 px-3 py-1 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent" 
                               value="${product['ĐƠN GIÁ XUẤT'] || 0}" ${isNhap ? 'readonly' : ''}>
                    </td>
                    <td class="px-6 py-4">
                        <input type="text" 
                               class="w-full px-3 py-1 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent" 
                               placeholder="Ghi chú">
                    </td>
                    <td class="px-6 py-4">
                        <button onclick="this.parentElement.parentElement.remove(); updateProductCount();" 
                                class="text-red-500 hover:text-red-700 p-2 hover:bg-red-50 rounded-full transition-colors">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                `;
                tbody.appendChild(tr);
                updateRowCalculations(tr);
            }
            updateProductCount();
        }
        function updateRowCalculations(row) {
            const quantityInput = row.querySelector('[data-quantity]');
            const quyDoiInput = row.querySelector('[data-quy-doi]');
            const slNhapInput = row.querySelector('[data-sl-nhap]');

            if (quantityInput && quyDoiInput && slNhapInput) {
                const soLuong = parseInt(quantityInput.value) || 0;
                const quyDoi = parseInt(quyDoiInput.value) || 0;
                slNhapInput.value = soLuong * quyDoi;
            }
        }
        function updateProductCount() {
            const count = document.getElementById('warehouseDetails').children.length;
            document.getElementById('productCount').textContent = count;
        }


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

                // Validate form
                const requiredFields = ['soChungTu', 'thoiGian', 'khoXuat', 'khoNhan', 'nguoiTao', 'loaiNhap'];
                const missingFields = requiredFields.filter(field => !document.getElementById(field).value);

                if (missingFields.length > 0) {
                    throw new Error('Vui lòng điền đầy đủ thông tin bắt buộc');
                    showToast('Vui lòng điền đầy đủ thông tin bắt buộc', "error");
                }

                const phieuNhap = {
                    IDPHIEUNXT: document.getElementById('IDPHIEUNXT').value,
                    "LOẠI PHIẾU": document.getElementById('loaiNhap').value,
                    "SỐ CHỨNG TỪ": document.getElementById('soChungTu').value,
                    "THỜI GIAN": document.getElementById('thoiGian').value,
                    "ĐƠN VỊ XUẤT": document.getElementById('khoXuat').value,
                    "ĐƠN VỊ NHẬN": document.getElementById('khoNhan').value,
                    "DIỄN GIẢI": document.getElementById('dienGiai').value,
                    "NGƯỜI TẠO": document.getElementById('nguoiTao').value,
                    "GHI CHÚ": document.getElementById('ghiChu').value,
                    "TRẠNG THÁI": "Phiếu mới"
                };

                const chiTiet = Array.from(document.getElementById('warehouseDetails').getElementsByTagName('tr'))
                    .map(row => ({
                        IDPHIEUNXTDE: row.cells[0].textContent,
                        IDPHIEUNXT: document.getElementById('IDPHIEUNXT').value,
                        "LOẠI PHIẾU": document.getElementById('loaiNhap').value,
                        "SỐ CHỨNG TỪ": document.getElementById('soChungTu').value,
                        "THỜI GIAN": document.getElementById('thoiGian').value,
                        "ĐƠN VỊ XUẤT": document.getElementById('khoXuat').value,
                        "ĐƠN VỊ NHẬN": document.getElementById('khoNhan').value,
                        "MÃ HÀNG": row.cells[2].textContent,
                        "SỐ LƯỢNG": row.querySelector('[data-quantity]').value,
                        "ĐƠN VỊ TÍNH": row.cells[5].textContent,
                        "QUY ĐỔI": row.querySelector('[data-quy-doi]').value,
                        "ĐƠN GIÁ NHẬP": row.querySelector('[data-dongia-nhap]').value || 0,
                        "ĐƠN GIÁ XUẤT": row.querySelector('[data-dongia-xuat]').value || 0,
                        "GHI CHÚ": row.cells[9].querySelector('input').value,
                        "TRẠNG THÁI": "Phiếu mới"
                    }));

                if (chiTiet.length === 0) {
                    throw new Error('Vui lòng thêm ít nhất một sản phẩm');
                }
                console.log(phieuNhap);
                console.log(chiTiet);

                const responsePhieuNhap = await apiService.request('PHIEUNXT', 'Add', { Rows: [phieuNhap] });
                const responseChiTiet = await apiService.request('PHIEUNXTDE', 'Add', { Rows: chiTiet });

                // Hiển thị thông báo thành công
                showToast("Đã lưu phiếu thành công!", "success");
                resetForm();

            } catch (error) {
                // Hiển thị thông báo lỗi
                showToast(error.message || 'Có lỗi xảy ra khi lưu phiếu', "error");
            } finally {
                hideLoading();
            }
        }

        const showToast = (message, type = 'success') => {
            const config = {
                text: message,
                duration: 3000,
                close: true,
                gravity: "top",
                position: "right",
                stopOnFocus: true,
                onClick: function () { }
            };

            if (type === 'success') {
                config.style = {
                    background: "linear-gradient(to right, #00b09b, #96c93d)",
                };
            } else if (type === 'error') {
                config.style = {
                    background: "linear-gradient(to right, #ff5f6d, #ffc371)",
                };
            }

            Toastify(config).showToast();
        };



        // Reset form
        function resetForm() {

            document.getElementById('warehouseForm').reset();
            document.getElementById('warehouseDetails').innerHTML = '';
            updateProductCount();

            // Reset radio buttons
            document.querySelectorAll('[name="loaiPhieu"]').forEach(radio => {
                radio.checked = false;
                const label = radio.parentElement;
                label.classList.remove('bg-blue-50', 'border-blue-300');
            });
            document.getElementById('loaiNhap').value = '';

            // Set current time
            const now = new Date();
            now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
            document.getElementById('thoiGian').value = now.toISOString().slice(0, 16);
            state.currentWarehouseId = 'NK' + Date.now();
            document.getElementById('IDPHIEUNXT').value = state.currentWarehouseId;
            const urlParams = new URLSearchParams(window.location.search);
            manv = urlParams.get('manv');
            document.getElementById('nguoiTao').value = manv;
        }
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('-translate-x-full');
        }


        function updateDonGiaVisibility(isNhap) {
            const dgnCells = document.querySelectorAll('.dongianhap');
            const dgxCells = document.querySelectorAll('.dongiaxuat');

            // Cập nhật hiển thị các cột
            dgnCells.forEach(cell => {
                cell.style.display = isNhap ? '' : 'none';
                const input = cell.querySelector('input');
                if (input) {
                    input.readOnly = !isNhap;
                    if (!isNhap) input.value = '0';
                }
            });

            dgxCells.forEach(cell => {
                cell.style.display = isNhap ? 'none' : '';
                const input = cell.querySelector('input');
                if (input) {
                    input.readOnly = isNhap;
                    if (isNhap) input.value = '0';
                }
            });

            // Cập nhật tiêu đề cột
            const headerNhap = document.querySelector('th.dongianhap');
            const headerXuat = document.querySelector('th.dongiaxuat');
            if (headerNhap) headerNhap.style.display = isNhap ? '' : 'none';
            if (headerXuat) headerXuat.style.display = isNhap ? 'none' : '';
        }
        // Khởi tạo trang
        document.addEventListener('DOMContentLoaded', function () {
            // Khởi tạo thời gian
            const now = new Date();
            now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
            document.getElementById('thoiGian').value = now.toISOString().slice(0, 16);
            document.getElementById('IDPHIEUNXT').value = state.currentWarehouseId;
            const urlParams = new URLSearchParams(window.location.search);
            manv = urlParams.get('manv');
            document.getElementById('nguoiTao').value = manv;
            // Khởi tạo dữ liệu
            loadProducts();
            loadWarehouses();

            // Setup radio buttons
            const loaiPhieuTags = document.querySelectorAll('input[name="loaiPhieu"]');
            const hiddenInput = document.getElementById('loaiNhap');

            loaiPhieuTags.forEach(tag => {
                tag.addEventListener('change', function () {
                    // Reset all labels
                    document.querySelectorAll('[name="loaiPhieu"]').forEach(radio => {
                        const label = radio.parentElement;
                        label.classList.remove('bg-blue-50', 'border-blue-300');
                    });

                    // Style selected label
                    if (this.checked) {
                        const label = this.parentElement;
                        label.classList.add('bg-blue-50', 'border-blue-300');
                        hiddenInput.value = this.value;

                        

                        // Update visibility
                        updateDonGiaVisibility(this.value.toLowerCase().includes('nhập'));
                    }
                });
            });

            // Setup search
            document.getElementById('searchProduct').addEventListener('input', function (e) {
                searchProducts(e.target.value);
            });
        });

    </script>

</body>

</html>