
 /**
 * =============================================================================
 * @package         Blue Raven (Free Version)
 * @Plugin URI      https://enterrahost.com/plugins/blue-raven
 * 
 * @Author          EnterraHost
 * @Author URI      https://enterrahost.com
 * @License         GPL-2.0-or-later
 *  
 * @Copyright       (c) 2025 EnterraHost
 * @Contents        Sales Analyitcs JS 
 * 
 * =============================================================================
 * 
 * || INDEX:
 * ||   - UPDATE SUMMARY STATS
 * ||   - LOAD DATA
 * ||   - CREATE CHEARTS
 * || 
 * =============================================================================
 */
    
(function ($) {
    
    $(document)
    
    /* ===========  Handle range selector change =========== */
       
    .on('change', '#sales-analytics-range', function() { if ($(this).val() === 'custom_month') { $('#month-selector').show(); } else { $('#month-selector').hide(); } })
    
    /* =========== Load Data =========== */
    
    .on('submit', '#sales-analytics-form', function(e) {e.preventDefault(); BlueRaven_loadData();})
    .on('change', '#sales-analytics-composite', function() {BlueRaven_loadData();})
    .on('click', '#home', function() {setTimeout(function() {BlueRaven_loadData(true); $('#sales-analytics').show();}, 500);});

/*
============================================================
    UPDATE SUMMARY STATS
============================================================
*/

    function BlueRaven_updateSummaryStats(data) {
        if (!data || typeof data !== 'object') {
            console.error('Invalid or missing data');
            return;
        }

    /* =========== Calculate totals =========== */

        const totalSales = Array.isArray(data.sales_per_day) 
            ? data.sales_per_day.reduce((a, b) => a + b, 0) 
            : 0;
        
        const totalRevenue = Array.isArray(data.revenue_per_day) 
            ? data.revenue_per_day.reduce((a, b) => a + b, 0) 
            : 0;
        
    /* =========== Calculate total units (use provided data or estimate) =========== */

        const totalUnits = data.total_units || 
            (Array.isArray(data.items_per_order) && data.items_per_order.length > 0
                ? Math.round(totalSales * (data.items_per_order.reduce((a, b) => a + b, 0) / data.items_per_order.length))
                : totalSales); 
        
    /* =========== Update the DOM =========== */

        $('#total-sales').text(totalSales.toLocaleString());
        $('#total-revenue').text('$' + totalRevenue.toLocaleString(undefined, { 
            minimumFractionDigits: 2, 
            maximumFractionDigits: 2 
        }));
        $('#total-units').text(totalUnits.toLocaleString());
    }

/*
============================================================
    LOAD DATA
============================================================
*/

    function BlueRaven_loadData() {
        var selectedRange = $('#sales-analytics-range').val() || 'current_month';
        var selectedMonth = $('#sales-analytics-month').val() || '2025-01';
        var showComposite = $('#sales-analytics-composite').is(':checked');
        
    /* =========== Toggle chart visibility based on composite selection =========== */
   
        if (showComposite) {
            $('.composite-chart-container').show();
            $('.individual-charts').hide();
        } else {
            $('.composite-chart-container').hide();
            $('.individual-charts').show();
        }

    /* =========== Load data via AJAX =========== */
    
        $.ajax({
            url: blue_raven_salesAnalyticsData.ajax_url,
            type: 'POST',
            data: {
                action: 'blue_raven_sales_analytics',
                nonce: blue_raven_salesAnalyticsData.nonce,
                subaction: 'BlueRaven_loadData',
                content: [selectedRange, selectedMonth]
            },
            success: function(response) {
                if (response.success) {
                    var data = response.data;
                    BlueRaven_updateSummaryStats(data);
                    BlueRaven_createCharts(data, showComposite);
                    $('#sales-analytics').show();
                } else {
                    console.error('Error loading data');
                }
            },
            error: function() {
                console.error('AJAX error');
            }
        });
    }
    
/*
============================================================
    CREATE CHEARTS
============================================================
*/

    function BlueRaven_createCharts(data, showComposite) {

        console.log(data);
        
    /* =========== Destroy existing charts if they exist =========== */
    
        Chart.helpers.each(Chart.instances, function(instance) {
            instance.destroy();
        });
        
    /* =========== Exit if no canvas exists =========== */
    
        const canvasIds = [
            'compositeChart', 
            'salesPerDayChart', 
            'revenuePerDayChart', 
            'salesByCategoryChart'
        ];
        const hasCanvas = canvasIds.some(id => document.getElementById(id));
        if (!hasCanvas) return;
    
        if (showComposite) {
            new Chart(
                document.getElementById('compositeChart'),
                {
                    type: 'line',
                    data: {
                        labels: data.labels,
                        datasets: [
                            {
                                label: 'Sales per Day',
                                data: data.sales_per_day,
                                borderColor: 'rgba(54, 162, 235, 1)',
                                backgroundColor: 'rgba(54, 162, 235, 0.1)',
                                yAxisID: 'y',
                                tension: 0.1
                            },
                            {
                                label: 'Revenue per Day',
                                data: data.revenue_per_day,
                                borderColor: 'rgba(75, 192, 192, 1)',
                                backgroundColor: 'rgba(75, 192, 192, 0.1)',
                                borderDash: [5, 5],
                                yAxisID: 'y1',
                                tension: 0.1
                            },
                            {
                                label: 'Cumulative Revenue',
                                data: data.cumulative_revenue,
                                borderColor: 'rgba(153, 102, 255, 1)',
                                backgroundColor: 'rgba(153, 102, 255, 0.1)',
                                yAxisID: 'y1',
                                tension: 0.1
                            },
                            {
                                label: 'Average Order Value',
                                data: data.aov_per_day,
                                borderColor: 'rgba(255, 159, 64, 1)',
                                backgroundColor: 'rgba(255, 159, 64, 0.1)',
                                borderDash: [5, 5],
                                yAxisID: 'y1',
                                tension: 0.1
                            },
                            {
                                label: 'Average Items per Order',
                                data: data.items_per_order,
                                borderColor: 'rgba(255, 99, 132, 1)',
                                backgroundColor: 'rgba(255, 99, 132, 0.1)',
                                yAxisID: 'y',
                                tension: 0.1
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        interaction: {
                            mode: 'index',
                            intersect: false,
                        },
                        stacked: false,
                        scales: {
                            y: {
                                type: 'linear',
                                display: true,
                                position: 'left',
                                title: {
                                    display: true,
                                    text: 'Count (Sales, Items)',
                                    color: '#ffffff' 
                                },
                                ticks: {
                                    color: '#ffffff' 
                                },
                                grid: {
                                    color: '#333333' 
                                }
                            },
                            y1: {
                                type: 'linear',
                                display: true,
                                position: 'right',
                                title: {
                                    display: true,
                                    text: 'Revenue ($)',
                                    color: '#ffffff' 
                                },
                                grid: {
                                    drawOnChartArea: false,
                                    color: '#333333' 
                                },
                                ticks: {
                                    color: '#ffffff' 
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: data.range_type === 'month' ? 'Day of Month' : 'Month',
                                    color: '#ffffff' 
                                },
                                grid: {
                                    drawOnChartArea: false,
                                    color: '#333333' 
                                },
                                ticks: {
                                    color: '#ffffff' 
                                }
                            }
                        },
                        plugins: {
                            title: {
                                display: true,
                                text: 'Composite Sales Metrics - ' + data.range_label,
                                color: '#ffffff' 
                            },
                            labels: {
                                color: '#ffffff' 
                            },
                            legend: {
                                labels: {
                                    color: '#ffffff' 
                                }
                            }
                        }
                    }
                }
            );
        } else {
            
    /* =========== Create individual charts as before - Sales per Day Chart =========== */
                
            new Chart(
                document.getElementById('salesPerDayChart'),
                {
                    type: 'bar',
                    data: {
                        labels: data.labels,
                        datasets: [{
                            label: 'Sales per Day',
                            data: data.sales_per_day,
                            backgroundColor: 'rgba(54, 162, 235, 0.5)',
                            borderColor: 'rgba(54, 162, 235, 1)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            title: {
                                display: true,
                                text: 'Sales per Day - ' + data.range_label,
                                color: '#ffffff'
                            },
                            legend: {
                                labels: {
                                    color: '#ffffff'
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: 'Number of Orders',
                                    color: '#ffffff'
                                },
                                ticks: {
                                    color: '#ffffff' 
                                },
                                grid: {
                                    color: '#333333' 
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: data.range_type === 'month' ? 'Day of Month' : 'Month',
                                    color: '#ffffff'
                                },
                                ticks: {
                                    color: '#ffffff' 
                                },
                                grid: {
                                    color: '#333333' 
                                }
                            }
                        }
                    }
                }
            );
            
    /* =========== Revenue per Day Chart =========== */
      
            new Chart(
                document.getElementById('revenuePerDayChart'),
                {
                    type: 'bar',
                    data: {
                        labels: data.labels,
                        datasets: [{
                            label: 'Revenue per Day',
                            data: data.revenue_per_day,
                            backgroundColor: 'rgba(75, 192, 192, 0.5)',
                            borderColor: 'rgba(75, 192, 192, 1)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            title: {
                                display: true,
                                text: 'Revenue per Day - ' + data.range_label,
                                color: '#ffffff'
                            },
                            legend: {
                                labels: {
                                    color: '#ffffff'
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: 'Revenue',
                                    color: '#ffffff'
                                },
                                ticks: {
                                    color: '#ffffff' 
                                },
                                grid: {
                                    color: '#333333' 
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: data.range_type === 'month' ? 'Day of Month' : 'Month',
                                    color: '#ffffff'
                                },
                                ticks: {
                                    color: '#ffffff' 
                                },
                                grid: {
                                    color: '#333333' 
                                }
                            }
                        }
                    }
                }
            );
            
    /* =========== Cumulative Revenue Chart =========== */
     
            new Chart(
                document.getElementById('cumulativeRevenueChart'),
                {
                    type: 'line',
                    data: {
                        labels: data.labels,
                        datasets: [{
                            label: 'Cumulative Revenue',
                            data: data.cumulative_revenue,
                            fill: true,
                            backgroundColor: 'rgba(153, 102, 255, 0.2)',
                            borderColor: 'rgba(153, 102, 255, 1)',
                            tension: 0.1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            title: {
                                display: true,
                                text: 'Cumulative Revenue - ' + data.range_label,
                                color: '#ffffff'
                            },
                            legend: {
                                labels: {
                                    color: '#ffffff' 
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: 'Total Revenue',
                                    color: '#ffffff'
                                },
                                ticks: {
                                    color: '#ffffff' 
                                },
                                grid: {
                                    color: '#333333' 
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: data.range_type === 'month' ? 'Day of Month' : 'Month',
                                    color: '#ffffff'
                                },
                                ticks: {
                                    color: '#ffffff' 
                                },
                                grid: {
                                    color: '#333333' 
                                }
                            }
                        }
                    }
                }
            );
            
    /* =========== Average Order Value Chart =========== */
     
            new Chart(
                document.getElementById('aovChart'),
                {
                    type: 'line',
                    data: {
                        labels: data.labels,
                        datasets: [{
                            label: 'Average Order Value',
                            data: data.aov_per_day,
                            fill: false,
                            borderColor: 'rgba(255, 159, 64, 1)',
                            tension: 0.1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            title: {
                                display: true,
                                text: 'Average Order Value - ' + data.range_label,
                                color: '#ffffff'
                            },
                            legend: {
                                labels: {
                                    color: '#ffffff' 
                                }
                            }

                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: 'AOV',
                                    color: '#ffffff'
                                },
                                ticks: {
                                    color: '#ffffff' 
                                },
                                grid: {
                                    color: '#333333' 
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: data.range_type === 'month' ? 'Day of Month' : 'Month',
                                    color: '#ffffff'
                                },
                                ticks: {
                                    color: '#ffffff' 
                                },
                                grid: {
                                    color: '#333333' 
                                }
                            }
                        }
                    }
                }
            );
            
    /* =========== Average Items per Order Chart =========== */
              
            new Chart(
                document.getElementById('itemsPerOrderChart'),
                {
                    type: 'line',
                    data: {
                        labels: data.labels,
                        datasets: [{
                            label: 'Average Items per Order',
                            data: data.items_per_order,
                            fill: false,
                            borderColor: 'rgba(255, 99, 132, 1)',
                            tension: 0.1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            title: {
                                display: true,
                                text: 'Average Items per Order - ' + data.range_label,
                                color: '#ffffff'
                            },
                            legend: {
                                labels: {
                                    color: '#ffffff' 
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: 'Items per Order',
                                    color: '#ffffff'
                                },
                                ticks: {
                                    color: '#ffffff' 
                                },
                                grid: {
                                    color: '#333333' 
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: data.range_type === 'month' ? 'Day of Month' : 'Month',
                                    color: '#ffffff'
                                },
                                ticks: {
                                    color: '#ffffff' 
                                },
                                grid: {
                                    color: '#333333' 
                                }
                            }
                        }
                    }
                }
            );
        }
        
    /* =========== Sales by Category Chart (always shown) =========== */
           
        const ctx = document.getElementById('salesByCategoryChart');
        ctx.style.height = 'auto';
        
        const cleanLabels = (data?.category_labels ?? []).map(label => 
            typeof label === 'string' ? label.replace(/&amp;/g, '&') : String(label)
        );
        
        const lighterColors = data.category_colors.map(color => BlueRaven_lightenColor(color, 20)); // Lighten by 20%
        
        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: cleanLabels,
                datasets: [{
                    label: 'Sales by Category',
                    data: data.category_sales,
                    backgroundColor: lighterColors,
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'right',
                        labels: {
                            color: '#ffffff'
                        }
                    },
                    title: {
                        display: true,
                        text: 'Sales Distribution by Category - ' + data.range_label,
                        color: '#ffffff'
                    },
                }
            }
        });
        
        function BlueRaven_lightenColor(hex, percent) {
            const num = parseInt(hex.replace('#', ''), 16),
                  amt = Math.round(2.55 * percent),
                  R = (num >> 16) + amt,
                  G = (num >> 8 & 0x00FF) + amt,
                  B = (num & 0x0000FF) + amt;
        
            return '#' + (
                0x1000000 +
                (R < 255 ? (R < 1 ? 0 : R) : 255) * 0x10000 +
                (G < 255 ? (G < 1 ? 0 : G) : 255) * 0x100 +
                (B < 255 ? (B < 1 ? 0 : B) : 255)
            ).toString(16).slice(1);
        }
    }
})(jQuery);