<?php
if (!defined('ABSPATH')) exit;

class VS_Commission {

    public static function init() {
        // Calculate and store commission when order is created
        add_action('woocommerce_checkout_create_order_line_item', [__CLASS__, 'calculate_commission'], 100, 4);
        
        // Also recalculate if order is saved manually in admin (optional but good for testing)
        // add_action('woocommerce_before_save_order_item', ...); 
    }

    /**
     * Calculates commission for a line item and saves it as metadata.
     * This ensures the commission rate is locked in at the time of purchase.
     */
    public static function calculate_commission($item, $cart_item_key, $values, $order) {
        $product = $item->get_product();
        
        if (!$product) return;

        $vendor_id = get_post_field('post_author', $product->get_id());
        
        // 1. Per-vendor override, 2. Global rate from woocommerce_vs_commission_rate (single source of truth)
        $vendor_rate = get_user_meta($vendor_id, 'vs_vendor_commission_rate', true);
        $rate        = ($vendor_rate !== '') ? (float) $vendor_rate
                                            : (float) get_option('woocommerce_vs_commission_rate', 10);

        $commission_type = (string) get_option('woocommerce_vs_commission_type', 'percentage');

        $line_total = (float) $item->get_total();

        if ($commission_type === 'fixed') {
            $commission_amount = $rate;
        } elseif ($commission_type === 'hybrid') {
            $fixed_fee         = (float) get_option('woocommerce_vs_commission_fixed', 0);
            $commission_amount = ($line_total * $rate / 100) + $fixed_fee;
        } else {
            // percentage (default)
            $commission_amount = ($line_total * $rate) / 100;
        }

        $vendor_earning = $line_total - $commission_amount;

        // Save metadata (underscore prefix hides from customer-facing order screen)
        $item->add_meta_data('_vs_vendor_id',               $vendor_id);
        $item->add_meta_data('_woocommerce_vs_commission_rate', $rate);
        $item->add_meta_data('_vs_commission_amount',        $commission_amount);
        $item->add_meta_data('_vs_vendor_earning',           $vendor_earning);
    }
    
    /**
     * Helper to get earnings for a specific order for a specific vendor
     */
    public static function get_order_earnings($order_id, $vendor_id) {
        $data = self::get_order_financials($order_id, $vendor_id);
        return $data['net_earning'];
    }

    /**
     * Recalculate commission for existing orders when settings change
     * This should be called when commission settings are updated
     */
    public static function recalculate_all_commissions() {
        global $wpdb;
        
        // Get all completed orders
        $order_ids = $wpdb->get_col("
            SELECT ID FROM {$wpdb->posts} 
            WHERE post_type = 'shop_order' 
            AND post_status = 'wc-completed'
        ");
        
        echo "Found " . count($order_ids) . " completed orders\n";
        
        foreach ($order_ids as $order_id) {
            echo "Recalculating order $order_id\n";
            self::recalculate_order_commission($order_id);
        }
    }
    
    /**
     * Recalculate commission for a specific order
     */
    public static function recalculate_order_commission($order_id) {
        $order = wc_get_order($order_id);
        if (!$order) return;

        $commission_type = (string) get_option('woocommerce_vs_commission_type', 'percentage');

        foreach ($order->get_items() as $item) {
            $product = $item->get_product();
            if (!$product) continue;
            
            $vendor_id = get_post_field('post_author', $product->get_id());
            if (!$vendor_id) continue;
            
            // Per-vendor override → global woocommerce_vs_commission_rate
            $vendor_rate = get_user_meta($vendor_id, 'vs_vendor_commission_rate', true);
            $rate        = ($vendor_rate !== '') ? (float) $vendor_rate
                                                : (float) get_option('woocommerce_vs_commission_rate', 10);

            $line_total = (float) $item->get_total();

            if ($commission_type === 'fixed') {
                $commission_amount = $rate;
            } elseif ($commission_type === 'hybrid') {
                $fixed_fee         = (float) get_option('woocommerce_vs_commission_fixed', 0);
                $commission_amount = ($line_total * $rate / 100) + $fixed_fee;
            } else {
                $commission_amount = ($line_total * $rate) / 100;
            }

            $vendor_earning = $line_total - $commission_amount;
            
            // Update metadata
            $item->update_meta_data('_woocommerce_vs_commission_rate', $rate);
            $item->update_meta_data('_vs_commission_amount',            $commission_amount);
            $item->update_meta_data('_vs_vendor_earning',               $vendor_earning);
        }
        
        $order->save();
    }
    
    /**
     * Get full financial breakdown for a specific order and vendor
     */
    public static function get_order_financials($order_id, $vendor_id) {
        $order = wc_get_order($order_id);
        $result = [
            'gross_sales' => 0,
            'commission'  => 0,
            'net_earning' => 0
        ];

        if(!$order) return $result;
        
        foreach($order->get_items() as $item) {
            $item_vendor = $item->get_meta('_vs_vendor_id');
            if (empty($item_vendor)) {
                $product = $item->get_product();
                if ($product) {
                    $item_vendor = get_post_field('post_author', $product->get_id());
                }
            }

            if($item_vendor == $vendor_id) {
                $line_total = (float) $item->get_total();
                $result['gross_sales'] += $line_total;

                // Check for saved commission first
                $saved_commission = $item->get_meta('_vs_commission_amount');
$saved_earning    = $item->get_meta('_vs_vendor_earning');

if ($saved_commission !== '') {
    $result['commission'] += (float) $saved_commission;
    $result['net_earning'] += (float) $saved_earning;
} else {
                    // Fallback: calculate using woocommerce_vs_commission_rate (single source of truth)
                    $vendor_rate     = get_user_meta($vendor_id, 'vs_vendor_commission_rate', true);
                    $rate            = ($vendor_rate !== '') ? (float) $vendor_rate
                                                            : (float) get_option('woocommerce_vs_commission_rate', 20);
                    $commission_type = (string) get_option('woocommerce_vs_commission_type', 'percentage');

                    if ($commission_type === 'fixed') {
                        $commission = $rate;
                    } elseif ($commission_type === 'hybrid') {
                        $fixed_fee  = (float) get_option('woocommerce_vs_commission_fixed', 20);
                        $commission = ($line_total * $rate / 100) + $fixed_fee;
                    } else {
                        $commission = ($line_total * (float) $rate) / 100;
                    }

                    $result['net_earning'] += ($line_total - $commission);
                    $result['commission']  += $commission;
                }
            }
        }
        return $result;
    }
}