<?php
 
/**
 * =============================================================================
 * @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        Blue Raven Admin Tools and Tool Settings
 *
 * =============================================================================
 * 
 * || INDEX:
 * ||   - WP AJAX BLUE RAVEN ANALYTICS 
 * ||   - LOAD DATA
 * ||   
 * =============================================================================
 */

if ( ! defined( 'ABSPATH' ) ) exit; 

/*
============================================================
    WP AJAX BLUE RAVEN ANALYTICS BlueRaven_loadData
============================================================
*/

add_action('wp_ajax_blue_raven_sales_analytics', 'blue_raven_run_analytics');

function blue_raven_run_analytics() {
    
    ## =========== Security check =========== ##
    
    $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';

	if (!wp_verify_nonce($nonce, 'blue_raven_sales_analytics_nonce')) {
		BlueRaven_SendError("LOG", "blue-raven/includes/admin-home.php", "blue_raven_run_analytics", "Invalid nonce : " . wp_create_nonce('blue_raven_sales_analytics_nonce'));
		wp_send_json_error('Invalid nonce');
	}
    
    ## =========== Get Page =========== ##
     
    $subaction = sanitize_text_field(wp_unslash($_POST['subaction'] ?? ''));


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

    ## =========== Load data =========== ##
        
    if ($subaction === 'BlueRaven_loadData') {

        if (class_exists('WooCommerce')) { 

            $content = isset($_POST['content']) ? array_map('sanitize_text_field', wp_unslash($_POST['content'])) : [];
            $range = sanitize_text_field($content[0] ?? '');
            $month = sanitize_text_field($content[1] ?? '');
            
            $data = array();
            $range_label = '';
            $range_type = 'month'; 
            
            if ($range === 'current_month') {
                $current_month = gmdate('m');
                $current_year = gmdate('Y');
                $days_in_month = gmdate('t');
                $range_label = gmdate('F Y');
                $data = BlueRaven_get_monthly_data($current_year, $current_month, $days_in_month);
            }
            elseif ($range === 'custom_month') {
                list($year, $month_num) = explode('-', $month);
                $days_in_month = gmdate('t', strtotime($month . '-01'));
                $range_label = gmdate('F Y', strtotime($month . '-01'));
                $data = BlueRaven_get_monthly_data($year, $month_num, $days_in_month);
            }
            elseif ($range === 'last_12_months') {
                $range_type = 'year';
                $current_month = gmdate('m');
                $current_year = gmdate('Y');
                $range_label = 'Last 12 Months';
                
                $labels = array();
                $sales_per_day = array();
                $revenue_per_day = array();
                $cumulative_revenue = array();
                $aov_per_day = array();
                $items_per_order = array();
                $total_revenue = 0;
                
                for ($i = 11; $i >= 0; $i--) {
                    $date = gmdate('Y-m', strtotime("-$i months"));
                    $labels[] = gmdate('M Y', strtotime($date));
                    
                    $year = gmdate('Y', strtotime($date));
                    $month_num = gmdate('m', strtotime($date));
                    $days_in_month = gmdate('t', strtotime($date . '-01'));
                    
                    $start_date = $date . '-01';
                    $end_date = $date . '-' . $days_in_month;
                    
                    $args = array('date_created' => $start_date . '...' . $end_date,'limit' => -1,'return' => 'objects','status' => array('completed', 'processing'));
                    $orders = wc_get_orders($args);
                    $sales_count = count($orders);
                    $sales_per_day[] = $sales_count;
                    
                    $monthly_revenue = 0;
                    $total_items = 0;
                    
                    foreach ($orders as $order) {
                        $monthly_revenue += $order->get_total();
                        $total_items += $order->get_item_count();
                    }
                    
                    $revenue_per_day[] = $monthly_revenue;
                    $total_revenue += $monthly_revenue;
                    $cumulative_revenue[] = $total_revenue;
                    
                    $aov = ($sales_count > 0) ? $monthly_revenue / $sales_count : 0;
                    $aov_per_day[] = $aov;
                    
                    $avg_items = ($sales_count > 0) ? $total_items / $sales_count : 0;
                    $items_per_order[] = $avg_items;
                }
                
                $start_date = gmdate('Y-m-01', strtotime('-11 months'));
                $end_date = gmdate('Y-m-t');
                
                $categories = get_terms(array(
                    'taxonomy' => 'product_cat',
                    'hide_empty' => false
                ));
                
                $category_labels = array();
                $category_sales = array();
                $category_colors = array();
                
                foreach ($categories as $category) {
                    $args = array(
                        'status' => array('completed', 'processing'),
                        'date_created' => $start_date . '...' . $end_date,
                        'limit' => -1
                    );
                    
                    $orders = wc_get_orders($args);
                    $category_total = 0;
                    
                    foreach ($orders as $order) {
                        foreach ($order->get_items() as $item) {
                            $product_id = $item->get_product_id();
                            $product_categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));
                            if (in_array($category->term_id, $product_categories)) $category_total += $item->get_total();
                        }
                    }
                    
                    if ($category_total > 0) {
                        $category_labels[] = $category->name;
                        $category_sales[] = $category_total;
                        $category_colors[] = '#' . substr(md5($category->name), 0, 6);
                    }
                }
                
                $total_units = 0;
                foreach ($orders as $order) {$total_units += $order->get_item_count();}
                
                $data = array(
                    'labels' => $labels,
                    'sales_per_day' => $sales_per_day,
                    'revenue_per_day' => $revenue_per_day,
                    'cumulative_revenue' => $cumulative_revenue,
                    'aov_per_day' => $aov_per_day,
                    'items_per_order' => $items_per_order,
                    'category_labels' => $category_labels,
                    'category_sales' => $category_sales,
                    'category_colors' => $category_colors,
                    'total_units' => $total_units
                );
            }
            elseif ($range === 'year_to_date') {
                $range_type = 'year';
                $current_year = gmdate('Y');
                $current_month = gmdate('m');
                $range_label = 'Year to Date (' . $current_year . ')';
                
                $labels = array();
                $sales_per_day = array();
                $revenue_per_day = array();
                $cumulative_revenue = array();
                $aov_per_day = array();
                $items_per_order = array();
                $total_revenue = 0;
                
                for ($i = 1; $i <= $current_month; $i++) {
                    $month_num = str_pad($i, 2, '0', STR_PAD_LEFT);
                    $labels[] = gmdate('M', strtotime($current_year . '-' . $month_num . '-01'));
                    
                    $days_in_month = gmdate('t', strtotime($current_year . '-' . $month_num . '-01'));
                    $start_date = $current_year . '-' . $month_num . '-01';
                    $end_date = $current_year . '-' . $month_num . '-' . $days_in_month;
                    
                    $args = array(
                        'date_created' => $start_date . '...' . $end_date,
                        'limit' => -1,
                        'return' => 'objects',
                        'status' => array('completed', 'processing')
                    );
                    
                    $orders = wc_get_orders($args);
                    $sales_count = count($orders);
                    $sales_per_day[] = $sales_count;
                    
                    $monthly_revenue = 0;
                    $total_items = 0;
                    
                    foreach ($orders as $order) {
                        $monthly_revenue += $order->get_total();
                        $total_items += $order->get_item_count();
                    }
                    
                    $revenue_per_day[] = $monthly_revenue;
                    $total_revenue += $monthly_revenue;
                    $cumulative_revenue[] = $total_revenue;
                    
                    $aov = ($sales_count > 0) ? $monthly_revenue / $sales_count : 0;
                    $aov_per_day[] = $aov;
                    
                    $avg_items = ($sales_count > 0) ? $total_items / $sales_count : 0;
                    $items_per_order[] = $avg_items;
                }
                
                $start_date = $current_year . '-01-01';
                $end_date = $current_year . '-' . $current_month . '-' . gmdate('d');
                
                $categories = get_terms(array('taxonomy' => 'product_cat','hide_empty' => false));
                $category_labels = array();
                $category_sales = array();
                $category_colors = array();
                
                foreach ($categories as $category) {
                    $args = array(
                        'status' => array('completed', 'processing'),
                        'date_created' => $start_date . '...' . $end_date,
                        'limit' => -1
                    );
                    
                    $orders = wc_get_orders($args);
                    $category_total = 0;
                    
                    foreach ($orders as $order) {
                        foreach ($order->get_items() as $item) {
                            $product_id = $item->get_product_id();
                            $product_categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));
                            
                            if (in_array($category->term_id, $product_categories)) $category_total += $item->get_total();
                        }
                    }
                    
                    if ($category_total > 0) {
                        $category_labels[] = $category->name;
                        $category_sales[] = $category_total;
                        $category_colors[] = '#' . substr(md5($category->name), 0, 6);
                    }
                }
                
                $total_units = 0;
                foreach ($orders as $order) { $total_units += $order->get_item_count();}
                
                $data = array(
                    'labels' => $labels,
                    'sales_per_day' => $sales_per_day,
                    'revenue_per_day' => $revenue_per_day,
                    'cumulative_revenue' => $cumulative_revenue,
                    'aov_per_day' => $aov_per_day,
                    'items_per_order' => $items_per_order,
                    'category_labels' => $category_labels,
                    'category_sales' => $category_sales,
                    'category_colors' => $category_colors,
                    'total_units' => $total_units
                );
            }
            
            $data['range_label'] = $range_label;
            $data['range_type'] = $range_type;
            
            wp_send_json_success($data);
        }else{
            wp_send_json_success([]);
        }
    }
}

