<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_chart').getContext('2d');
        let chart;

        function fetchData(dateRange) {
            let url = `https://drycleaneo.com/admin/orders_api?date_range=${dateRange}`;
            return fetch(url)
                .then(response => response.json())
                .catch(error => console.error('Error fetching data:', error));
        }

        function aggregateSalesData(orders, startDate, endDate) {
            let salesData = {};

            orders.forEach(order => {
                let orderDate = moment(order.created_at);
                let formattedDate;

                if (startDate.isSame(endDate, 'day')) {
                    formattedDate = orderDate.format("HH:mm"); // Show time for today
                } else {
                    formattedDate = orderDate.format("D MMM");
                    if (!startDate.isSame(endDate, 'year')) {
                        formattedDate += ` ${orderDate.format("YYYY")}`;
                    }
                }

                if (!salesData[formattedDate]) {
                    salesData[formattedDate] = 0;
                }
                salesData[formattedDate] += parseFloat(order.UserTotalCost);
            });

            return Object.keys(salesData).map(date => ({
                x: date,
                y: salesData[date]
            }));
        }

        function calculateTotalSales(dataPoints) {
            return dataPoints.reduce((total, point) => total + point.y, 0);
        }

        function updateChart(dataPoints) {
            const xValues = dataPoints.map(point => point.x);
            const yValues = dataPoints.map(point => point.y);

            if (chart) {
                chart.data.labels = xValues;
                chart.data.datasets[0].data = yValues;
                chart.update();
            } else {
                chart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: xValues,
                        datasets: [{
                            label: 'Total Sales',
                            data: yValues,
                            fill: true,
                            backgroundColor: "rgba(27, 89, 248, 0.2)",
                            borderColor: "#1B59F8",
                            pointBackgroundColor: "#1B59F8",
                            pointBorderColor: "#fff",
                            pointHoverBackgroundColor: "#ff5722",
                            pointHoverBorderColor: "#ff5722",
                            borderWidth: 2,
                            lineTension: 0.3
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        tooltips: {
                            enabled: true,
                            mode: 'index',
                            intersect: false,
                            backgroundColor: "#1B59F8",
                            titleFontColor: "#fff",
                            bodyFontColor: "#fff",
                            callbacks: {
                                label: function(tooltipItem) {
                                    return `₹ ${tooltipItem.yLabel.toFixed(2)}`;
                                }
                            }
                        },
                        hover: {
                            mode: 'nearest',
                            intersect: true
                        },
                        scales: {
                            xAxes: [{
                                ticks: {
                                    autoSkip: true,
                                    maxTicksLimit: 10,
                                    fontColor: "#333"
                                },
                                gridLines: { color: "rgba(0,0,0,0.1)" }
                            }],
                            yAxes: [{
                                ticks: {
                                    beginAtZero: true,
                                    fontColor: "#333"
                                },
                                gridLines: { color: "rgba(0,0,0,0.1)" }
                            }]
                        }
                    }
                });
            }
        }

        function loadOrdersData(startDate, endDate) {
            let dateRange = `${startDate.format('YYYY-MM-DD')} - ${endDate.format('YYYY-MM-DD')}`;
            fetchData(dateRange).then(data => {
                if (data.success) {
                    let chartData = aggregateSalesData(data.data, startDate, endDate);
                    updateChart(chartData);

                    let totalSales = calculateTotalSales(chartData);
                    document.getElementById('total_cost1').textContent = '₹ ' + totalSales.toFixed(2);
                }
            });
        }

        $('#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'));
            loadOrdersData(start, end);
        });

        loadOrdersData(moment(), moment());
    });
</script>
