<?php
/**
 * Plugin Compatibility Manager
 * KDS plugin'ini hem Orderable hem normal WooCommerce ile uyumlu yapar
 */

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

class KDSAMREF_Compatibility_Manager {
    
    private static $compatibility_mode = null;
    
    /**
     * Get current compatibility mode
     */
    public static function get_mode() {
        if (self::$compatibility_mode === null) {
            self::$compatibility_mode = self::detect_mode();
        }
        return self::$compatibility_mode;
    }
    
    /**
     * Reset compatibility mode cache
     */
    public static function reset_cache() {
        self::$compatibility_mode = null;
    }
    
    /**
     * Detect compatibility mode automatically
     */
    private static function detect_mode() {
        // Check user setting first
        $user_setting = get_option('kdsamref_compatibility_mode', 'auto');
        
        if ($user_setting !== 'auto') {
            return $user_setting; // User manually selected mode
        }
        
        // Auto-detect based on installed plugins
        if (self::is_orderable_active()) {
            return 'orderable';
        }
        
        return 'woocommerce'; // Default to WooCommerce mode
    }
    
    /**
     * Check if Orderable plugin is active
     */
    public static function is_orderable_active() {
        // Method 1: Check classes
        if (class_exists('Orderable') || class_exists('Orderable_Main')) {
            return true;
        }
        
        // Method 2: Check active plugins
        $active_plugins = get_option('active_plugins', array());
        foreach ($active_plugins as $plugin) {
            if (strpos($plugin, 'orderable') !== false) {
                return true;
            }
        }
        
        // Method 3: Check functions
        if (function_exists('orderable_init') || function_exists('orderable')) {
            return true;
        }
        
        return false;
    }
    
    /**
     * Get proper order statuses based on mode
     */
    public static function get_valid_order_statuses() {
        $mode = self::get_mode();
        $statuses = array();

        switch ($mode) {
            case 'orderable':
                $base_statuses = array('processing', 'preparing', 'ready-pickup', 'completed');
                
                // Check if Orderable Pro custom statuses are available
                if (class_exists('Orderable_Custom_Order_Status_Pro_Helper')) {
                    try {
                        $custom_statuses = Orderable_Custom_Order_Status_Pro_Helper::get_custom_order_statuses();
                        if (!empty($custom_statuses)) {
                            // Add custom status slugs to the list
                            foreach ($custom_statuses as $status) {
                                if (isset($status->post_name) && !empty($status->post_name)) {
                                    $base_statuses[] = $status->post_name;
                                }
                            }
                        }
                    } catch (Exception $e) {
                        // Continue with base statuses on error
                    }
                }
                $statuses = $base_statuses;
                break;
                
            case 'woocommerce':
            default:
                $statuses = array('processing', 'completed');
                break;
        }

        // Always merge custom statuses from plugin settings, regardless of mode
        $settings = get_option('kdsamref_settings', array());
        if (!empty($settings['custom_statuses']) && is_array($settings['custom_statuses'])) {
            foreach ($settings['custom_statuses'] as $slug => $status_data) {
                if (!empty($slug) && !in_array($slug, $statuses, true)) {
                    $statuses[] = $slug;
                }
            }
        }

        // Ensure uniqueness and return
        return array_values(array_unique($statuses));
    }
    
    /**
     * Get proper post status filter based on mode
     */
    public static function get_forbidden_statuses() {
        $mode = self::get_mode();
        
        switch ($mode) {
            case 'orderable':
                // Strict filtering for Orderable
                return array('draft', 'brouillon', 'checkout-draft', 'wc-draft', 'wc-brouillon', 'wc-checkout-draft');
                
            case 'woocommerce':
            default:
                // Relaxed filtering for normal WooCommerce
                // Allow draft post_status for valid WooCommerce orders
                return array('checkout-draft', 'wc-checkout-draft');
        }
    }
    
    /**
     * Format order data based on mode
     */
    public static function format_order_data($order, $original_data) {
        $mode = self::get_mode();
        
        switch ($mode) {
            case 'orderable':
                return self::format_orderable_data($order, $original_data);
                
            case 'woocommerce':
            default:
                return self::format_woocommerce_data($order, $original_data);
        }
    }
    
    /**
     * Format data for Orderable mode
     */
    private static function format_orderable_data($order, $data) {
        // Keep original Orderable formatting
        return $data;
    }
    