function BlueRaven_get_monthly_data($year, $month, $days_in_month) {
    
    $labels = array();
    $sales_per_day = array();
    $revenue_per_day = array();
    $cumulative_revenue = array();
    $aov_per_day = array();
    $items_per_order = array();

    $total_revenue = 0;
    
    for ($day = 1; $day <= $days_in_month; $day++) {
        $date = sprintf('%04d-%02d-%02d', $year, $month, $day);
        $labels[] = $day;
        
        $args = array(
            'date_created' => $date . '...' . $date,
            'limit' => -1,
            'return' => 'objects',
            'status' => array('completed', 'processing')
        );
        
        $orders = wc_get_orders($args);
        $sales_count = count($orders);
        $sales_per_day[] = $sales_count;
        
        $daily_revenue = 0;
        $total_items = 0;
        
        foreach ($orders as $order) {
            $daily_revenue += $order->get_total();
            $total_items += $order->get_item_count();
        }
        
        $revenue_per_day[] = $daily_revenue;
        $total_revenue += $daily_revenue;
        $cumulative_revenue[] = $total_revenue;
        
        $aov = ($sales_count > 0) ? $daily_revenue / $sales_count : 0;
        $aov_per_day[] = $aov;
        
        $avg_items = ($sales_count > 0) ? $total_items / $sales_count : 0;
        $items_per_order[] = $avg_items;
    }
    
    $categories = get_terms(array('taxonomy' => 'product_cat','hide_empty' => false));
    $category_labels = array();
    $category_sales = array();
    $category_colors = array();
    
    foreach ($categories as $category) {
        $args = array('status' => array('completed', 'processing'),'date_created' => $year . '-' . $month . '-01...' . $year . '-' . $month . '-' . $days_in_month,'limit' => -1);
        $orders = wc_get_orders($args);
        $category_total = 0;
        
        foreach ($orders as $order) {
            foreach ($order->get_items() as $item) {
                $product_id = $item->get_product_id();
                $product_categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));
                if (in_array($category->term_id, $product_categories)) $category_total += $item->get_total();
            }
        }
        
        if ($category_total > 0) {
            $category_labels[] = $category->name;
            $category_sales[] = $category_total;
            $category_colors[] = '#' . substr(md5($category->name), 0, 6);
        }
    }
    
    $total_units = 0;
    foreach ($orders as $order) {$total_units += $order->get_item_count();}
    
    return array(
        'labels' => $labels,
        'sales_per_day' => $sales_per_day,
        'revenue_per_day' => $revenue_per_day,
        'cumulative_revenue' => $cumulative_revenue,
        'aov_per_day' => $aov_per_day,
        'items_per_order' => $items_per_order,
        'category_labels' => $category_labels,
        'category_sales' => $category_sales,
        'category_colors' => $category_colors,
        'total_units' => $total_units
    );
}