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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Thu Chi</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://code.highcharts.com/highcharts.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }

        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.9);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }

        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        .card {
            transition: all 0.3s ease;
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }

        .animate-fade-in {
            animation: fadeIn 0.5s ease-in;
        }

        .skeleton {
            animation: skeleton-loading 1s linear infinite alternate;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }

        @keyframes skeleton-loading {
            0% {
                background-color: #f3f4f6;
            }

            100% {
                background-color: #e5e7eb;
            }
        }

        .dark-mode {
            background-color: #1a1a1a;
            color: #ffffff;
        }

        .tooltip {
            position: relative;
            display: inline-block;
        }

        .tooltip .tooltip-text {
            visibility: hidden;
            width: 120px;
            background-color: #555;
            color: #fff;
            text-align: center;
            border-radius: 6px;
            padding: 5px;
            position: absolute;
            z-index: 1;
            bottom: 125%;
            left: 50%;
            margin-left: -60px;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .tooltip:hover .tooltip-text {
            visibility: visible;
            opacity: 1;
        }

        .dark-mode {
            background-color: #1a1a1a;
            color: #ffffff;
        }

        .dark-mode .bg-white {
            background-color: #2d2d2d;
        }

        .dark-mode .bg-gray-50 {
            background-color: #3d3d3d;
        }

        .dark-mode .text-gray-600,
        .dark-mode .text-gray-700 {
            color: #d1d5db;
        }

        .dark-mode .border-gray-200 {
            border-color: #374151;
        }

        .dark-mode .divide-gray-200>* {
            border-color: #374151;
        }
    </style>
</head>

<body class="bg-gray-50">
    <!-- Loading Overlay -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="loading-spinner"></div>
    </div>

    <!-- Toast Notification -->
    <div id="toast" class="fixed top-4 right-4 z-50 hidden">
        <div class="bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg">
            <span id="toastMessage"></span>
        </div>
    </div>

    <div class="flex min-h-screen">
        <!-- Sidebar -->
        <div class="w-64 bg-white shadow-lg p-6 space-y-6">
            <div class="flex items-center space-x-2 mb-6">
                <svg class="w-6 h-6 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16m-7 6h7" />
                </svg>
                <h2 class="text-xl font-bold">Bộ lọc</h2>
            </div>

            <div class="space-y-4">
                <div class="form-group">
                    <label class="block mb-2 text-sm font-medium text-gray-700">Từ ngày</label>
                    <input type="date" id="fromDate"
                        class="w-full border-2 border-gray-200 rounded-lg p-2.5 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all">
                </div>

                <div class="form-group">
                    <label class="block mb-2 text-sm font-medium text-gray-700">Đến ngày</label>
                    <input type="date" id="toDate"
                        class="w-full border-2 border-gray-200 rounded-lg p-2.5 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all">
                </div>

                <div class="form-group">
                    <label class="block mb-2 text-sm font-medium text-gray-700">Loại phiếu</label>
                    <select id="loaiPhieu"
                        class="w-full border-2 border-gray-200 rounded-lg p-2.5 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all">
                        <option value="all">Tất cả</option>
                        <option value="thu">Thu</option>
                        <option value="chi">Chi</option>
                    </select>
                </div>

                <button id="filterButton" onclick="handleFilterAndRender()"
                    class="w-full bg-blue-500 hover:bg-blue-600 text-white font-medium px-4 py-2.5 rounded-lg transition-colors">
                    Áp dụng
                </button>

                <!-- Export Buttons -->
                <div class="flex space-x-2">
                    <button onclick="exportToPDF()"
                        class="flex-1 bg-red-500 hover:bg-red-600 text-white font-medium px-4 py-2 rounded-lg transition-colors">
                        PDF
                    </button>
                    <button onclick="exportToExcel()"
                        class="flex-1 bg-green-500 hover:bg-green-600 text-white font-medium px-4 py-2 rounded-lg transition-colors">
                        Excel
                    </button>
                </div>
            </div>
        </div>

        <!-- Main Content -->
        <div class="flex-1 p-6 space-y-6">
            <!-- Header -->
            <div class="flex justify-between items-center">
                <h1 class="text-3xl font-bold">Dashboard Thu Chi</h1>
                <div class="flex items-center space-x-4">
                    <!-- Search Bar -->
                    <div class="relative">
                        <input type="text" id="searchInput" placeholder="Tìm kiếm..."
                            class="w-64 pl-10 pr-4 py-2 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all">
                        <svg class="w-5 h-5 text-gray-400 absolute left-3 top-2.5" fill="none" stroke="currentColor"
                            viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                        </svg>
                    </div>

                    <!-- Dark Mode Toggle -->
                    <button id="darkModeToggle" class="p-2 rounded-lg hover:bg-gray-100 transition-colors">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" />
                        </svg>
                    </button>
                </div>
            </div>

            <!-- Statistics Cards -->
            <div class="grid grid-cols-2 gap-6">
                <!-- Thu Card -->
                <div class="card bg-white p-6 rounded-xl shadow-lg">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="font-bold text-xl text-green-600">Thống kê Thu</h3>
                        <span class="p-2 bg-green-100 rounded-full">
                            <svg class="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M12 4v16m8-8H4" />
                            </svg>
                        </span>
                    </div>
                    <div class="grid grid-cols-2 gap-6">
                        <div class="p-4 bg-gray-50 rounded-lg">
                            <p class="text-gray-600 text-sm mb-1">Tổng thu:</p>
                            <p id="tongThu" class="text-2xl font-bold text-green-600">0 đ</p>
                        </div>
                        <div class="p-4 bg-gray-50 rounded-lg">
                            <p class="text-gray-600 text-sm mb-1">Đã thanh toán:</p>
                            <p id="daThanhToanThu" class="text-2xl font-bold text-green-500">0 đ</p>
                        </div>
                        <div class="p-4 bg-gray-50 rounded-lg">
                            <p class="text-gray-600 text-sm mb-1">Còn nợ:</p>
                            <p id="congNoThu" class="text-2xl font-bold text-orange-500">0 đ</p>
                        </div>
                        <div class="p-4 bg-gray-50 rounded-lg">
                            <p class="text-gray-600 text-sm mb-1">Số đơn:</p>
                            <p id="soDonThu" class="text-2xl font-bold text-blue-500">0</p>
                        </div>
                    </div>
                </div>

                <!-- Chi Card -->
                <div class="card bg-white p-6 rounded-xl shadow-lg">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="font-bold text-xl text-red-600">Thống kê Chi</h3>
                        <span class="p-2 bg-red-100 rounded-full">
                            <svg class="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 12H4" />
                            </svg>
                        </span>
                    </div>
                    <div class="grid grid-cols-2 gap-6">
                        <div class="p-4 bg-gray-50 rounded-lg">
                            <p class="text-gray-600 text-sm mb-1">Tổng chi:</p>
                            <p id="tongChi" class="text-2xl font-bold text-red-600">0 đ</p>
                        </div>
                        <div class="p-4 bg-gray-50 rounded-lg">
                            <p class="text-gray-600 text-sm mb-1">Đã thanh toán:</p>
                            <p id="daThanhToanChi" class="text-2xl font-bold text-red-500">0 đ</p>
                        </div>
                        <div class="p-4 bg-gray-50 rounded-lg">
                            <p class="text-gray-600 text-sm mb-1">Còn nợ:</p>
                            <p id="congNoChi" class="text-2xl font-bold text-orange-500">0 đ</p>
                        </div>
                        <div class="p-4 bg-gray-50 rounded-lg">
                            <p class="text-gray-600 text-sm mb-1">Số đơn:</p>
                            <p id="soDonChi" class="text-2xl font-bold text-blue-500">0</p>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Charts Grid -->
            <div class="grid grid-cols-2 gap-6">
                <!-- Pie Chart -->
                <div class="card bg-white p-6 rounded-xl shadow-lg">
                    <div id="pieChart" style="height: 300px"></div>
                </div>
                <!-- Column Chart -->
                <div class="card bg-white p-6 rounded-xl shadow-lg">
                    <div id="columnChart" style="height: 300px"></div>
                </div>
            </div>

            <!-- Công nợ Charts -->
            <div class="grid grid-cols-2 gap-6">
                <div class="card bg-white p-6 rounded-xl shadow-lg">
                    <div id="congNoThuChart" style="height: 300px"></div>
                </div>
                <div class="card bg-white p-6 rounded-xl shadow-lg">
                    <div id="congNoChiChart" style="height: 300px"></div>
                </div>
            </div>

            <!-- Data Table -->
            <div class="card bg-white rounded-xl shadow-lg overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="group px-6 py-3 text-left cursor-pointer">
                                    <div class="flex items-center space-x-2">
                                        <span class="text-xs font-medium text-gray-500 uppercase tracking-wider">ID</span>
                                        <svg class="w-4 h-4 text-gray-400 opacity-0 group-hover:opacity-100" fill="none"
                                            stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4" />
                                        </svg>
                                    </div>
                                </th>
                                <th class="group px-6 py-3 text-left cursor-pointer">
                                    <div class="flex items-center space-x-2">
                                        <span class="text-xs font-medium text-gray-500 uppercase tracking-wider">Loại phiếu</span>
                                        <svg class="w-4 h-4 text-gray-400 opacity-0 group-hover:opacity-100" fill="none"
                                            stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4" />
                                        </svg>
                                    </div>
                                </th>
                                <th class="group px-6 py-3 text-left cursor-pointer">
                                    <div class="flex items-center space-x-2">
                                        <span class="text-xs font-medium text-gray-500 uppercase tracking-wider">Thời gian</span>
                                        <svg class="w-4 h-4 text-gray-400 opacity-0 group-hover:opacity-100" fill="none"
                                            stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4" />
                                        </svg>
                                    </div>
                                </th>
                                <th class="group px-6 py-3 text-left cursor-pointer">
                                    <div class="flex items-center space-x-2">
                                        <span class="text-xs font-medium text-gray-500 uppercase tracking-wider">Nội dung</span>
                                        <svg class="w-4 h-4 text-gray-400 opacity-0 group-hover:opacity-100" fill="none"
                                            stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4" />
                                        </svg>
                                    </div>
                                </th>
                                <th class="group px-6 py-3 text-left cursor-pointer">
                                    <div class="flex items-center space-x-2">
                                        <span class="text-xs font-medium text-gray-500 uppercase tracking-wider">Đối tượng</span>
                                        <svg class="w-4 h-4 text-gray-400 opacity-0 group-hover:opacity-100" fill="none"
                                            stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4" />
                                        </svg>
                                    </div>
                                </th>
                                <th class="group px-6 py-3 text-left cursor-pointer">
                                    <div class="flex items-center space-x-2">
                                        <span class="text-xs font-medium text-gray-500 uppercase tracking-wider">Tổng tiền</span>
                                        <svg class="w-4 h-4 text-gray-400 opacity-0 group-hover:opacity-100" fill="none"
                                            stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4" />
                                        </svg>
                                    </div>
                                </th>
                                <th class="group px-6 py-3 text-left cursor-pointer">
                                    <div class="flex items-center space-x-2">
                                        <span class="text-xs font-medium text-gray-500 uppercase tracking-wider">Đã thanh toán</span>
                                        <svg class="w-4 h-4 text-gray-400 opacity-0 group-hover:opacity-100" fill="none"
                                            stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4" />
                                        </svg>
                                    </div>
                                </th>
                                <th class="group px-6 py-3 text-left cursor-pointer">
                                    <div class="flex items-center space-x-2">
                                        <span class="text-xs font-medium text-gray-500 uppercase tracking-wider">Còn nợ</span>
                                        <svg class="w-4 h-4 text-gray-400 opacity-0 group-hover:opacity-100" fill="none"
                                            stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4" />
                                        </svg>
                                    </div>
                                </th>
                             
                            </tr>
                        </thead>
                        <tbody id="reportData" class="bg-white divide-y divide-gray-200"></tbody>
                    </table>
                </div>
                <!-- Pagination -->
                <div class="px-6 py-3 flex items-center justify-between border-t border-gray-200">
                    <div class="flex-1 flex justify-between sm:hidden">
                        <button
                            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">
                            Trước
                        </button>
                        <button
                            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">
                            Sau
                        </button>
                    </div>
                    <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                        <div>
                            <p class="text-sm text-gray-700">
                                Hiển thị <span class="font-medium">1</span> đến <span class="font-medium">10</span> của
                                <span class="font-medium">20</span> kết quả
                            </p>
                        </div>
                        <div>
                            <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                                <!-- Pagination buttons -->
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Khai báo API credentials và các biến toàn cục giữ nguyên
        const APP_ID = 'a3c21623-f7da-4dfd-bbe4-197bd67d7296';
        const ACCESS_KEY = 'V2-5WcPS-sJgmv-8IXNy-QnfZ7-8sfxW-8XiP6-bZe4T-IaHdV';
        let globalData = {
            thuChi: [],
            nhapHang: [],
            banHang: []
        };

        // Cấu hình chung cho biểu đồ
        const chartConfig = {
            chart: {
                style: {
                    fontFamily: 'Inter, sans-serif'
                },
                backgroundColor: 'transparent',
                borderRadius: 8,
                animation: {
                    duration: 1000
                }
            },
            title: {
                style: {
                    fontSize: '18px',
                    fontWeight: 'bold'
                }
            },
            credits: {
                enabled: false
            }
        };

        // Toast notification
        function showToast(message, type = 'success') {
            const toast = document.getElementById('toast');
            const toastMessage = document.getElementById('toastMessage');
            toastMessage.textContent = message;

            toast.classList.remove('hidden');
            toast.classList.add('animate-fade-in');

            setTimeout(() => {
                toast.classList.add('hidden');
                toast.classList.remove('animate-fade-in');
            }, 3000);
        }

        // Dark mode toggle
        const darkModeToggle = document.getElementById('darkModeToggle');
        darkModeToggle.addEventListener('click', () => {
            document.body.classList.toggle('dark-mode');
            // Update charts theme accordingly
            updateChartsTheme();
        });
        function updateChartsTheme() {
            const isDarkMode = document.body.classList.contains('dark-mode');
            const theme = {
                background: isDarkMode ? '#1a1a1a' : 'transparent',
                textColor: isDarkMode ? '#ffffff' : '#333333'
            };

            // Cập nhật style cho tất cả biểu đồ
            const charts = ['pieChart', 'columnChart', 'congNoThuChart', 'congNoChiChart'].map(id =>
                Highcharts.charts[Highcharts.getChartById(id)?.index]
            ).filter(Boolean);

            charts.forEach(chart => {
                if (chart) {
                    chart.update({
                        chart: {
                            backgroundColor: theme.background
                        },
                        title: {
                            style: {
                                color: theme.textColor
                            }
                        },
                        legend: {
                            itemStyle: {
                                color: theme.textColor
                            }
                        }
                    });
                }
            });
        }
        // Search functionality
        const searchInput = document.getElementById('searchInput');
        searchInput.addEventListener('input', (e) => {
            const searchTerm = e.target.value.toLowerCase();
            filterDataBySearch(searchTerm);
        });

        function filterDataBySearch(searchTerm) {
            const filteredData = globalData.thuChi.filter(item =>
                item.ID.toLowerCase().includes(searchTerm) ||
                item.Noidung.toLowerCase().includes(searchTerm) ||
                item.Tendoituong.toLowerCase().includes(searchTerm)
            );
            processData(filteredData, globalData.nhapHang, globalData.banHang, globalData.thuChi);
        }

        // Export functions
        function exportToPDF() {
            showToast('Đang xuất file PDF...');
            // Implement PDF export logic
        }

        function exportToExcel() {
            showToast('Đang xuất file Excel...');
            // Implement Excel export logic
        }

        // Update các hàm xử lý dữ liệu và render chart với animation và style mới
        function renderCharts(stats, thuChiData, nhapHangData, banHangData) {
            // 1. Biểu đồ tròn Thu/Chi
            Highcharts.chart('pieChart', {
                ...chartConfig,
                chart: {
                    ...chartConfig.chart,
                    type: 'pie'
                },
                title: {
                    text: 'Tỷ lệ Thu/Chi'
                },
                plotOptions: {
                    pie: {
                        borderRadius: 5,
                        innerSize: '60%',
                        dataLabels: {
                            enabled: true,
                            format: '{point.percentage:.1f}%'
                        }
                    }
                },
                series: [{
                    name: 'Giá trị',
                    data: [
                        { name: 'Thu', y: stats.tongThu, color: '#10B981' },
                        { name: 'Chi', y: stats.tongChi, color: '#EF4444' }
                    ]
                }]
            });

            // 2. Biểu đồ cột theo thời gian
            const timeData = processDailyData(thuChiData, nhapHangData, banHangData);
            Highcharts.chart('columnChart', {
                ...chartConfig,
                chart: {
                    ...chartConfig.chart,
                    type: 'column'
                },
                title: {
                    text: 'Thu Chi theo thời gian'
                },
                xAxis: {
                    categories: timeData.categories,
                    crosshair: true
                },
                yAxis: {
                    title: {
                        text: 'Giá trị (VNĐ)'
                    }
                },
                series: [{
                    name: 'Thu',
                    data: timeData.thuData,
                    color: '#10B981'
                }, {
                    name: 'Chi',
                    data: timeData.chiData,
                    color: '#EF4444'
                }]
            });

            // 3. Biểu đồ công nợ thu
            Highcharts.chart('congNoThuChart', {
                ...chartConfig,
                chart: {
                    ...chartConfig.chart,
                    type: 'pie'
                },
                title: {
                    text: 'Công nợ Thu'
                },
                plotOptions: {
                    pie: {
                        borderRadius: 5,
                        innerSize: '60%',
                        dataLabels: {
                            enabled: true,
                            format: '{point.percentage:.1f}%'
                        }
                    }
                },
                series: [{
                    name: 'Giá trị',
                    data: [
                        { name: 'Đã thanh toán', y: stats.daThanhToanThu, color: '#10B981' },
                        { name: 'Còn nợ', y: stats.congNoThu, color: '#F97316' }
                    ]
                }]
            });

            // 4. Biểu đồ công nợ chi
            Highcharts.chart('congNoChiChart', {
                ...chartConfig,
                chart: {
                    ...chartConfig.chart,
                    type: 'pie'
                },
                title: {
                    text: 'Công nợ Chi'
                },
                plotOptions: {
                    pie: {
                        borderRadius: 5,
                        innerSize: '60%',
                        dataLabels: {
                            enabled: true,
                            format: '{point.percentage:.1f}%'
                        }
                    }
                },
                series: [{
                    name: 'Giá trị',
                    data: [
                        { name: 'Đã thanh toán', y: stats.daThanhToanChi, color: '#EF4444' },
                        { name: 'Còn nợ', y: stats.congNoChi, color: '#F97316' }
                    ]
                }]
            });
        }

        // Hàm xử lý dữ liệu theo thời gian
        function processDailyData(thuChiData, nhapHangData, banHangData) {
            const dailyData = {};

            thuChiData.forEach(item => {
                const date = formatDate(item.Thoigian);
                if (!dailyData[date]) {
                    dailyData[date] = { thu: 0, chi: 0 };
                }

                const chiTiet = item.Loaiphieu.toLowerCase() === 'thu'
                    ? banHangData.find(bh => bh.IDBANHANG === item.key)
                    : nhapHangData.find(nh => nh.IDNHAPHANG === item.key);

                if (chiTiet) {
                    const amount = parseFloat(chiTiet.Tongtien || 0);
                    if (item.Loaiphieu.toLowerCase() === 'thu') {
                        dailyData[date].thu += amount;
                    } else {
                        dailyData[date].chi += amount;
                    }
                }
            });

            const categories = Object.keys(dailyData).sort();
            const thuData = categories.map(date => dailyData[date].thu);
            const chiData = categories.map(date => dailyData[date].chi);

            return { categories, thuData, chiData };
        }
        // Update existing functions with loading states and error handling
        async function getData() {
            const loadingOverlay = document.getElementById('loadingOverlay');
            try {
                loadingOverlay.style.display = 'flex';

                const [thuChiData, nhapHangData, banHangData] = await Promise.all([
                    fetchData('ThuChi'),
                    fetchData('NHAPHANG'),
                    fetchData('BANHANG')
                ]);

                globalData = {
                    thuChi: thuChiData,
                    nhapHang: nhapHangData,
                    banHang: banHangData
                };

                handleFilterAndRender();
                showToast('Dữ liệu đã được cập nhật');

            } catch (error) {
                console.error('Lỗi:', error);
                showToast('Có lỗi xảy ra khi tải dữ liệu', 'error');
            } finally {
                loadingOverlay.style.display = 'none';
            }
        }
        // Hàm fetch data từ API
        async function fetchData(tableName) {
            try {
                const config = {
                    method: 'post',
                    url: `https://www.appsheet.com/api/v2/apps/${APP_ID}/tables/${tableName}/Action`,
                    headers: {
                        'ApplicationAccessKey': ACCESS_KEY,
                        'Content-Type': 'application/json'
                    },
                    data: {
                        Action: 'Find',
                        Properties: {
                            Locale: 'vi-VN',
                            Timezone: 'Asia/Ho_Chi_Minh',
                            Selector: `Filter(${tableName}, true)`
                        },
                        Rows: []
                    }
                };

                const response = await axios(config);

                if (!response.data) {
                    throw new Error(`Không có dữ liệu trả về từ bảng ${tableName}`);
                }

                showToast(`Đã tải dữ liệu ${tableName} thành công`);
                return response.data;

            } catch (error) {
                console.error(`Lỗi khi lấy dữ liệu bảng ${tableName}:`, error);
                showToast(`Lỗi khi tải dữ liệu ${tableName}`, 'error');
                throw error;
            }
        }
        // Hàm xử lý filter và render
        function handleFilterAndRender() {
            const fromDate = document.getElementById('fromDate').value;
            const toDate = document.getElementById('toDate').value;
            const loaiPhieu = document.getElementById('loaiPhieu').value;

            const filteredThuChi = filterData(globalData.thuChi, fromDate, toDate, loaiPhieu);
            processData(filteredThuChi, globalData.nhapHang, globalData.banHang, globalData.thuChi);
        }

        // Hàm filter data
        function filterData(data, fromDate, toDate, loaiPhieu) {
            return data.filter(item => {
                const itemDate = new Date(item.Thoigian);
                const from = fromDate ? new Date(fromDate) : null;
                const to = toDate ? new Date(toDate) : null;

                const dateCondition = (!from || itemDate >= from) && (!to || itemDate <= to);
                const typeCondition = loaiPhieu === 'all' || item.Loaiphieu.toLowerCase() === loaiPhieu.toLowerCase();

                return dateCondition && typeCondition;
            });
        }

        // Hàm xử lý và hiển thị dữ liệu
        function processData(thuChiData, nhapHangData, banHangData, originalThuChiData) {
            const tableBody = document.getElementById('reportData');
            tableBody.innerHTML = '';

            let stats = {
                tongThu: 0,
                tongChi: 0,
                daThanhToanThu: 0,
                daThanhToanChi: 0,
                congNoThu: 0,
                congNoChi: 0,
                soDonThu: 0,
                soDonChi: 0
            };

            // Xử lý từng dòng dữ liệu
            thuChiData.forEach(item => {
                const row = document.createElement('tr');
                row.className = 'hover:bg-gray-50 transition-colors';

                // Tìm thông tin chi tiết từ bảng liên quan
                const chiTiet = item.Loaiphieu.toLowerCase() === 'thu'
                    ? banHangData.find(bh => bh.IDBANHANG === item.key)
                    : nhapHangData.find(nh => nh.IDNHAPHANG === item.key);

                if (chiTiet) {
                    const tongtien = parseFloat(chiTiet.Tongtien || 0);
                    const daThanhToan = parseFloat(chiTiet['Số tiền đã thanh toán'] || 0);
                    const conNo = parseFloat(chiTiet['Còn nợ'] || 0);

                    // Cập nhật thống kê
                    if (item.Loaiphieu.toLowerCase() === 'thu') {
                        stats.tongThu += tongtien;
                        stats.daThanhToanThu += daThanhToan;
                        stats.congNoThu += conNo;
                        stats.soDonThu++;
                    } else {
                        stats.tongChi += tongtien;
                        stats.daThanhToanChi += daThanhToan;
                        stats.congNoChi += conNo;
                        stats.soDonChi++;
                    }

                    // Tạo nội dung cho row
                    row.innerHTML = `
                <td class="px-6 py-4 whitespace-nowrap">${item.ID}</td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <span class="px-2 py-1 text-xs font-semibold rounded-full
                        ${item.Loaiphieu.toLowerCase() === 'thu'
                            ? 'bg-green-100 text-green-800'
                            : 'bg-red-100 text-red-800'}">
                        ${item.Loaiphieu.toUpperCase()}
                    </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">${formatDate(item.Thoigian)}</td>
                <td class="px-6 py-4">${item.Noidung}</td>
                <td class="px-6 py-4">${item.Tendoituong}</td>
                <td class="px-6 py-4">${formatMoney(tongtien)}</td>
                <td class="px-6 py-4">${formatMoney(daThanhToan)}</td>
                <td class="px-6 py-4">${formatMoney(conNo)}</td>
               
            `;
                }

                tableBody.appendChild(row);
            });

            // Cập nhật thống kê
            updateStatistics(stats);

            // Vẽ biểu đồ
            renderCharts(stats, originalThuChiData, nhapHangData, banHangData);
        }

        // Hàm format tiền tệ
        function formatMoney(amount) {
            return new Intl.NumberFormat('vi-VN', {
                style: 'currency',
                currency: 'VND'
            }).format(amount || 0);
        }

        // Hàm format ngày tháng
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleDateString('vi-VN');
        }

        // Hàm cập nhật thống kê
        function updateStatistics(stats) {
            document.getElementById('tongThu').textContent = formatMoney(stats.tongThu);
            document.getElementById('tongChi').textContent = formatMoney(stats.tongChi);
            document.getElementById('daThanhToanThu').textContent = formatMoney(stats.daThanhToanThu);
            document.getElementById('daThanhToanChi').textContent = formatMoney(stats.daThanhToanChi);
            document.getElementById('congNoThu').textContent = formatMoney(stats.congNoThu);
            document.getElementById('congNoChi').textContent = formatMoney(stats.congNoChi);
            document.getElementById('soDonThu').textContent = stats.soDonThu;
            document.getElementById('soDonChi').textContent = stats.soDonChi;
        }
        // Initialize the dashboard
        getData();
    </script>
</body>

</html>