    /**
     * Format data for WooCommerce mode
     */
    private static function format_woocommerce_data($order, $data) {
        // Fix delivery type based on shipping method
        if (empty($data['delivery']['orderable_service'])) {
            $shipping_methods = $order->get_shipping_methods();
            
            if (empty($shipping_methods)) {
                $data['delivery']['type'] = 'dine-in';
                $data['delivery']['type_name'] = 'Dine In';
            } else {
                foreach ($shipping_methods as $method) {
                    $method_id = strtolower($method->get_method_id());
                    
                    if (strpos($method_id, 'pickup') !== false || strpos($method_id, 'collection') !== false) {
                        $data['delivery']['type'] = 'pickup';
                        $data['delivery']['type_name'] = 'Takeaway';
                        break;
                    } elseif (strpos($method_id, 'delivery') !== false) {
                        $data['delivery']['type'] = 'delivery';
                        $data['delivery']['type_name'] = 'Delivery';
                        break;
                    }
                }
            }
        }
        
        // Add WooCommerce-specific indicators
        $data['compatibility_mode'] = 'woocommerce';
        $data['is_orderable_order'] = false;
        
        return $data;
    }
    
    /**
     * Get mode display name
     */
    public static function get_mode_display_name($mode = null) {
        if ($mode === null) {
            $mode = self::get_mode();
        }
        
        switch ($mode) {
            case 'orderable':
                return 'Orderable Restaurant Orders';
            case 'woocommerce':
                return 'WooCommerce Standard Orders';
            default:
                return 'Unknown Mode';
        }
    }
    
    /**
     * Check if current order should be visible
     */
    public static function should_show_order($order_data) {
        $forbidden = self::get_forbidden_statuses();
        $mode = self::get_mode();
        
        // For WooCommerce mode, be more lenient with post_status
        if ($mode === 'woocommerce') {
            // Only filter by WooCommerce status, not post_status
            return !in_array($order_data['status'], $forbidden);
        }
        
        // For Orderable mode, use strict filtering
        return !in_array($order_data['status'], $forbidden) && 
               !in_array($order_data['post_status'], $forbidden);
    }
    
    /**
     * Get dashboard title based on mode
     */
    public static function get_dashboard_title() {
        $mode = self::get_mode();
        
        switch ($mode) {
            case 'orderable':
                return "Commandes Restaurant (Orderable)";
            case 'woocommerce':
                return "Commandes Restaurant (WooCommerce)";
            default:
                return "Commandes Restaurant";
        }
    }
    
    /**
     * Get mode-specific settings
     */
    public static function get_mode_settings() {
        $mode = self::get_mode();
        
        return array(
            'mode' => $mode,
            'display_name' => self::get_mode_display_name($mode),
            'valid_statuses' => self::get_valid_order_statuses(),
            'forbidden_statuses' => self::get_forbidden_statuses(),
            'orderable_active' => self::is_orderable_active(),
            'features' => self::get_mode_features($mode)
        );
    }
    
    /**
     * Get available features for mode
     */
    private static function get_mode_features($mode) {
        switch ($mode) {
            case 'orderable':
                return array(
                    'scheduled_orders' => true,
                    'table_numbers' => true,
                    'service_types' => true,
                    'location_info' => true,
                    'orderable_integration' => true
                );
                
            case 'woocommerce':
            default:
                return array(
                    'scheduled_orders' => false,
                    'table_numbers' => false,
                    'service_types' => false,
                    'location_info' => false,
                    'orderable_integration' => false,
                    'shipping_methods' => true,
                    'standard_orders' => true
                );
        }
    }
    
    /**
     * Get delivery type information with mode-aware logic
     */
    public static function get_delivery_type_info($order, $mode = null) {
        if (!$mode) {
            $mode = self::get_mode();
        }
        

        
        if ($mode === 'orderable') {
            return self::get_orderable_delivery_type_info($order);
        } else {
            return self::get_woocommerce_delivery_type_info($order);
        }
    }
    
