<!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>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.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);
        }

        .sticky-header {
            position: sticky;
            top: 0;
            z-index: 10;
            background-color: rgb(249 250 251);
            /* bg-gray-50 */
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .table-container {
            max-height: 82vh;
            overflow-y: auto;
            position: relative;
        }

        /* Đảm bảo các cột có chiều rộng cố định */
        .fixed-width-cols th {
            white-space: nowrap;
            padding: 0.75rem 1rem;
        }
    </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">
                <!-- Logo và tên cửa hàng bên trái -->
                <div class="flex items-center gap-4">
                    <img src="1.png" width="50" alt="Logo">
                    <div class="flex flex-col">
                        <h1 class="text-2xl font-bold text-gray-800">NHATGIANG STORE</h1>
                        <p class="text-gray-600">
                            SN 729 Bà Triệu, P. Trường Thi, TPTH - ĐT: 091905061
                        </p>
                    </div>
                </div>

                <!-- Tiêu đề báo cáo ở giữa -->
                <div class="absolute left-1/2 transform -translate-x-1/2">
                    <h3 class="text-xl font-bold uppercase">BÁO CÁO HÀNG TỒN</h3>
                </div>

                <!-- Phần trống bên phải để cân bằng layout -->
                <div class="invisible">
                    <img src="1.png" width="50" alt="">
                </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>
                        <div class="space-y-3 pt-4 border-t">
                            <button onclick="exportToExcel()" class="w-full inline-flex items-center justify-center px-4 py-2.5 bg-green-600 hover:bg-green-700 text-white rounded-lg transition duration-200 shadow-sm">
                                <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 toàn bộ
                            </button>
            
                            <button onclick="exportToExcelTH_LAILO_WEB()" class="w-full inline-flex items-center justify-center px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition duration-200 shadow-sm">
                                <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="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 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>
                                BC Cân đối bán hàng
                            </button>
            
                            <button onclick="exportToExcelDetail()" class="w-full inline-flex items-center justify-center px-4 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg transition duration-200 shadow-sm">
                                <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="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 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>
                                BC chi tiết bán hàng
                            </button>
            
                            <button onclick="exportToExcelSummary()" class="w-full inline-flex items-center justify-center px-4 py-2.5 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition duration-200 shadow-sm">
                                <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="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 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>
                                BC tổng hợp bán hàng
                            </button>
                        </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>


                <!-- Table -->
                <div class="bg-white rounded-lg shadow-md overflow-hidden">
                    <div class="table-container">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="sticky-header fixed-width-cols">
                                <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">
                                        Đvtính
                                    </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>
                                </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: [],

            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':
                    // Sửa phần này
                    fromDate = new Date(today.getFullYear(), today.getMonth(), 1);
                    toDate = new Date(today.getFullYear(), today.getMonth() + 1, 0);

                    // Đảm bảo ngày bắt đầu và kết thúc được format đúng theo giờ địa phương
                    fromDate.setHours(0, 0, 0, 0);
                    toDate.setHours(23, 59, 59, 999);
                    break;
            }

            // Format ngày theo định dạng YYYY-MM-DD
            document.getElementById('fromDate').value = formatDate(fromDate);
            document.getElementById('toDate').value = formatDate(toDate);
            calculateReport();
            applyFilters();
        }

        // Hàm format ngày
        function formatDate(date) {
            const d = new Date(date);
            const year = d.getFullYear();
            const month = String(d.getMonth() + 1).padStart(2, '0');
            const day = String(d.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        }
        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,
                    dvtinh: product.Dvtinh, // Thêm đơn vị tính
                    nhomsp: product.Nhomsp,
                    nhapTrongKy: formatNumber(totalPurchases),
                    xuatTrongKy: formatNumber(totalSales),
                    tonCuoiKy: formatNumber(tonCuoiKy),
                    tienNhap: fomatPrice(tienNhap),
                    tienBan: fomatPrice(tienBan),
                    lai: fomatPrice(lai)
                };
            });

            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 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 (!activeGroups.includes('all') && activeGroups.length > 0) {
                filteredData = filteredData.filter(item => activeGroups.includes(item.nhomsp));
            }

            // Hiển thị tất cả dữ liệu
            renderReport(filteredData);
        }

        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.dvtinh}</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>
    </tr>
