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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Báo Cáo Tồn Kho</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <style>
        .sticky-footer {
            position: sticky;
            bottom: 0;
            z-index: 10;
            background-color: rgb(249 250 251);
            box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>

<body class="bg-gray-100 min-h-screen">
    <!-- Header -->
    <header class="bg-white shadow-sm mb-6">
        <div class="mx-auto px-4 py-4">
            <div class="flex justify-between items-center">
                <h1 class="text-2xl font-bold text-gray-800">Báo Cáo Tồn Kho</h1>
                <div class="flex items-center space-x-4">
                    <button onclick="exportToExcel()"
                        class="inline-flex items-center px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-md transition duration-200">
                        <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        </svg>
                        Xuất Excel
                    </button>
                </div>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <div class="mx-auto px-4">
        <div class="flex flex-col md:flex-row gap-6">
            <!-- Filters -->
            <!-- Filters -->
            <div class="w-full md:w-1/6">
                <div class="bg-white p-6 rounded-lg shadow-md transition-all duration-300 hover:shadow-lg">
                    <h2 class="text-lg font-semibold text-gray-800 mb-6">Bộ lọc</h2>
                    <div class="space-y-6">
                        <!-- Preset Date Ranges -->
                        <div class="filter-group">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Thời gian</label>
                            <div class="flex flex-wrap gap-2">
                                <button
                                    class="px-3 py-1 rounded-full text-sm bg-gray-100 hover:bg-blue-500 hover:text-white transition-colors duration-200 date-tag"
                                    data-range="today">
                                    Hôm nay
                                </button>
                                <button
                                    class="px-3 py-1 rounded-full text-sm bg-gray-100 hover:bg-blue-500 hover:text-white transition-colors duration-200 date-tag"
                                    data-range="yesterday">
                                    Hôm qua
                                </button>
                                <button
                                    class="px-3 py-1 rounded-full text-sm bg-gray-100 hover:bg-blue-500 hover:text-white transition-colors duration-200 date-tag"
                                    data-range="week">
                                    Tuần này
                                </button>
                                <button
                                    class="px-3 py-1 rounded-full text-sm bg-gray-100 hover:bg-blue-500 hover:text-white transition-colors duration-200 date-tag"
                                    data-range="month">
                                    Tháng này
                                </button>
                            </div>
                            <div class="mt-3">
                                <button id="customDateBtn" class="text-sm text-blue-600 hover:text-blue-800">
                                    + Tùy chọn thời gian
                                </button>
                                <div id="customDateInputs" class="mt-2 hidden">
                                    <div class="grid grid-cols-2 gap-2">
                                        <input type="date" id="fromDate"
                                            class="w-full px-2 py-1 border rounded-md text-sm">
                                        <input type="date" id="toDate"
                                            class="w-full px-2 py-1 border rounded-md text-sm">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Search -->
                        <div class="filter-group">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Tìm kiếm</label>
                            <input type="text" id="searchInput" placeholder="Tìm kiếm..."
                                class="w-full px-3 py-2 border rounded-md focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <!-- Product Groups as Tags -->
                        <div class="filter-group">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Nhóm sản phẩm</label>
                            <div id="groupTags" class="flex flex-wrap gap-2">
                                <!-- Groups will be dynamically added here -->
                            </div>
                        </div>

                        <!-- Status -->
                        <div class="filter-group">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Trạng thái</label>
                            <div class="flex gap-2">
                                <button
                                    class="px-3 py-1 rounded-full text-sm bg-gray-100 hover:bg-blue-500 hover:text-white transition-colors duration-200 status-tag active"
                                    data-status="all">
                                    Tất cả
                                </button>
                                <button
                                    class="px-3 py-1 rounded-full text-sm bg-gray-100 hover:bg-blue-500 hover:text-white transition-colors duration-200 status-tag"
                                    data-status="conhang">
                                    Còn hàng
                                </button>
                                <button
                                    class="px-3 py-1 rounded-full text-sm bg-gray-100 hover:bg-blue-500 hover:text-white transition-colors duration-200 status-tag"
                                    data-status="hethang">
                                    Hết hàng
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Table Section -->
            <div class="flex-1">
                <!-- Loading State -->
                <div id="loading"
                    class="fixed inset-0 bg-gray-900 bg-opacity-50 flex items-center justify-center z-50 hidden">
                    <div class="bg-white p-8 rounded-lg shadow-xl flex flex-col items-center">
                        <div class="animate-spin rounded-full h-16 w-16 border-b-4 border-blue-600"></div>
                        <p class="mt-4 text-gray-700">Đang tải dữ liệu...</p>
                    </div>
                </div>
                <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 
                            sm:px-6 mt-4 rounded-lg shadow-md">
                    <div class="flex-1 flex justify-between sm:hidden">
                        <button id="prevPage" class="relative inline-flex items-center px-4 py-2 border border-gray-300 
                                       text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 
                                       transition duration-200">
                            Trước
                        </button>
                        <button id="nextPage" class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 
                                       text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 
                                       transition duration-200">
                            Sau
                        </button>
                    </div>
                    <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                        <div class="flex items-center">
                            <span class="text-sm text-gray-700">Hiển thị</span>
                            <select id="pageSize" class="mx-2 border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 
                                           focus:border-blue-500 text-sm">
                                <option value="10">10</option>
                                <option value="20">20</option>
                                <option value="50">50</option>
                            </select>
                            <span class="text-sm text-gray-700">kết quả mỗi trang</span>
                        </div>
                        <div class="flex items-center space-x-2">
                            <button id="prevPage" class="relative inline-flex items-center px-4 py-2 border border-gray-300 
                                           text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 
                                           transition duration-200">
                                Trước
                            </button>
                            <span id="pageInfo" class="text-sm text-gray-700">
                                Trang <span class="font-medium">1</span> / <span class="font-medium">1</span>
                            </span>
                            <button id="nextPage" class="relative inline-flex items-center px-4 py-2 border border-gray-300 
                                           text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 
                                           transition duration-200">
                                Sau
                            </button>
                        </div>
                    </div>
                </div>
                <br>
                <!-- Table -->
                <div class="bg-white rounded-lg shadow-md overflow-hidden">
                    <div class="overflow-x-auto relative" style="max-height: 75vh;">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th
                                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Hình ảnh
                                    </th>
                                    <th
                                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Tên SP
                                    </th>
                                    <th
                                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Nhập
                                    </th>
                                    <th
                                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Xuất
                                    </th>
                                    <th
                                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Tồn
                                    </th>
                                    <th
                                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Tiền nhập
                                    </th>
                                    <th
                                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Tiền bán
                                    </th>
                                    <th
                                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Lãi
                                    </th>
                                    <th
                                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Trạng thái
                                    </th>
                                </tr>
                            </thead>
                            <tbody id="reportData" class="bg-white divide-y divide-gray-200">
                                <!-- Data will be inserted here -->
                            </tbody>
                            <tfoot id="reportSummary" class="bg-gray-50 sticky bottom-0">
                                <!-- Summary row will be here -->
                            </tfoot>
                        </table>
                    </div>
                </div>

              

            </div>
        </div>
    </div>
      <!-- Key -->
    <script src="key.js"></script>
    <script>
        // API Configuration
        

        // Axios instance
        const axiosInstance = axios.create({
            headers: {
                'ApplicationAccessKey': API_CONFIG.ACCESS_KEY,
                'Content-Type': 'application/json'
            }
        });

        // State management
        let state = {
            products: [],
            sales: [],
            purchases: [],
            reportData: [],
            currentPage: 1,
            pageSize: 10,
            uniqueGroups: new Set()
        };

        // Utility functions
        function formatNumber(num) {
            return Number(num).toLocaleString('vi-VN', {
                minimumFractionDigits: 0,
                maximumFractionDigits: 1
            });
        }
        // Handling date range tags
        const dateButtons = document.querySelectorAll('.date-tag');
        const customDateBtn = document.getElementById('customDateBtn');
        const customDateInputs = document.getElementById('customDateInputs');

        dateButtons.forEach(button => {
            button.addEventListener('click', () => {
                // Remove active class from all buttons
                dateButtons.forEach(btn => btn.classList.remove('bg-blue-500', 'text-white'));
                // Add active class to clicked button
                button.classList.add('bg-blue-500', 'text-white');

                const range = button.dataset.range;
                setDateRange(range);
            });
        });

        customDateBtn.addEventListener('click', () => {
            customDateInputs.classList.toggle('hidden');
        });

        function setDateRange(range) {
            const today = new Date();
            let fromDate, toDate;

            switch (range) {
                case 'today':
                    fromDate = toDate = today;
                    break;
                case 'yesterday':
                    fromDate = toDate = new Date(today.setDate(today.getDate() - 1));
                    break;
                case 'week':
                    fromDate = new Date(today.setDate(today.getDate() - today.getDay()));
                    toDate = new Date(today.setDate(fromDate.getDate() + 6));
                    break;
                case 'month':
                    fromDate = new Date(today.getFullYear(), today.getMonth(), 1);
                    toDate = new Date(today.getFullYear(), today.getMonth() + 1, 0);
                    break;
            }

            document.getElementById('fromDate').value = formatDate(fromDate);
            document.getElementById('toDate').value = formatDate(toDate);
            calculateReport();
            applyFilters();
        }

        function formatDate(date) {
            return date.toISOString().split('T')[0];
        }
        function filterDataByDate(data, fromDate, toDate) {
            return data.filter(item => {
                const itemDate = new Date(item.Thoigian);
                const start = fromDate ? new Date(fromDate) : null;
                const end = toDate ? new Date(toDate) : null;

                if (end) {
                    end.setHours(23, 59, 59, 999);
                }

                if (start && end) {
                    return itemDate >= start && itemDate <= end;
                } else if (start) {
                    return itemDate >= start;
                } else if (end) {
                    return itemDate <= end;
                }
                return true;
            });
        }

        function toggleLoading(show) {
            document.getElementById('loading').style.display = show ? 'flex' : 'none';
        }

        // Core functions
        function calculateReport() {
            const fromDate = document.getElementById('fromDate').value;
            const toDate = document.getElementById('toDate').value;

            const filteredSales = fromDate || toDate ? filterDataByDate(state.sales, fromDate, toDate) : state.sales;
            const filteredPurchases = fromDate || toDate ? filterDataByDate(state.purchases, fromDate, toDate) : state.purchases;

            state.reportData = state.products.map(product => {
                const productSales = filteredSales.filter(sale => sale.Masp === product.Masp);
                const productPurchases = filteredPurchases.filter(purchase => purchase.Masp === product.Masp);

                const totalSales = productSales.reduce((sum, sale) => sum + (parseFloat(sale.Soluong) || 0), 0);
                const totalPurchases = productPurchases.reduce((sum, purchase) => sum + (parseFloat(purchase.Soluong) || 0), 0);

                const tonCuoiKy = totalPurchases - totalSales;
                const tienNhap = totalPurchases * (parseFloat(product.Gianhap) || 0);
                const tienBan = totalSales * (parseFloat(product.Giaban) || 0);
                const lai = tienBan - tienNhap;

                state.uniqueGroups.add(product.Nhomsp);

                return {
                    masp: product.Masp,
                    Hinhanh: product.Hinhanh,
                    tensp: product.Tensp,
                    nhomsp: product.Nhomsp,
                    nhapTrongKy: formatNumber(totalPurchases),
                    xuatTrongKy: formatNumber(totalSales),
                    tonCuoiKy: formatNumber(tonCuoiKy),
                    tienNhap: fomatPrice(tienNhap),
                    tienBan: fomatPrice(tienBan),
                    lai: fomatPrice(lai),
                    trangthai: tonCuoiKy > 0 ? 'conhang' : 'hethang'
                };
            });

            updateGroupFilter();
        }
        fomatPrice = (price) => {
            return price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        }
        // Handling group tags
        function updateGroupFilter() {
            const groupTags = document.getElementById('groupTags');
            groupTags.innerHTML = `
        <button class="px-3 py-1 rounded-full text-sm bg-gray-100 hover:bg-blue-500 hover:text-white transition-colors duration-200 group-tag active" 
                data-group="all">
            Tất cả
        </button>
    `;

            [...state.uniqueGroups].sort().forEach(group => {
                groupTags.innerHTML += `
            <button class="px-3 py-1 rounded-full text-sm bg-gray-100 hover:bg-blue-500 hover:text-white transition-colors duration-200 group-tag" 
                    data-group="${group}">
                ${group}
            </button>
        `;
            });

            // Add click handlers for group tags
            document.querySelectorAll('.group-tag').forEach(tag => {
                tag.addEventListener('click', () => {
                    // If "All" is clicked
                    if (tag.dataset.group === 'all') {
                        document.querySelectorAll('.group-tag').forEach(t => {
                            t.classList.remove('bg-blue-500', 'text-white', 'active');
                        });
                        tag.classList.add('bg-blue-500', 'text-white', 'active');
                    } else {
                        // Remove active state from "All" button
                        const allButton = document.querySelector('.group-tag[data-group="all"]');
                        allButton.classList.remove('bg-blue-500', 'text-white', 'active');

                        // Toggle active state for clicked tag
                        tag.classList.toggle('bg-blue-500');
                        tag.classList.toggle('text-white');
                        tag.classList.toggle('active');
                    }
                    applyFilters();
                });
            });
        }

        function applyFilters() {
            const searchText = document.getElementById('searchInput').value.toLowerCase();
            const activeStatus = document.querySelector('.status-tag.active').dataset.status;
            const activeGroups = Array.from(document.querySelectorAll('.group-tag.active'))
                .map(tag => tag.dataset.group);

            let filteredData = state.reportData;

            if (searchText) {
                filteredData = filteredData.filter(item =>
                    item.masp.toLowerCase().includes(searchText) ||
                    item.tensp.toLowerCase().includes(searchText) ||
                    item.nhomsp.toLowerCase().includes(searchText)
                );
            }

            if (activeStatus !== 'all') {
                filteredData = filteredData.filter(item => item.trangthai === activeStatus);
            }

            // Filter by multiple groups if any are selected
            if (!activeGroups.includes('all') && activeGroups.length > 0) {
                filteredData = filteredData.filter(item => activeGroups.includes(item.nhomsp));
            }

            const startIndex = (state.currentPage - 1) * state.pageSize;
            const endIndex = startIndex + state.pageSize;
            const paginatedData = filteredData.slice(startIndex, endIndex);

            renderReport(paginatedData);
            updatePagination(filteredData.length);
        }

        function renderReport(data) {
            const tbody = document.getElementById('reportData');
            const tfoot = document.getElementById('reportSummary');

            // Render data rows
            tbody.innerHTML = data.map(item => `
        <tr class="hover:bg-gray-50 transition-colors duration-200">
            <td class="px-6 py-4 whitespace-nowrap">
                <img src="${item.Hinhanh || 'path/to/default-image.jpg'}" 
                     alt="${item.tensp}"
                     class="h-12 w-12 object-cover rounded-md">
            </td>
            <td class="px-6 py-4">
                <div class="text-sm text-gray-900 break-words max-w-[200px]">${item.tensp}</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${item.nhapTrongKy}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${item.xuatTrongKy}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${item.tonCuoiKy}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${item.tienNhap}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${item.tienBan}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${item.lai}</td>
            <td class="px-6 py-4 whitespace-nowrap">
                <span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${item.trangthai === 'conhang'
                    ? 'bg-green-100 text-green-800'
                    : 'bg-red-100 text-red-800'
                }">
                    ${item.trangthai === 'conhang' ? 'Còn hàng' : 'Hết hàng'}
                </span>
            </td>
        </tr>
    `).join('');

            // Calculate and render summary
            const summary = calculateSummary(state.reportData); // Sử dụng toàn bộ data để tính tổng
            tfoot.innerHTML = `
        <tr class="font-semibold border-t-2 border-gray-200">
            <td colspan="2" class="px-6 py-4 text-right bg-gray-50">Tổng cộng:</td>
            <td class="px-6 py-4 bg-gray-50">${summary.totalPurchases}</td>
            <td class="px-6 py-4 bg-gray-50">${summary.totalSales}</td>
            <td class="px-6 py-4 bg-gray-50">${summary.totalStock}</td>
            <td class="px-6 py-4 bg-gray-50">${summary.totalPurchaseAmount}</td>
            <td class="px-6 py-4 bg-gray-50">${summary.totalSaleAmount}</td>
            <td class="px-6 py-4 bg-gray-50">${summary.totalProfit}</td>
            <td class="px-6 py-4 bg-gray-50"></td>
        </tr>
    `;
        }



        function calculateSummary(data) {
    const summary = data.reduce((acc, item) => {
        // Chuyển đổi chuỗi thành số bằng cách loại bỏ dấu phẩy và dấu chấm
        const purchases = parseFloat(item.nhapTrongKy.replace(/[,.]/g, ''));
        const sales = parseFloat(item.xuatTrongKy.replace(/[,.]/g, ''));
        const stock = parseFloat(item.tonCuoiKy.replace(/[,.]/g, ''));
        const purchaseAmount = parseFloat(item.tienNhap.replace(/[,.]/g, ''));
        const saleAmount = parseFloat(item.tienBan.replace(/[,.]/g, ''));
        const profit = parseFloat(item.lai.replace(/[,.]/g, ''));

        return {
            totalPurchases: (acc.totalPurchases || 0) + purchases,
            totalSales: (acc.totalSales || 0) + sales,
            totalStock: (acc.totalStock || 0) + stock,
            totalPurchaseAmount: (acc.totalPurchaseAmount || 0) + purchaseAmount,
            totalSaleAmount: (acc.totalSaleAmount || 0) + saleAmount,
            totalProfit: (acc.totalProfit || 0) + profit
        };
    }, {});

    // Định dạng số với dấu phẩy ngăn cách hàng nghìn
    return {
        totalPurchases: formatNumber(summary.totalPurchases),
        totalSales: formatNumber(summary.totalSales),
        totalStock: formatNumber(summary.totalStock),
        totalPurchaseAmount: fomatPrice(summary.totalPurchaseAmount),
        totalSaleAmount: fomatPrice(summary.totalSaleAmount),
        totalProfit: fomatPrice(summary.totalProfit)
    };
}

        function updatePagination(totalItems) {
            const totalPages = Math.ceil(totalItems / state.pageSize);
            const prevButton = document.querySelectorAll('#prevPage');
            const nextButton = document.querySelectorAll('#nextPage');

            prevButton.forEach(btn => {
                btn.disabled = state.currentPage === 1;
                btn.classList.toggle('opacity-50', state.currentPage === 1);
            });

            nextButton.forEach(btn => {
                btn.disabled = state.currentPage === totalPages;
                btn.classList.toggle('opacity-50', state.currentPage === totalPages);
            });

            document.querySelectorAll('#pageInfo').forEach(info => {
                info.innerHTML = `
            Trang <span class="font-medium">${state.currentPage}</span> / 
            <span class="font-medium">${totalPages}</span>
        `;
            });
        }

        async function fetchTableData(tableName, filter) {
            try {
                const response = await axiosInstance.post(
                    `${API_CONFIG.BASE_URL}/${API_CONFIG.APP_ID}/tables/${tableName}/Action`,
                    {
                        Action: "Find",
                        Properties: {
                            Locale: "vi-VN",
                            Timezone: "Asia/Ho_Chi_Minh",
                            Selector: filter
                        },
                        Rows: []
                    }
                );
                return response.data;
            } catch (error) {
                console.error(`Error fetching ${tableName}:`, error);
                throw error;
            }
        }

        async function fetchAllData() {
            toggleLoading(true);
            try {
                const [products, sales, purchases] = await Promise.all([
                    fetchTableData('DMHH', 'Filter(DMHH, true)'),
                    fetchTableData('BANHANGDE', 'Filter(BANHANGDE, true)'),
                    fetchTableData('NHAPHANGDE', 'Filter(NHAPHANGDE, true)')
                ]);

                state = {
                    ...state,
                    products,
                    sales,
                    purchases,
                    uniqueGroups: new Set(products.map(p => p.Nhomsp))
                };

                calculateReport();
                applyFilters();
            } catch (error) {
                console.error('Error fetching data:', error);
                alert('Có lỗi xảy ra khi tải dữ liệu. Vui lòng thử lại sau.');
            } finally {
                toggleLoading(false);
            }
        }
        function exportToExcel() {
            // Tạo bảng mới chỉ với dữ liệu cần xuất
            const exportTable = document.createElement('table');
            const thead = document.createElement('thead');
            thead.innerHTML = `
        <tr>
            <th>Tên SP</th>
            <th>Nhập</th>
            <th>Xuất</th>
            <th>Tồn</th>
            <th>Tiền nhập</th>
            <th>Tiền bán</th>
            <th>Lãi</th>
            <th>Trạng thái</th>
        </tr>
    `;
            exportTable.appendChild(thead);

            const tbody = document.createElement('tbody');
            state.reportData.forEach(item => {
                const row = document.createElement('tr');
                row.innerHTML = `
            <td>${item.tensp}</td>
            <td>${item.nhapTrongKy}</td>
            <td>${item.xuatTrongKy}</td>
            <td>${item.tonCuoiKy}</td>
            <td>${item.tienNhap}</td>
            <td>${item.tienBan}</td>
            <td>${item.lai}</td>
            <td>${item.trangthai === 'conhang' ? 'Còn hàng' : 'Hết hàng'}</td>
        `;
                tbody.appendChild(row);
            });
            exportTable.appendChild(tbody);

            const wb = XLSX.utils.book_new();
            const ws = XLSX.utils.table_to_sheet(exportTable);

            const colWidths = [
                { wch: 30 },  // Tên SP
                { wch: 12 },  // Nhập
                { wch: 12 },  // Xuất
                { wch: 12 },  // Tồn
                { wch: 15 },  // Tiền nhập
                { wch: 15 },  // Tiền bán
                { wch: 15 },  // Lãi
                { wch: 12 }   // Trạng thái
            ];
            ws['!cols'] = colWidths;

            // Sửa đúng tên hàm ở đây
            XLSX.utils.book_append_sheet(wb, ws, "Báo cáo tồn kho");
            XLSX.writeFile(wb, `bao-cao-ton-kho-${new Date().toISOString().split('T')[0]}.xlsx`);
        }
        // Event Listeners
        function initializeEventListeners() {
            document.getElementById('searchInput').addEventListener('input', applyFilters);

            // Status tag listeners
            document.querySelectorAll('.status-tag').forEach(tag => {
                tag.addEventListener('click', () => {
                    document.querySelectorAll('.status-tag').forEach(t =>
                        t.classList.remove('bg-blue-500', 'text-white', 'active'));
                    tag.classList.add('bg-blue-500', 'text-white', 'active');
                    applyFilters();
                });
            });

            document.getElementById('fromDate').addEventListener('change', () => {
                calculateReport();
                applyFilters();
            });
            document.getElementById('toDate').addEventListener('change', () => {
                calculateReport();
                applyFilters();
            });
            document.getElementById('pageSize').addEventListener('change', (e) => {
                state.pageSize = parseInt(e.target.value);
                state.currentPage = 1;
                applyFilters();
            });

            // Handle pagination
            document.querySelectorAll('#prevPage').forEach(btn => {
                btn.addEventListener('click', () => {
                    if (state.currentPage > 1) {
                        state.currentPage--;
                        applyFilters();
                    }
                });
            });

            document.querySelectorAll('#nextPage').forEach(btn => {
                btn.addEventListener('click', () => {
                    state.currentPage++;
                    applyFilters();
                });
            });
        }
        // Initialize
        window.onload = async () => {
            await fetchAllData();
            initializeEventListeners();
        };
    </script>
</body>

</html>