    /**
     * Get Orderable-specific delivery type info
     */
    private static function get_orderable_delivery_type_info($order) {
        // Original Orderable logic
        $delivery_type = 'emporter'; // default to emporter (takeaway)
        
        if ($order instanceof WC_Order) {
            // First check custom meta
            $delivery_type = get_post_meta($order->get_id(), '_kdsamref_delivery_type', true);
            
            if (empty($delivery_type)) {
                // Try to detect from Orderable service type
                $orderable_service_type = get_post_meta($order->get_id(), '_orderable_service_type', true);
                
                if (!empty($orderable_service_type)) {
                    $service_type_lower = strtolower($orderable_service_type);
                    
                    if (strpos($service_type_lower, 'delivery') !== false || 
                        strpos($service_type_lower, 'livraison') !== false) {
                        $delivery_type = 'livraison';
                    } elseif (strpos($service_type_lower, 'dine') !== false || 
                             strpos($service_type_lower, 'sur place') !== false ||
                             strpos($service_type_lower, 'table') !== false) {
                        $delivery_type = 'surplace';
                    } else {
                        $delivery_type = 'emporter';
                    }
                } else {
                    // Fallback to shipping method detection
                    $shipping_methods = $order->get_shipping_methods();
                    if (!empty($shipping_methods)) {
                        $method = reset($shipping_methods);
                        $method_id = strtolower($method->get_method_id());
                        $method_name = strtolower($method->get_name());
                        
                        if (strpos($method_name, 'delivery') !== false || 
                            strpos($method_name, 'livraison') !== false ||
                            strpos($method_id, 'delivery') !== false) {
                            $delivery_type = 'livraison';
                        } elseif (strpos($method_name, 'dine') !== false || 
                                 strpos($method_name, 'sur place') !== false ||
                                 strpos($method_name, 'table') !== false) {
                            $delivery_type = 'surplace';
                        } else {
                            $delivery_type = 'emporter';
                        }
                    }
                }
            }
        }
        
        $types = array(
            'emporter' => array(
                'class' => 'pickup',
                'label' => 'À Emporter',
                'color' => '#007cba'
            ),
            'livraison' => array(
                'class' => 'delivery', 
                'label' => 'Livraison',
                'color' => '#28a745'
            ),
            'surplace' => array(
                'class' => 'dine-in',
                'label' => 'Sur Place', 
                'color' => '#6f42c1'
            )
        );
        
        return $types[$delivery_type] ?? $types['emporter'];
    }
    
    /**
     * Get WooCommerce-specific delivery type info
     */
    private static function get_woocommerce_delivery_type_info($order) {
        $delivery_type = 'point-vente'; // default for WooCommerce
        
        if ($order instanceof WC_Order) {
            // First check if order contains only digital/downloadable products
            $is_digital_only = self::is_digital_only_order($order);
            
            if ($is_digital_only) {
                $delivery_type = 'numerique';
            } else {
                // Check custom meta first
                $delivery_type = get_post_meta($order->get_id(), '_kdsamref_delivery_type', true);
                
                if (empty($delivery_type)) {
                    // Try to detect from WooCommerce shipping method
                    $shipping_methods = $order->get_shipping_methods();
                    if (!empty($shipping_methods)) {
                        $method = reset($shipping_methods);
                        $method_id = strtolower($method->get_method_id());
                        $method_name = strtolower($method->get_name());
                        
                        // WooCommerce shipping method mapping
                        if (strpos($method_id, 'local_delivery') !== false || 
                            strpos($method_id, 'delivery') !== false ||
                            strpos($method_name, 'livraison') !== false ||
                            strpos($method_name, 'delivery') !== false ||
                            strpos($method_name, 'domicile') !== false) {
                            $delivery_type = 'livraison';
                        } elseif (strpos($method_id, 'local_pickup') !== false || 
                                 strpos($method_id, 'pickup') !== false ||
                                 strpos($method_id, 'store_pickup') !== false ||
                                 strpos($method_name, 'retrait') !== false ||
                                 strpos($method_name, 'pickup') !== false ||
                                 strpos($method_name, 'collect') !== false) {
                            $delivery_type = 'retrait';
                        } else {
                            // Default: Point de vente (in-store/POS)
                            $delivery_type = 'point-vente';
                        }
                    } else {
                        // No shipping method = likely point de vente or digital
                        $delivery_type = 'point-vente';
                    }
                }
            }
        }
        
        // WooCommerce mode delivery types
        $types = array(
            'numerique' => array(
                'class' => 'numerique',
                'label' => 'Numérique',
                'color' => '#17a2b8'
            ),
            'point-vente' => array(
                'class' => 'point-vente',
                'label' => 'Point de Vente',
                'color' => '#6f42c1'
            ),
            'livraison' => array(
                'class' => 'delivery',
                'label' => 'Livraison', 
                'color' => '#28a745'
            ),
            'retrait' => array(
                'class' => 'pickup',
                'label' => 'Retrait',
                'color' => '#ff6f00'
            )
        );
        
        return $types[$delivery_type] ?? $types['point-vente'];
    }
    
    /**
     * Check if order contains only digital/downloadable products
     */
    private static function is_digital_only_order($order) {
        if (!$order instanceof WC_Order) {
            return false;
        }
        
        $items = $order->get_items();
        if (empty($items)) {
            return false;
        }
        
        $digital_count = 0;
        $total_count = 0;
        
        foreach ($items as $item) {
            $product = $item->get_product();
            if (!$product) {
                continue;
            }
            
            $total_count++;
            
            // Check if product is downloadable OR virtual
            if ($product->is_downloadable() || $product->is_virtual()) {
                $digital_count++;
            }
        }
        
        $is_digital_only = ($total_count > 0 && $digital_count === $total_count);
        
        // Digital detection completed
        
        return $is_digital_only;
    }
}