`).join('');

            // Calculate and render summary
            const summary = calculateSummary(data);
            tfoot.innerHTML = `
    <tr class="font-semibold border-t-2 border-gray-200">
        <td colspan="3" 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>
    </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)
            };
        }



        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 exportToExcelTH_LAILO_WEB() {
            const searchText = document.getElementById('searchInput').value.toLowerCase();
            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 (!activeGroups.includes('all') && activeGroups.length > 0) {
                filteredData = filteredData.filter(item => activeGroups.includes(item.nhomsp));
            }

            const headerRows = [
                ['NHATGIANG STORE'],
                ['SN 729 Bà Triệu, P. Trường Thi, TPTH - ĐT: 091905061'],
                ['BÁO CÁO CÂN ĐỐI HÀNG BÁN'],
                ['']
            ];

            const fromDate = document.getElementById('fromDate').value;
            const toDate = document.getElementById('toDate').value;
            if (fromDate && toDate) {
                headerRows.push([`Từ ngày: ${fromDate} đến ngày: ${toDate}`]);
                headerRows.push(['']);
            }

            const exportTable = document.createElement('table');
            const thead = document.createElement('thead');

            headerRows.forEach(row => {
                const headerRow = document.createElement('tr');
                const cell = document.createElement('td');
                cell.colSpan = 8; // Sửa thành 8 cột theo header
                cell.textContent = row[0];
                headerRow.appendChild(cell);
                thead.appendChild(headerRow);
            });

            const columnHeaders = document.createElement('tr');
            columnHeaders.innerHTML = `
        <th>STT</th>
        <th>Tên SP</th>
        <th>Số lượng</th>
        <th>Giá bán</th>
        <th>Doanh số</th>
        <th>Giá nhập</th>
        <th>Giá vốn</th>
        <th>Lãi lỗ</th>
    `;
            thead.appendChild(columnHeaders);
            exportTable.appendChild(thead);

            const tbody = document.createElement('tbody');
            let totalSoLuong = 0;
            let totalDoanhSo = 0;
            let totalGiaVon = 0;
            let totalLaiLo = 0;

            filteredData.forEach((item, index) => {
                const soLuong = parseFloat(item.xuatTrongKy.replace(/,/g, '')) || 0;
                const giaBan = parseFloat(item.tienBan.replace(/,/g, '')) || 0;
                const giaNhap = parseFloat(item.tienNhap.replace(/,/g, '')) || 0;
                const doanhSo = soLuong * giaBan;
                const giaVon = soLuong * giaNhap;
                const laiLo = doanhSo - giaVon;

                // Cộng dồn vào tổng
                totalSoLuong += soLuong;
                totalDoanhSo += doanhSo;
                totalGiaVon += giaVon;
                totalLaiLo += laiLo;

                const row = document.createElement('tr');
                row.innerHTML = `
            <td>${index + 1}</td>
            <td>${item.tensp}</td>
            <td>${(soLuong)}</td>
            <td>${(giaBan)}</td>
            <td>${(doanhSo)}</td>
            <td>${(giaNhap)}</td>
            <td>${(giaVon)}</td>
            <td>${(laiLo)}</td>
        `;
                tbody.appendChild(row);
            });
            exportTable.appendChild(tbody);

            // Thêm dòng tổng cộng
            const tfoot = document.createElement('tfoot');
            tfoot.innerHTML = `
        <tr>
            <td colspan="2" style="font-weight: bold">Tổng cộng:</td>
            <td>${(totalSoLuong)}</td>
            <td></td>
            <td>${(totalDoanhSo)}</td>
            <td></td>
            <td>${(totalGiaVon)}</td>
            <td>${(totalLaiLo)}</td>
        </tr>
    `;
            exportTable.appendChild(tfoot);

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

            // Các style cho bảng
            const headerStyle = {
                font: { bold: true, sz: 14 },
                alignment: { horizontal: 'center', vertical: 'center' }
            };

            const titleStyle = {
                font: { bold: true, sz: 16 },
                alignment: { horizontal: 'center', vertical: 'center' }
            };

            const allCellStyle = {
                border: {
                    top: { style: 'thin', color: { rgb: "000000" } },
                    bottom: { style: 'thin', color: { rgb: "000000" } },
                    left: { style: 'thin', color: { rgb: "000000" } },
                    right: { style: 'thin', color: { rgb: "000000" } }
                }
            };

            const summaryStyle = {
                font: { bold: true },
                border: {
                    top: { style: 'thin', color: { rgb: "000000" } },
                    bottom: { style: 'thin', color: { rgb: "000000" } },
                    left: { style: 'thin', color: { rgb: "000000" } },
                    right: { style: 'thin', color: { rgb: "000000" } }
                }
            };

            // Áp dụng style
            ['A1', 'A2'].forEach(cell => {
                if (!ws[cell]) ws[cell] = {};
                ws[cell].s = headerStyle;
            });

            if (!ws['A3']) ws['A3'] = {};
            ws['A3'].s = titleStyle;

            if (fromDate && toDate) {
                if (!ws['A5']) ws['A5'] = {};
                ws['A5'].s = headerStyle;
            }

            // Áp dụng border cho tất cả các ô
            const range = XLSX.utils.decode_range(ws['!ref']);
            const headerRowIndex = fromDate && toDate ? 6 : 4;

            for (let R = headerRowIndex; R <= range.e.r; R++) {
                for (let C = 0; C <= range.e.c; C++) {
                    const cellRef = XLSX.utils.encode_cell({ r: R, c: C });
                    if (!ws[cellRef]) ws[cellRef] = {};

                    if (R === range.e.r) {
                        ws[cellRef].s = summaryStyle;
                    } else {
                        ws[cellRef].s = allCellStyle;
                    }
                }
            }

            // Thiết lập độ rộng cột
            const colWidths = [
                { wch: 6 },   // STT
                { wch: 30 },  // Tên SP
                { wch: 12 },  // Số lượng
                { wch: 15 },  // Giá bán
                { wch: 15 },  // Doanh số
                { wch: 15 },  // Giá nhập
                { wch: 15 },  // Giá vốn
                { wch: 15 }   // Lãi lỗ
            ];
            ws['!cols'] = colWidths;

            // Merge cells cho header
            const merges = [];
            for (let i = 0; i < headerRows.length; i++) {
                merges.push({
                    s: { r: i, c: 0 },
                    e: { r: i, c: 7 }  // Sửa thành 7 vì có 8 cột
                });
            }
            ws['!merges'] = merges;

            XLSX.utils.book_append_sheet(wb, ws, "Báo cáo lãi lỗ");
            XLSX.writeFile(wb, `bao-cao-lai-lo-${new Date().toISOString().split('T')[0]}.xlsx`);
        }
        function exportToExcelDetail() {
            const searchText = document.getElementById('searchInput').value.toLowerCase();
            const activeGroups = Array.from(document.querySelectorAll('.group-tag.active'))
                .map(tag => tag.dataset.group);

            let filteredData = state.sales; // Lấy trực tiếp từ state.sales thay vì reportData

            if (searchText) {
                filteredData = filteredData.filter(item =>
                    item.Masp.toLowerCase().includes(searchText) ||
                    item.Tensp.toLowerCase().includes(searchText)
                );
            }

            const headerRows = [
                ['NHATGIANG STORE'],
                ['SN 729 Bà Triệu, P. Trường Thi, TPTH - ĐT: 091905061'],
                ['BÁO CÁO CHI TIẾT HÀNG BÁN'],
                ['']
            ];

            const fromDate = document.getElementById('fromDate').value;
            const toDate = document.getElementById('toDate').value;
            if (fromDate && toDate) {
                headerRows.push([`Từ ngày: ${fromDate} đến ngày: ${toDate}`]);
                headerRows.push(['']);
            }

            const exportTable = document.createElement('table');
            const thead = document.createElement('thead');

            headerRows.forEach(row => {
                const headerRow = document.createElement('tr');
                const cell = document.createElement('td');
                cell.colSpan = 6; // 6 cột
                cell.textContent = row[0];
                headerRow.appendChild(cell);
                thead.appendChild(headerRow);
            });

            const columnHeaders = document.createElement('tr');
            columnHeaders.innerHTML = `
        <th>STT</th>
        <th>Ngày</th>
        <th>Tên hàng hoá</th>
        <th>Số lượng</th>
        <th>Đơn giá</th>
        <th>Thành tiền</th>
    `;
            thead.appendChild(columnHeaders);
            exportTable.appendChild(thead);

            const tbody = document.createElement('tbody');
            let totalSoLuong = 0;
            let totalThanhTien = 0;

            // Lọc dữ liệu theo ngày nếu có
            if (fromDate && toDate) {
                const fromDateTime = new Date(fromDate);
                const toDateTime = new Date(toDate);
                toDateTime.setHours(23, 59, 59, 999);

                filteredData = filteredData.filter(item => {
                    const itemDate = new Date(item.Thoigian);
                    return itemDate >= fromDateTime && itemDate <= toDateTime;
                });
            }

            filteredData.forEach((item, index) => {
                const soLuong = parseFloat(item.Soluong) || 0;
                const donGia = parseFloat(item.Giaban) || 0;
                const thanhTien = soLuong * donGia;

                totalSoLuong += soLuong;
                totalThanhTien += thanhTien;

                const row = document.createElement('tr');
                row.innerHTML = `
            <td>${index + 1}</td>
            <td>${new Date(item.Thoigian).toLocaleDateString('vi-VN')}</td>
            <td>${item.Tensp}</td>
            <td>${(soLuong)}</td>
            <td>${(donGia)}</td>
            <td>${(thanhTien)}</td>
        `;
                tbody.appendChild(row);
            });
            exportTable.appendChild(tbody);

            const tfoot = document.createElement('tfoot');
            tfoot.innerHTML = `
        <tr>
            <td colspan="3" style="font-weight: bold">Tổng cộng:</td>
            <td>${(totalSoLuong)}</td>
            <td></td>
            <td>${(totalThanhTien)}</td>
        </tr>
    `;
            exportTable.appendChild(tfoot);

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

            // Định dạng style
            const headerStyle = {
                font: { bold: true, sz: 14 },
                alignment: { horizontal: 'center', vertical: 'center' }
            };

            const titleStyle = {
                font: { bold: true, sz: 16 },
                alignment: { horizontal: 'center', vertical: 'center' }
            };

            const allCellStyle = {
                border: {
                    top: { style: 'thin', color: { rgb: "000000" } },
                    bottom: { style: 'thin', color: { rgb: "000000" } },
                    left: { style: 'thin', color: { rgb: "000000" } },
                    right: { style: 'thin', color: { rgb: "000000" } }
                }
            };

            const summaryStyle = {
                font: { bold: true },
                border: {
                    top: { style: 'thin', color: { rgb: "000000" } },
                    bottom: { style: 'thin', color: { rgb: "000000" } },
                    left: { style: 'thin', color: { rgb: "000000" } },
                    right: { style: 'thin', color: { rgb: "000000" } }
                }
            };

            // Áp dụng style
            ['A1', 'A2'].forEach(cell => {
                if (!ws[cell]) ws[cell] = {};
                ws[cell].s = headerStyle;
            });

            if (!ws['A3']) ws['A3'] = {};
            ws['A3'].s = titleStyle;

            if (fromDate && toDate) {
                if (!ws['A5']) ws['A5'] = {};
                ws['A5'].s = headerStyle;
            }

            const range = XLSX.utils.decode_range(ws['!ref']);
            const headerRowIndex = fromDate && toDate ? 6 : 4;

            for (let R = headerRowIndex; R <= range.e.r; R++) {
                for (let C = 0; C <= range.e.c; C++) {
                    const cellRef = XLSX.utils.encode_cell({ r: R, c: C });
                    if (!ws[cellRef]) ws[cellRef] = {};

                    if (R === range.e.r) {
                        ws[cellRef].s = summaryStyle;
                    } else {
                        ws[cellRef].s = allCellStyle;
                    }
                }
            }

            // Thiết lập độ rộng cột
            const colWidths = [
                { wch: 6 },   // STT
                { wch: 12 },  // Ngày
                { wch: 40 },  // Tên hàng hoá
                { wch: 12 },  // Số lượng
                { wch: 15 },  // Đơn giá
                { wch: 15 }   // Thành tiền
            ];
            ws['!cols'] = colWidths;

            // Merge cells cho header
            const merges = [];
            for (let i = 0; i < headerRows.length; i++) {
                merges.push({
                    s: { r: i, c: 0 },
                    e: { r: i, c: 5 }  // 6 cột
                });
            }
            ws['!merges'] = merges;

            XLSX.utils.book_append_sheet(wb, ws, "Báo cáo chi tiết");
            XLSX.writeFile(wb, `bao-cao-chi-tiet-${new Date().toISOString().split('T')[0]}.xlsx`);
        }
        // Hàm hỗ trợ format số
        function formatNumber(num) {
            return Number(num).toLocaleString('vi-VN', {
                minimumFractionDigits: 0,
                maximumFractionDigits: 0
            });
        }
        function exportToExcelSummary() {
            const searchText = document.getElementById('searchInput').value.toLowerCase();
            const activeGroups = Array.from(document.querySelectorAll('.group-tag.active'))
                .map(tag => tag.dataset.group);

            let filteredData = state.sales;

            // Lọc theo thời gian nếu có
            const fromDate = document.getElementById('fromDate').value;
            const toDate = document.getElementById('toDate').value;
            if (fromDate && toDate) {
                const fromDateTime = new Date(fromDate);
                const toDateTime = new Date(toDate);
                toDateTime.setHours(23, 59, 59, 999);

                filteredData = filteredData.filter(item => {
                    const itemDate = new Date(item.Thoigian);
                    return itemDate >= fromDateTime && itemDate <= toDateTime;
                });
            }

            // Group dữ liệu theo sản phẩm
            const groupedData = filteredData.reduce((acc, item) => {
                const key = item.Masp;
                if (!acc[key]) {
                    acc[key] = {
                        masp: item.Masp,
                        tensp: item.Tensp,
                        soLuong: 0,
                        donGia: parseFloat(item.Giaban) || 0,
                        thanhTien: 0
                    };
                }
                acc[key].soLuong += parseFloat(item.Soluong) || 0;
                acc[key].thanhTien += (parseFloat(item.Soluong) || 0) * (parseFloat(item.Giaban) || 0);
                return acc;
            }, {});

            // Chuyển đổi thành mảng và sắp xếp
            const summaryData = Object.values(groupedData);

            const headerRows = [
                ['NHATGIANG STORE'],
                ['SN 729 Bà Triệu, P. Trường Thi, TPTH - ĐT: 091905061'],
                ['BÁO CÁO TỔNG HỢP HÀNG BÁN'],
                ['']
            ];

            if (fromDate && toDate) {
                headerRows.push([`Từ ngày: ${fromDate} đến ngày: ${toDate}`]);
                headerRows.push(['']);
            }

            const exportTable = document.createElement('table');
            const thead = document.createElement('thead');

            headerRows.forEach(row => {
                const headerRow = document.createElement('tr');
                const cell = document.createElement('td');
                cell.colSpan = 6;
                cell.textContent = row[0];
                headerRow.appendChild(cell);
                thead.appendChild(headerRow);
            });

            const columnHeaders = document.createElement('tr');
            columnHeaders.innerHTML = `
        <th>STT</th>
        <th>Từ ngày - Đến ngày</th>
        <th>Tên hàng hoá</th>
        <th>Số lượng</th>
        <th>Đơn giá</th>
        <th>Thành tiền</th>
    `;
            thead.appendChild(columnHeaders);
            exportTable.appendChild(thead);

            const tbody = document.createElement('tbody');
            let totalSoLuong = 0;
            let totalThanhTien = 0;

            summaryData.forEach((item, index) => {
                totalSoLuong += item.soLuong;
                totalThanhTien += item.thanhTien;

                const row = document.createElement('tr');
                row.innerHTML = `
            <td>${index + 1}</td>
            <td>${fromDate} - ${toDate}</td>
            <td>${item.tensp}</td>
            <td>${(item.soLuong)}</td>
            <td>${(item.donGia)}</td>
            <td>${(item.thanhTien)}</td>
        `;
                tbody.appendChild(row);
            });
            exportTable.appendChild(tbody);

            const tfoot = document.createElement('tfoot');
            tfoot.innerHTML = `
        <tr>
            <td colspan="3" style="font-weight: bold">Tổng cộng:</td>
            <td>${(totalSoLuong)}</td>
            <td></td>
            <td>${(totalThanhTien)}</td>
        </tr>
    `;
            exportTable.appendChild(tfoot);

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

            // Định dạng style
            const headerStyle = {
                font: { bold: true, sz: 14 },
                alignment: { horizontal: 'center', vertical: 'center' }
            };

            const titleStyle = {
                font: { bold: true, sz: 16 },
                alignment: { horizontal: 'center', vertical: 'center' }
            };

            const allCellStyle = {
                border: {
                    top: { style: 'thin', color: { rgb: "000000" } },
                    bottom: { style: 'thin', color: { rgb: "000000" } },
                    left: { style: 'thin', color: { rgb: "000000" } },
                    right: { style: 'thin', color: { rgb: "000000" } }
                }
            };

            const summaryStyle = {
                font: { bold: true },
                border: {
                    top: { style: 'thin', color: { rgb: "000000" } },
                    bottom: { style: 'thin', color: { rgb: "000000" } },
                    left: { style: 'thin', color: { rgb: "000000" } },
                    right: { style: 'thin', color: { rgb: "000000" } }
                }
            };

            // Áp dụng style
            ['A1', 'A2'].forEach(cell => {
                if (!ws[cell]) ws[cell] = {};
                ws[cell].s = headerStyle;
            });

            if (!ws['A3']) ws['A3'] = {};
            ws['A3'].s = titleStyle;

            if (fromDate && toDate) {
                if (!ws['A5']) ws['A5'] = {};
                ws['A5'].s = headerStyle;
            }

            const range = XLSX.utils.decode_range(ws['!ref']);
            const headerRowIndex = fromDate && toDate ? 6 : 4;

            for (let R = headerRowIndex; R <= range.e.r; R++) {
                for (let C = 0; C <= range.e.c; C++) {
                    const cellRef = XLSX.utils.encode_cell({ r: R, c: C });
                    if (!ws[cellRef]) ws[cellRef] = {};

                    if (R === range.e.r) {
                        ws[cellRef].s = summaryStyle;
                    } else {
                        ws[cellRef].s = allCellStyle;
                    }
                }
            }

            // Thiết lập độ rộng cột
            const colWidths = [
                { wch: 6 },   // STT
                { wch: 20 },  // Ngày
                { wch: 40 },  // Tên hàng hoá
                { wch: 12 },  // Số lượng
                { wch: 15 },  // Đơn giá
                { wch: 15 }   // Thành tiền
            ];
            ws['!cols'] = colWidths;

            // Merge cells cho header
            const merges = [];
            for (let i = 0; i < headerRows.length; i++) {
                merges.push({
                    s: { r: i, c: 0 },
                    e: { r: i, c: 5 }
                });
            }
            ws['!merges'] = merges;

            XLSX.utils.book_append_sheet(wb, ws, "Báo cáo tổng hợp");
            XLSX.writeFile(wb, `bao-cao-tong-hop-${new Date().toISOString().split('T')[0]}.xlsx`);
        }
        function exportToExcel() {
            const searchText = document.getElementById('searchInput').value.toLowerCase();
            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 (!activeGroups.includes('all') && activeGroups.length > 0) {
                filteredData = filteredData.filter(item => activeGroups.includes(item.nhomsp));
            }

            const headerRows = [
                ['NHATGIANG STORE'],
                ['SN 729 Bà Triệu, P. Trường Thi, TPTH - ĐT: 091905061'],
                ['BÁO CÁO HÀNG TỒN'],
                ['']
            ];

            const fromDate = document.getElementById('fromDate').value;
            const toDate = document.getElementById('toDate').value;
            if (fromDate && toDate) {
                headerRows.push([`Từ ngày: ${fromDate} đến ngày: ${toDate}`]);
                headerRows.push(['']);
            }

            const exportTable = document.createElement('table');
            const thead = document.createElement('thead');

            headerRows.forEach(row => {
                const headerRow = document.createElement('tr');
                const cell = document.createElement('td');
                cell.colSpan = 10; // Tăng lên 10 cột
                cell.textContent = row[0];
                headerRow.appendChild(cell);
                thead.appendChild(headerRow);
            });

            const columnHeaders = document.createElement('tr');
            columnHeaders.innerHTML = `
        <th>STT</th>
        <th>Mã SP</th>
        <th>Tên SP</th>
        <th>Đvtính</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>
    `;
            thead.appendChild(columnHeaders);
            exportTable.appendChild(thead);

            const tbody = document.createElement('tbody');
            filteredData.forEach((item, index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
            <td>${index + 1}</td>
            <td>${item.masp}</td>
            <td>${item.tensp}</td>
            <td>${item.dvtinh}</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>
        `;
                tbody.appendChild(row);
            });
            exportTable.appendChild(tbody);

            const summary = calculateSummary(filteredData);
            const tfoot = document.createElement('tfoot');
            tfoot.innerHTML = `
        <tr>
            <td colspan="4" style="font-weight: bold">Tổng cộng:</td>
            <td>${summary.totalPurchases}</td>
            <td>${summary.totalSales}</td>
            <td>${summary.totalStock}</td>
            <td>${summary.totalPurchaseAmount}</td>
            <td>${summary.totalSaleAmount}</td>
            <td>${summary.totalProfit}</td>
        </tr>
    `;
            exportTable.appendChild(tfoot);

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

            // Định dạng style cho header
            const headerStyle = {
                font: { bold: true, sz: 14 },
                alignment: { horizontal: 'center', vertical: 'center' }
            };

            const titleStyle = {
                font: { bold: true, sz: 16 },
                alignment: { horizontal: 'center', vertical: 'center' }
            };

            // Style cho tất cả các ô trong bảng
            const allCellStyle = {
                border: {
                    top: { style: 'thin', color: { rgb: "000000" } },
                    bottom: { style: 'thin', color: { rgb: "000000" } },
                    left: { style: 'thin', color: { rgb: "000000" } },
                    right: { style: 'thin', color: { rgb: "000000" } }
                }
            };

            // Style cho dòng tổng cộng
            const summaryStyle = {
                font: { bold: true },
                border: {
                    top: { style: 'thin', color: { rgb: "000000" } },
                    bottom: { style: 'thin', color: { rgb: "000000" } },
                    left: { style: 'thin', color: { rgb: "000000" } },
                    right: { style: 'thin', color: { rgb: "000000" } }
                }
            };

            // Áp dụng style cho header
            ['A1', 'A2'].forEach(cell => {
                if (!ws[cell]) ws[cell] = {};
                ws[cell].s = headerStyle;
            });

            if (!ws['A3']) ws['A3'] = {};
            ws['A3'].s = titleStyle;

            if (fromDate && toDate) {
                if (!ws['A5']) ws['A5'] = {};
                ws['A5'].s = headerStyle;
            }

            // Áp dụng style cho tất cả các ô trong bảng
            const range = XLSX.utils.decode_range(ws['!ref']);
            const headerRowIndex = fromDate && toDate ? 6 : 4;

            for (let R = headerRowIndex; R <= range.e.r; R++) {
                for (let C = 0; C <= range.e.c; C++) {
                    const cellRef = XLSX.utils.encode_cell({ r: R, c: C });
                    if (!ws[cellRef]) ws[cellRef] = {};

                    // Áp dụng style tổng cộng cho dòng cuối
                    if (R === range.e.r) {
                        ws[cellRef].s = summaryStyle;
                    } else {
                        ws[cellRef].s = allCellStyle;
                    }
                }
            }

            // Thiết lập độ rộng cột
            const colWidths = [
                { wch: 6 },   // STT
                { wch: 12 },  // Mã SP
                { wch: 30 },  // Tên SP
                { wch: 10 },  // Đvtính
                { 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
            ];
            ws['!cols'] = colWidths;

            // Tính số dòng header để merge
            const numberOfHeaderRows = headerRows.length;
            const merges = [];
            for (let i = 0; i < numberOfHeaderRows; i++) {
                merges.push({
                    s: { r: i, c: 0 },
                    e: { r: i, c: 9 }
                });
            }
            ws['!merges'] = merges;

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

        }
        // Initialize
        window.onload = async () => {
            await fetchAllData();
            initializeEventListeners();
        };
    </script>
</body>

</html>