<?php

defined('ABSPATH') || exit;

class BundlePress_Analytics_Handler
{
    private $namespace;

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

        // Track views on frontend
        add_action('wp_ajax_bundlepress_track_view', [$this, 'ajax_track_view']);
        add_action('wp_ajax_nopriv_bundlepress_track_view', [$this, 'ajax_track_view']);

        // Record sales to dedicated table
        add_action('woocommerce_order_status_completed', [$this, 'record_bundle_sales']);
        add_action('woocommerce_order_status_processing', [$this, 'record_bundle_sales']);
    }

    public function register_routes()
    {
        register_rest_route($this->namespace, '/analytics/stats', [
            'methods' => 'GET',
            'callback' => [$this, 'get_stats'],
            'permission_callback' => [$this, 'check_permission']
        ]);

        register_rest_route($this->namespace, '/analytics/track', [
            'methods' => 'POST',
            'callback' => [$this, 'track_event'],
            'permission_callback' => [$this, 'public_permission_check']
        ]);
    }

    public function public_permission_check()
    {
        return true;
    }

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

    /**
     * Track a view or click via AJAX/REST
     */
    public function ajax_track_view()
    {
        $bundle_id = isset($_POST['bundle_id']) ? absint($_POST['bundle_id']) : 0;
        if ($bundle_id) {
            $this->log_event('view', $bundle_id);
        }
        wp_send_json_success();
    }

    public function track_event($request)
    {
        $params = $request->get_json_params();
        $type = $params['type'] ?? 'view';
        $bundle_id = absint($params['bundle_id'] ?? 0);

        if ($bundle_id) {
            $this->log_event($type, $bundle_id);
        }

        return rest_ensure_response(['success' => true]);
    }

    private function log_event($type, $bundle_id)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'bundlepress_analytics';

        $wpdb->insert($table, [
            'event_type' => $type,
            'bundle_id' => $bundle_id,
            'created_at' => current_time('mysql'),
        ]);
    }

    /**
     * Record actual sales data to a dedicated table for reliable analytics
     */
    public function record_bundle_sales($order_id)
    {
        global $wpdb;
        $order = wc_get_order($order_id);
        if (!$order) return;

        // Check if already recorded to prevent duplicates
        $recorded = $wpdb->get_var($wpdb->prepare("SELECT id FROM {$wpdb->prefix}bundlepress_sales WHERE order_id = %d LIMIT 1", $order_id));
        if ($recorded) return;

        foreach ($order->get_items() as $item) {
            $bundle_id = $item->get_meta('_bundlepress_bundle');
            $parent_bundle_id = $item->get_meta('_bundlepress_parent'); // If numeric ID
            
            // Mix & Match children might use _bundlepress_parent as the ID
            $id_to_track = $bundle_id ?: $parent_bundle_id;
            
            if ($id_to_track && is_numeric($id_to_track)) {
                $wpdb->insert($wpdb->prefix . 'bundlepress_sales', [
                    'order_id'   => $order_id,
                    'bundle_id'  => absint($id_to_track),
                    'product_id' => $item->get_product_id(),
                    'quantity'   => $item->get_quantity(),
                    'revenue'    => $item->get_total(),
                    'discount'   => (float) $item->get_meta('_bundlepress_discount'),
                    'created_at' => $order->get_date_created()->date('Y-m-d H:i:s'),
                ]);
            }
        }
    }

    public function get_stats($request)
    {
        global $wpdb;

        $bundle_id = $request->get_param('bundle_id');
        $start_date = $request->get_param('startDate');
        $end_date = $request->get_param('endDate');

        $sales_table = $wpdb->prefix . 'bundlepress_sales';
        $analytics_table = $wpdb->prefix . 'bundlepress_analytics';

        $date_where = "1=1";
        $a_date_where = "1=1";
        if ($start_date && $end_date) {
            $date_where = $wpdb->prepare("created_at >= %s AND created_at <= %s", $start_date . ' 00:00:00', $end_date . ' 23:59:59');
            $a_date_where = $wpdb->prepare("created_at >= %s AND created_at <= %s", $start_date . ' 00:00:00', $end_date . ' 23:59:59');
        }

        $b_where = $bundle_id ? $wpdb->prepare("AND bundle_id = %d", $bundle_id) : "";

        // 1. Core Metrics from Sales Table
        $sales_data = $wpdb->get_row("
            SELECT 
                COUNT(DISTINCT order_id) as total_orders,
                SUM(revenue) as total_revenue,
                SUM(quantity) as total_units,
                SUM(discount) as total_discount
            FROM $sales_table 
            WHERE $date_where $b_where
        ");

        // Fallback or override for better accuracy: use live meta for total_revenue if bundle_id is set
        if ($bundle_id) {
            $live_rev = $wpdb->get_var($wpdb->prepare(
                "SELECT SUM(CAST(meta_v.meta_value AS DECIMAL(19,4))) 
                 FROM {$wpdb->prefix}woocommerce_order_itemmeta AS meta_k
                 JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS meta_v ON meta_k.order_item_id = meta_v.order_item_id
                 WHERE meta_k.meta_key = '_bundlepress_bundle' 
                 AND meta_k.meta_value = %d
                 AND meta_v.meta_key = '_line_total'",
                $bundle_id
            ));
            
            $live_orders = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(DISTINCT oi.order_id)
                 FROM {$wpdb->prefix}woocommerce_order_items AS oi
                 JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS oim ON oi.order_item_id = oim.order_item_id
                 WHERE oim.meta_key = '_bundlepress_bundle' 
                 AND oim.meta_value = %d",
                $bundle_id
            ));
            
            $total_bundle_revenue = (float)($live_rev ?? 0);
            $total_bundle_orders = (int)($live_orders ?? 0);
        } else {
            $total_bundle_orders = (int) $sales_data->total_orders;
            $total_bundle_revenue = (float) $sales_data->total_revenue;
        }

        $total_bundles_sold = (int) $sales_data->total_units;
        $total_discount = (float) $sales_data->total_discount;

        $avg_bundle_order_value = $total_bundle_orders > 0 ? $total_bundle_revenue / $total_bundle_orders : 0;

        // 2. Engagement from Analytics Table
        $views = (int) $wpdb->get_var("SELECT COUNT(*) FROM $analytics_table WHERE event_type = 'view' AND $a_date_where $b_where");
        $carts = (int) $wpdb->get_var("SELECT COUNT(*) FROM $analytics_table WHERE event_type = 'add_to_cart' AND $a_date_where $b_where");
        $clicks = (int) $wpdb->get_var("SELECT COUNT(*) FROM $analytics_table WHERE event_type = 'click' AND $a_date_where $b_where");

        $conversion_rate = $views > 0 ? ($total_bundle_orders / $views) * 100 : 0;
        $click_rate = $views > 0 ? ($clicks / $views) * 100 : 0;

        // 3. AOV Comparison
        $normal_aov = 52.00;
        $aov_increase = 0;
        if (!$bundle_id) {
            // Find orders in this date range that are NOT in our bundle sales table
            $all_range_ids = wc_get_orders(['limit' => -1, 'return' => 'ids', 'status' => ['processing', 'completed'], 'date_created' => $start_date . '...' . $end_date]);
            $bundle_range_ids = $wpdb->get_col("SELECT DISTINCT order_id FROM $sales_table WHERE $date_where");
            $normal_ids = array_diff($all_range_ids, $bundle_range_ids);
            
            if (!empty($normal_ids)) {
                $normal_rev = 0;
                foreach ($normal_ids as $nid) {
                    $no = wc_get_order($nid);
                    if ($no) $normal_rev += (float) $no->get_total();
                }
                $normal_aov = $normal_rev / count($normal_ids);
            }
            $aov_increase = $normal_aov > 0 ? (($avg_bundle_order_value - $normal_aov) / $normal_aov) * 100 : 0;
        }

        // 4. Performance Lists
        $top_bundles = [];
        $internal_products = [];
        $top_products = [];

        if (!$bundle_id) {
            // Global top bundles
            $top_b_raw = $wpdb->get_results("
                SELECT bundle_id, COUNT(DISTINCT order_id) as b_orders, SUM(revenue) as b_rev 
                FROM $sales_table WHERE $date_where 
                GROUP BY bundle_id ORDER BY b_orders DESC LIMIT 5
            ");
            foreach ($top_b_raw as $row) {
                $b_data = BundlePress_DB::get_bundle_data($row->bundle_id);
                $top_bundles[] = [
                    'name' => $b_data ? $b_data['name'] : 'Deleted Bundle',
                    'orders' => (int) $row->b_orders,
                    'revenue' => (float) $row->b_rev,
                ];
            }

            // Global top products sold via bundles
            $top_p_raw = $wpdb->get_results("
                SELECT product_id, SUM(quantity) as p_sales 
                FROM $sales_table WHERE $date_where
                GROUP BY product_id ORDER BY p_sales DESC LIMIT 5
            ");
            foreach ($top_p_raw as $row) {
                $top_products[] = [
                    'name' => get_the_title($row->product_id) ?: 'Unknown Product',
                    'sales' => (int) $row->p_sales
                ];
            }
        } else {
            // Product performance inside THIS bundle
            $int_raw = $wpdb->get_results($wpdb->prepare("
                SELECT product_id, SUM(quantity) as p_sales 
                FROM $sales_table WHERE $date_where AND bundle_id = %d
                GROUP BY product_id ORDER BY p_sales DESC
            ", $bundle_id));
            foreach ($int_raw as $row) {
                $internal_products[] = [
                    'name' => get_the_title($row->product_id) ?: 'Deleted Product',
                    'bundle_sales' => (int) $row->p_sales
                ];
            }
        }

        // 5. Trend Chart
        $dates = [];
        $revenue_trend = [];
        $orders_trend = [];
        $conversion_trend = [];

        $trend_days = 30;
        $trend_start = strtotime("-29 days");
        if ($start_date && $end_date) {
            $trend_start = strtotime($start_date);
            $trend_end = strtotime($end_date);
            $trend_days = ceil(($trend_end - $trend_start) / 86400) + 1;
        }

        $trend_data_raw = $wpdb->get_results("
            SELECT DATE(created_at) as d, COUNT(DISTINCT order_id) as o_count, SUM(revenue) as r_sum
            FROM $sales_table WHERE $date_where $b_where
            GROUP BY DATE(created_at)
        ");
        $trend_map = [];
        foreach ($trend_data_raw as $row) { $trend_map[$row->d] = $row; }

        for ($i = 0; $i < $trend_days; $i++) {
            $curr = date('Y-m-d', strtotime("+$i days", $trend_start));
            $dates[] = date('M d', strtotime($curr));
            
            $day = $trend_map[$curr] ?? (object)['o_count' => 0, 'r_sum' => 0];
            $orders_trend[] = (int) $day->o_count;
            $revenue_trend[] = (float) $day->r_sum;

            $d_v = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $analytics_table WHERE event_type = 'view' $b_where AND DATE(created_at) = %s", $curr));
            $conversion_trend[] = $d_v > 0 ? round(($day->o_count / $d_v) * 100, 2) : 0;
        }

        return rest_ensure_response([
            'success' => true,
            'data' => [
                'bundle_name' => $bundle_id ? ($bundle = BundlePress_DB::get_bundle_data($bundle_id)) ? $bundle['name'] : 'Deleted Bundle' : 'Global Overview',
                'revenue' => [
                    'total_revenue' => $total_bundle_revenue,
                    'total_orders' => $total_bundle_orders,
                    'avg_aov' => $avg_bundle_order_value,
                    'units_sold' => $total_bundles_sold,
                ],
                'sales' => [
                    'total_sold' => $total_bundles_sold,
                    'conversion_rate' => $conversion_rate,
                ],
                'engagement' => [
                    'views' => $views,
                    'carts' => $carts,
                    'click_rate' => $click_rate,
                ],
                'impact' => $bundle_id ? [
                    'discount_given' => $total_discount,
                    'revenue_generated' => $total_bundle_revenue,
                ] : [
                    'normal_aov' => $normal_aov,
                    'bundle_aov' => $avg_bundle_order_value,
                    'increase_pct' => $aov_increase,
                ],
                'top_bundles' => $top_bundles,
                'top_products' => $top_products,
                'internal_products' => $internal_products,
                'funnel' => [
                    'views' => $views,
                    'carts' => $carts,
                    'orders' => $total_bundle_orders,
                ],
                'trends' => [
                    'dates' => $dates,
                    'revenue' => $revenue_trend,
                    'orders' => $orders_trend,
                    'conversion' => $conversion_trend,
                ],
                'currency' => trim(html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8')),
            ]
        ]);
    }

    private function return_empty_stats($bundle_id)
    {
        return rest_ensure_response([
            'success' => true,
            'data' => [
                'bundle_name' => $bundle_id ? ($bundle = BundlePress_DB::get_bundle_data($bundle_id)) ? $bundle['name'] : 'Deleted Bundle' : 'Global Overview',
                'revenue' => ['total_revenue' => 0, 'total_orders' => 0, 'avg_aov' => 0, 'units_sold' => 0],
                'sales' => ['total_sold' => 0, 'conversion_rate' => 0],
                'engagement' => ['views' => 0, 'carts' => 0, 'click_rate' => 0],
                'impact' => ['discount_given' => 0, 'revenue_generated' => 0, 'normal_aov' => 52, 'bundle_aov' => 0, 'increase_pct' => 0],
                'top_bundles' => [],
                'top_products' => [],
                'internal_products' => [],
                'funnel' => ['views' => 0, 'carts' => 0, 'orders' => 0],
                'trends' => ['dates' => [], 'revenue' => [], 'orders' => [], 'conversion' => []],
                'currency' => trim(html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8')),
            ]
        ]);
    }
}
