<script>
    $(document).ready(function() {
        // Cache DOM elements
        const $chartArea = $("#transactions-chart");
        const $daterangeTransactions = $('#daterange-transactions');

        // Get the Laravel-generated data as a JavaScript object
        let transactions = @json($transactionsStatistics);

        let chart = null; // Store the chart instance

        // Initialize the date range picker and chart
        initializeDateRangePicker();
        createTransactionChart(transactions); // Call it initially to load the default data

        // Function to initialize the date range picker
        function initializeDateRangePicker() {
            $daterangeTransactions.daterangepicker({
                opens: 'left'
            }, function(start, end) {
                fetchTransactionsData(start, end);
            });
        }

        // Function to fetch data from the server based on date range
        function fetchTransactionsData(start, end) {
            $.ajax({
                url: '{{ route('user.dashboard') }}',
                data: {
                    start_date: start.format('DD-MM-YYYY'),
                    end_date: end.format('DD-MM-YYYY')
                },
                method: 'GET',
                success: function(data) {
                    transactions = data;
                    updateTransactionChart(transactions); // Update the chart with new data
                },
                error: function() {
                    console.error('Error fetching transaction data.');
                }
            });
        }

        // Function to create or update the chart
        function createTransactionChart(transactionsData) {
            let transactionDates = Object.keys(transactionsData);

            let transactionsPendingArrayValues = transactionDates.map(key => transactionsData[key].pending ?? 0);
            let transactionsCompletedArrayValues = transactionDates.map(key => transactionsData[key].completed ?? 0);
            let transactionsCanceledArrayValues = transactionDates.map(key => transactionsData[key].failed ?? 0);

            const chartOptions = {
                chart: {
                    type: "area",
                    fontFamily: 'inherit',
                    height: 240,
                    parentHeightOffset: 0,
                    toolbar: { show: false },
                    animations: { enabled: false }
                },
                dataLabels: { enabled: false },
                fill: { opacity: 0.16, type: 'solid' },
                stroke: { width: 2, lineCap: "round", curve: "smooth" },
                series: [
                    { name: "Pending", data: transactionsPendingArrayValues },
                    { name: "Completed", data: transactionsCompletedArrayValues },
                    { name: "Canceled", data: transactionsCanceledArrayValues }
                ],
                tooltip: { theme: 'dark' },
                grid: {
                    padding: { top: -20, right: 0, left: -4, bottom: -4 },
                    strokeDashArray: 4
                },
                xaxis: {
                    labels: { padding: 0 },
                    axisBorder: { show: false },
                    tooltip: { enabled: false },
                    type: 'datetime',
                    categories: transactionDates
                },
                yaxis: { labels: { padding: 4 } },
                labels: transactionDates,
                colors: [tabler.getColor("primary"), tabler.getColor("success"), tabler.getColor("danger")],
                legend: {
                    show: true,
                    position: 'bottom',
                    offsetY: 12,
                    markers: { width: 10, height: 10, radius: 100 },
                    itemMargin: { horizontal: 8, vertical: 8 }
                }
            };

            // Destroy existing chart instance if it exists
            if (chart) {
                chart.destroy();
            }

            // Create new chart instance and render
            chart = new ApexCharts($chartArea[0], chartOptions);
            chart.render();
        }

        // Function to update the chart data dynamically
        function updateTransactionChart(transactionsData) {
            if (chart) {
                let transactionDates = Object.keys(transactionsData);

                let transactionsPendingArrayValues = transactionDates.map(key => transactionsData[key].pending ?? 0);
                let transactionsCompletedArrayValues = transactionDates.map(key => transactionsData[key].completed ?? 0);
                let transactionsCanceledArrayValues = transactionDates.map(key => transactionsData[key].failed ?? 0);

                // Update the chart's series and categories with new data
                chart.updateSeries([
                    { name: "Pending", data: transactionsPendingArrayValues },
                    { name: "Completed", data: transactionsCompletedArrayValues },
                    { name: "Canceled", data: transactionsCanceledArrayValues }
                ]);

                chart.updateOptions({
                    xaxis: {
                        categories: transactionDates
                    },
                    labels: transactionDates
                });
            }
        }

        // Initial call to create the chart
        createTransactionChart(transactions);
    });
</script>

<script>

    let serviceStatistic = @json($serviceStatistics);

    let serviceStatisticKeys = Object.keys(serviceStatistic);

    let serviceStatisticValues = Object.values(serviceStatistic);

    let serviceStatisticLabels = serviceStatisticKeys.map(key => key.charAt(0).toUpperCase() + key.slice(1));

    document.addEventListener("DOMContentLoaded", function() {
        var options = {
            series: serviceStatisticValues,
            chart: {
                width: 380,
                type: 'pie',
            },
            labels: serviceStatisticLabels,
            responsive: [{
                breakpoint: 480,
                options: {
                    chart: {
                        width: 300  // Smaller size for mobile
                    },
                    legend: {
                        position: 'bottom'
                    }
                }
            }],
        };

        var chart = new ApexCharts(document.querySelector("#chart-demo-pie"), options);
        chart.render();
    });

</script>
