


<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        const ctx = document.getElementById('total_sales_chart1').getContext('2d');
        let chart; // Variable to hold the Chart instance

        // Function to fetch data from API based on date range
        function fetchData(dateRange) {
            let url = `http://localhost:8000/orders_api?date_range=${dateRange}`; // Replace with your actual endpoint
            return fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .catch(error => {
                    console.error('Error fetching data:', error);
                    throw error;
                });
        }

        // Function to extract x and y values for the chart
        function extractChartData(orders) {
            const xValues = orders.map(order => order.created_at);
            const yValues = orders.map(order => parseFloat(order.UserTotalCost));

            return { xValues, yValues };
        }

        // Function to calculate the total sales
        function calculateTotalSales(yValues) {
            return yValues.reduce((total, currentValue) => total + currentValue, 0);
        }

        // Function to update the Chart.js chart with animation
        function updateChart(xValues, yValues) {
            if (chart) {
                // Update chart data with animation
                chart.data.labels = xValues;
                chart.data.datasets[0].data = yValues;
                chart.update({
                    duration: 800, // Animation duration in milliseconds
                    easing: 'easeOutQuart' // Easing function for smooth animation
                });
            } else {
                // Create new chart instance
                chart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: xValues,
                        datasets: [{
                            label: 'Total Sales',
                            data: yValues,
                            fill: true,
                            lineTension: 0,
                            backgroundColor: "#C5E8FF",
                            borderColor: "#1B59F8",
                            borderWidth: 1.3,
                            pointBackgroundColor: "#1B59F8",
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        legend: {
                            display: false
                        },
                        scales: {
                            xAxes: [{
                                type: 'time',
                                time: {
                                    unit: 'day' // Adjust as per your data granularity
                                },
                                ticks: {
                                    autoSkip: true,
                                    maxTicksLimit: 10, // Limit max number of ticks on x-axis
                                    maxRotation: 0, // Rotate labels if needed
                                    minRotation: 0
                                },
                                gridLines: {
                                    display: true
                                }
                            }],
                            yAxes: [{
                                ticks: {
                                    beginAtZero: true
                                },
                                gridLines: {
                                    color: "rgba(0,0,0,0.1)",
                                    backgroundColor: "#0fa958"
                                },
                                position: 'left'
                            }]
                        },
                        animation: {
                            duration: 800, // Animation duration in milliseconds
                            easing: 'easeOutQuart' // Easing function for smooth animation
                        }
                    }
                });
            }
        }

        // Function to load orders data, update chart, and calculate total sales
        function loadOrdersData(dateRange) {
            fetchData(dateRange)
                .then(data => {
                    if (data.success) {
                        const { xValues, yValues } = extractChartData(data.data);
                        updateChart(xValues, yValues);

                        // Calculate and display total sales
                        const totalSales = calculateTotalSales(yValues);
                        document.getElementById('total_cost2').textContent = '₹ ' + totalSales.toFixed(2); // Display total with two decimal places
                    } else {
                        console.error('Error fetching orders');
                    }
                })
                .catch(error => console.error('Error fetching orders:', error));
        }

        // Initialize Date Range Picker
        $('#reportrange').daterangepicker({
            startDate: moment(),
            endDate: moment(),
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            }
        }, function(start, end) {
            $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
            const dateRange = start.format('YYYY-MM-DD') + ' - ' + end.format('YYYY-MM-DD');
            loadOrdersData(dateRange);
        });

        // Initial load with default date range (today)
        const initialDateRange = moment().format('YYYY-MM-DD') + ' - ' + moment().format('YYYY-MM-DD');
        loadOrdersData(initialDateRange);

        // Event listener for dropdown change (optional if using date range picker only)
        /*
        document.getElementById('dateRange').addEventListener('change', function() {
            const selectedDateRange = this.value;
            loadOrdersData(selectedDateRange);
        });
        */
    });
</script>

