<div class="content-wrapper">
    <h3>Statistique du commercial</h3>

    <div style="width: 80%; margin: auto;">
        <canvas id="salesChart"></canvas>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    window.onload = function() {
        const ctx = document.getElementById("salesChart")?.getContext("2d");
        if (!ctx) {
            console.error("Canvas element not found!");
            return;
        }

        const userData = <?= $user_order ?>;

        if (!Array.isArray(userData) || userData.length === 0) {
            console.error("User data is empty or invalid", userData);
            return;
        }

        const currentYear = new Date().getFullYear();

        // Filter and sort data by date
        const filteredData = userData
            .filter(sale => new Date(sale.date_time).getFullYear() === currentYear)
            .sort((a, b) => new Date(a.date_time) - new Date(b.date_time)); // Sort by date

        if (filteredData.length === 0) {
            console.warn("No data available for the current year.");
            return;
        }

        let labels = filteredData.map(sale => sale.date_time);
        let salesAmounts = filteredData.map(sale => parseFloat(sale.net_amount));

        new Chart(ctx, {
            type: "line",
            data: {
                labels: labels,
                datasets: [{
                    label: "Montant (Net)",
                    data: salesAmounts,
                    backgroundColor: "rgba(54, 162, 235, 0.5)",
                    borderColor: "rgba(54, 162, 235, 1)",
                    borderWidth: 2,
                    fill: false,
                    tension: 0.3
                }]
            },
            options: {
                responsive: true,
                scales: {
                    x: {
                        title: {
                            display: true,
                            text: "Date & Heure"
                        }
                    },
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: "Montant (MGA)"
                        }
                    }
                }
            }
        });
    };
</script>
