<?php

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

class ShopCentral_Advanced_Analytics
{
    private $namespace;

    public function __construct($namespace = 'shopcentral/v1')
    {
        $this->namespace = $namespace;
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    public function register_routes()
    {
        register_rest_route($this->namespace, '/api/store-manager/advanced-analytics', [
            'methods' => WP_REST_Server::READABLE,
            'callback' => [$this, 'get_advanced_analytics'],
            'permission_callback' => [$this, 'check_permission'],
        ]);
    }

    public function check_permission()
    {
        return current_user_can('manage_options');
    }

    public function get_advanced_analytics($request)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'shopcentral_stores';
        $stores = $wpdb->get_results("SELECT * FROM $table");

        $store_api = new ShopCentral_Store_API($this->namespace);
        
        $after = $request->get_param('after');
        $before = $request->get_param('before');
        $date_params = [];
        if ($after) $date_params['after'] = $after;
        if ($before) $date_params['before'] = $before;

        $analytics = [];
        $top_products = [];
        $revenue_trends = [];
        $network_countries = [];
        
        $total_network_revenue = 0;
        $total_network_orders = 0;

        foreach ($stores as $store) {
            $currency_symbol = '$';
            $store_revenue = 0;
            $store_orders = 0;
            $store_refunds = 0;
            $store_customers = 0;
            $store_taxes = 0;
            $trends = [];
            $top_sellers = [];

            if ($store_api->is_store_local($store)) {
                // Local Store Native WooCommerce Call (Bypass REST 401 issue)
                $currency_symbol = get_woocommerce_currency_symbol() ?: '$';
                $currency_symbol = html_entity_decode($currency_symbol, ENT_QUOTES | ENT_HTML5, 'UTF-8');

                // Determine Date ranges based on period or custom range
                $date_args = [];
                if ($after || $before) {
                    if ($after) $date_args['date_after'] = date('Y-m-d', strtotime($after));
                    if ($before) $date_args['date_before'] = date('Y-m-d', strtotime($before));
                } else {
                    if ($period === 'week') $date_args = ['date_after' => date('Y-m-d', strtotime('-7 days'))];
                    if ($period === 'month') $date_args = ['date_after' => date('Y-m-01'), 'date_before' => date('Y-m-t')];
                    if ($period === 'last_month') $date_args = ['date_after' => date('Y-m-01', strtotime('last month')), 'date_before' => date('Y-m-t', strtotime('last month'))];
                    if ($period === 'year') $date_args = ['date_after' => date('Y-01-01'), 'date_before' => date('Y-12-31')];
                }

                $orders = wc_get_orders(array_merge([
                    'limit' => -1,
                    'status' => ['wc-completed', 'wc-processing', 'wc-on-hold', 'wc-refunded']
                ], $date_args));

                $unique_customers = [];
                $product_stats = []; // [ pid => [qty, revenue, orders] ]
                foreach ($orders as $order) {
                    $date = $order->get_date_created()->date('Y-m-d');
                    if (!isset($trends[$date])) {
                        $trends[$date] = 0.0;
                    }
                    $order_total = (float)$order->get_total();
                    $trends[$date] += $order_total;
                    $store_revenue += $order_total;
                    $store_taxes += (float)$order->get_total_tax();
                    $store_orders++;
                    if ($order->get_status() === 'refunded') {
                        $store_refunds += $order_total;
                    }
                    if (is_callable([$order, 'get_billing_email'])) {
                        $unique_customers[$order->get_billing_email()] = true;
                    }
                    if (is_callable([$order, 'get_billing_country'])) {
                        $country = $order->get_billing_country() ?: 'Unknown';
                        $network_countries[$country] = ($network_countries[$country] ?? 0) + $order_total;
                    }

                    $order_pids = [];
                    foreach ($order->get_items() as $item) {
                        if ($item instanceof WC_Order_Item_Product) {
                            $pid = $item->get_product_id();
                            $qty = $item->get_quantity();
                            $total = (float)$item->get_total();
                            
                            if (!isset($product_stats[$pid])) {
                                $product_stats[$pid] = ['qty' => 0, 'revenue' => 0, 'orders' => 0];
                            }
                            $product_stats[$pid]['qty'] += $qty;
                            $product_stats[$pid]['revenue'] += $total;
                            if (!isset($order_pids[$pid])) {
                                $product_stats[$pid]['orders']++;
                                $order_pids[$pid] = true;
                            }
                        }
                    }
                }
                $store_customers = count($unique_customers);

                // Sort by quantity
                uasort($product_stats, function($a, $b) { return $b['qty'] <=> $a['qty']; });
                $ts_slice = array_slice($product_stats, 0, 10, true);
                foreach($ts_slice as $pid => $stats) {
                    $p = wc_get_product($pid);
                    if ($p) {
                        $image_id = $p->get_image_id();
                        $image_url = wp_get_attachment_image_url($image_id, 'thumbnail') ?: '';
                        $top_sellers[] = (object)[
                            'product_id' => $pid,
                            'name' => $p->get_name(),
                            'quantity' => $stats['qty'],
                            'revenue' => $stats['revenue'],
                            'orders' => $stats['orders'],
                            'image' => $image_url
                        ];
                    }
                }

            } else {
                // Remote Store Logic
                try {
                    $status = $store_api->get_remote_wc_data($store, 'wc/v3/system_status');
                    if (is_array($status) && isset($status['settings'])) {
                         $currency_symbol = html_entity_decode($status['settings']['currency_symbol'] ?? '$', ENT_QUOTES | ENT_HTML5, 'UTF-8');
                    }
                } catch (Exception $e) {}

                $sales_params = [];
                if ($after && $before) {
                    $sales_params['date_min'] = date('Y-m-d', strtotime($after));
                    $sales_params['date_max'] = date('Y-m-d', strtotime($before));
                }

                $sales_report = $store_api->get_remote_wc_data($store, 'wc/v3/reports/sales', $sales_params);
                
                if (is_array($sales_report) && !empty($sales_report) && !isset($sales_report['code'])) {
                    foreach ($sales_report as $req) {
                        if (isset($req['code'])) continue;
                        $store_revenue += (float) ($req['total_sales'] ?? 0);
                        $store_taxes += (float) ($req['total_tax'] ?? 0);
                        $store_orders += (int) ($req['total_orders'] ?? 0);
                        $store_refunds += (float) ($req['total_refunds'] ?? 0);
                        $store_customers += (int) ($req['total_customers'] ?? 0);
                        
                        if (isset($req['totals']) && is_array($req['totals'])) {
                            foreach ($req['totals'] as $date => $day_data) {
                                $trends[$date] = (float)($day_data['sales'] ?? 0);
                            }
                        }
                    }
                }

                // If revenue/orders still 0, try manual calculation from orders
                if ($store_revenue <= 0 || $store_orders <= 0) {
                    $order_params = ['status' => 'completed,processing,on-hold'];
                    if ($after) $order_params['after'] = $after;
                    if ($before) $order_params['before'] = $before;
                    
                    $real_order_count = $store_api->get_remote_wc_count($store, 'wc/v3/orders', $order_params);
                    if ($real_order_count > 0) {
                        $store_orders = $real_order_count;
                        if ($store_revenue <= 0) {
                            $orders = $store_api->get_remote_wc_data($store, 'wc/v3/orders', array_merge($order_params, ['per_page' => 50]));
                            if (is_array($orders) && !isset($orders['code'])) {
                                foreach ($orders as $o) {
                                    $store_revenue += (float)($o['total'] ?? 0);
                                    $store_taxes += (float)($o['total_tax'] ?? 0);
                                    // Trends calculation from manual fetch
                                    if (isset($o['date_created'])) {
                                        $d = date('Y-m-d', strtotime($o['date_created']));
                                        $trends[$d] = ($trends[$d] ?? 0) + (float)($o['total'] ?? 0);
                                    }
                                }
                            }
                        }
                    }
                }

                // Try to use analytics API for better top sellers data
                $date_args = [];
                if ($after || $before) {
                    if ($after) $date_args['after'] = date('Y-m-d\TH:i:s', strtotime($after));
                    if ($before) $date_args['before'] = date('Y-m-d\TH:i:s', strtotime($before));
                }

                $analytics_ts = $store_api->get_remote_wc_data($store, 'wc-analytics/products', array_merge(['per_page' => 10, 'orderby' => 'items_sold', 'order' => 'desc'], $date_args));
                
                if (is_array($analytics_ts) && !isset($analytics_ts['code']) && !empty($analytics_ts)) {
                    foreach ($analytics_ts as $ats) {
                        if (isset($ats['code'])) continue;
                        // Fetch individual product details for image
                        $p_id = $ats['product_id'];
                        $p_info = $store_api->get_remote_wc_data($store, "wc/v3/products/{$p_id}");
                        $top_sellers[] = (object)[
                            'product_id' => $p_id,
                            'name' => $p_info['name'] ?? 'Product #'.$p_id,
                            'quantity' => $ats['items_sold'],
                            'revenue' => (float)($ats['net_revenue'] ?? 0),
                            'orders' => $ats['orders_count'] ?? 0,
                            'image' => (isset($p_info['images']) && is_array($p_info['images']) && !empty($p_info['images'])) ? $p_info['images'][0]['src'] : ''
                        ];
                    }
                } else {
                    // Fallback to legacy reports
                    $remote_ts = $store_api->get_remote_wc_data($store, 'wc/v3/reports/top_sellers', ['per_page' => 10]);
                    if (is_array($remote_ts) && !isset($remote_ts['code'])) {
                        $product_ids = array_map(function($ts) { return $ts['product_id'] ?? 0; }, $remote_ts);
                        if (!empty($product_ids)) {
                            $remote_products = $store_api->get_remote_wc_data($store, 'wc/v3/products', ['include' => implode(',', $product_ids), 'per_page' => 10]);
                            $image_map = [];
                            if (is_array($remote_products)) {
                                foreach ($remote_products as $rp) { 
                                    if (isset($rp['id'])) {
                                        $image_map[$rp['id']] = (isset($rp['images']) && is_array($rp['images']) && !empty($rp['images'])) ? $rp['images'][0]['src'] : ''; 
                                    }
                                }
                            }
                            foreach ($remote_ts as $ts) {
                                if (!isset($ts['product_id'])) continue;
                                $top_sellers[] = (object)[
                                    'product_id' => $ts['product_id'],
                                    'name' => $ts['name'] ?? 'Unknown',
                                    'quantity' => $ts['quantity'] ?? 0,
                                    'revenue' => 0, // Legacy API doesn't provide this easily
                                    'orders' => 0,
                                    'image' => $image_map[$ts['product_id']] ?? ''
                                ];
                            }
                        }
                    }
                }
                
                // Sample Remote Countries from recent orders
                $remote_orders = $store_api->get_remote_wc_data($store, 'wc/v3/orders', array_merge(['status' => 'completed', 'per_page' => 100], $date_params));
                if (is_array($remote_orders) && !isset($remote_orders['code'])) {
                    foreach ($remote_orders as $ro) {
                        if (isset($ro['code'])) continue;
                        $country = $ro['billing']['country'] ?? 'Unknown';
                        if (empty($country)) $country = 'Unknown';
                        $network_countries[$country] = ($network_countries[$country] ?? 0) + (float)($ro['total'] ?? 0);
                    }
                }
            }
            
            $aov = $store_orders > 0 ? $store_revenue / $store_orders : 0;
            $refund_rate = $store_revenue > 0 ? ($store_refunds / $store_revenue) * 100 : 0;
            
            // returning customers % 
            $returning_pct = 0;
            if ($store_orders > 0 && $store_customers > 0) {
                 $returning_pct = max(0, ((1 - ($store_customers / $store_orders)) * 100));
            }
            
            // Store leaderboard stats
            $analytics[] = [
                'store_id' => $store->id,
                'store_name' => $store->name,
                'revenue' => $store_revenue,
                'orders' => $store_orders,
                'taxes' => $store_taxes,
                'aov' => $aov,
                'refund_rate' => $refund_rate,
                'returning_pct' => $returning_pct,
                'currency' => $currency_symbol
            ];

            // Revenue trends for stacked chart
            $revenue_trends[$store->name] = $trends;
            
            $total_network_revenue += $store_revenue;
            $total_network_orders += $store_orders;
            
            // Product Performance (Top sellers)
            if (is_array($top_sellers)) {
                foreach($top_sellers as $ts) {
                    $top_products[] = [
                        'store_name' => $store->name,
                        'product_id' => $ts->product_id ?? 0,
                        'name' => $ts->name ?? 'Product #'.($ts->product_id ?? 0),
                        'quantity' => (int)($ts->quantity ?? 0),
                        'revenue' => (float)($ts->revenue ?? 0),
                        'orders' => (int)($ts->orders ?? 0),
                        'image' => $ts->image ?? '',
                        'currency' => $currency_symbol
                    ];
                }
            }
        }
        
        // Sort analytics for leaderboard
        usort($analytics, function($a, $b) {
            return $b['revenue'] <=> $a['revenue'];
        });
        
        // Sort top products globally
        usort($top_products, function($a, $b) {
            return $b['quantity'] <=> $a['quantity'];
        });

        // Format dates for charts (Extract all unique dates)
        $all_dates = [];
        foreach($revenue_trends as $store_name => $trends) {
            foreach(array_keys($trends) as $date) {
                if(!in_array($date, $all_dates)) $all_dates[] = $date;
            }
        }
        sort($all_dates);
        
        // Format series for ApexCharts [ {name: 'Store A', data: [10, 20...]}, ... ]
        $chart_series = [];
        foreach($stores as $store) {
            $data = [];
            foreach($all_dates as $date) {
                $data[] = $revenue_trends[$store->name][$date] ?? 0;
            }
            $chart_series[] = [
                'name' => $store->name,
                'data' => $data
            ];
        }

        // Sort countries formatting
        arsort($network_countries);
        
        $wc_countries = (function_exists('WC') && isset(WC()->countries)) ? WC()->countries->get_countries() : [];
        $country_labels = [];
        foreach (array_keys($network_countries) as $code) {
            $country_labels[] = isset($wc_countries[$code]) ? $wc_countries[$code] : $code;
        }
        
        $country_series = array_values($network_countries);

        return new WP_REST_Response([
            'status' => 'success',
            'data' => [
                'leaderboard' => $analytics,
                'chart_series' => $chart_series,
                'chart_categories' => $all_dates,
                'country_labels' => $country_labels,
                'country_series' => $country_series,
                'top_products' => array_slice($top_products, 0, 10),
                'network_total' => $total_network_revenue
            ]
        ], 200);
    }
}
