<?php
/**
 * Order Manager Class - Updated with Compatibility Manager
 * 
 * Handles WooCommerce orders for restaurant management with dual mode support
 */

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

// Include compatibility manager
require_once KDSAMREF_PLUGIN_PATH . 'includes/class-kdsamref-compatibility-manager.php';

// Include admin class for settings
require_once KDSAMREF_PLUGIN_PATH . 'includes/class-kdsamref-admin.php';

class KDSAMREF_Order_Manager {

    /**
     * Constructor
     */
    public function __construct() {
        // Hook into WooCommerce order status changes
        add_action('woocommerce_order_status_changed', array($this, 'on_order_status_changed'), 10, 4);
        
        // Include Orderable integration if available
        if (file_exists(KDSAMREF_PLUGIN_PATH . 'includes/class-kdsamref-orderable-integration.php')) {
            include_once KDSAMREF_PLUGIN_PATH . 'includes/class-kdsamref-orderable-integration.php';
        }
    }

    /**
     * Get orders based on status - Updated with Compatibility Manager
     * Supports both Orderable and WooCommerce modes
     */
    public function get_orders($status = 'any', $limit = 100) {
        // Get compatibility mode and settings
        $compatibility_mode = KDSAMREF_Compatibility_Manager::get_mode();
        $valid_statuses = KDSAMREF_Compatibility_Manager::get_valid_order_statuses();
        
        // For WordPress.org Core: no artificial limits/date constraints
        $args = array(
            'limit' => $limit,
            'orderby' => 'date',
            'order' => 'DESC',
            'return' => 'objects',
            'type' => 'shop_order',
            'status' => $valid_statuses, // Use compatibility-aware statuses
        );
        
        $orders = wc_get_orders($args);
        $formatted_orders = array();
        foreach ($orders as $order) {
            $order_data = $this->format_order_data($order);
            if ($order_data && KDSAMREF_Compatibility_Manager::should_show_order($order_data)) {
                $formatted_orders[] = $order_data;
            }
        }

        // Use compatibility-aware filtering
        $forbidden_statuses = KDSAMREF_Compatibility_Manager::get_forbidden_statuses();
        $formatted_orders = array_filter($formatted_orders, function($order) use ($forbidden_statuses, $compatibility_mode) {
            // Apply mode-specific filtering logic
            if ($compatibility_mode === 'woocommerce') {
                // For WooCommerce mode: Only filter by order status, ignore post_status
                return !in_array($order['status'], $forbidden_statuses);
            } else {
                // For Orderable mode: Use strict filtering
                $status_variants = array(
                    $order['status'] ?? '',
                    $order['post_status'] ?? '',
                    isset($order['status']) ? 'wc-' . $order['status'] : '',
                    isset($order['post_status']) ? 'wc-' . $order['post_status'] : '',
                );
                foreach ($forbidden_statuses as $forbidden) {
                    if (in_array($forbidden, $status_variants, true)) {
                        return false;
                    }
                }
                return true;
            }
        });

        return $formatted_orders;
    }
    
    /**
     * Get order ID safely (HPOS compatible)
     */
    private function get_order_id($order) {
        if (method_exists($order, 'get_id')) {
            return $order->get_id();
        }
        
        // Fallback for older WooCommerce versions
        if (isset($order->id)) {
            return $order->id;
        }
        
        return 0;
    }

    /**
     * Format order data for frontend - Updated with Compatibility Manager
     */
    public function format_order_data($order) {
        if (!$order instanceof WC_Order) {
            return false;
        }

        $order_id = $this->get_order_id($order);
        $post = get_post($order_id);
        $post_status = $post ? $post->post_status : '';

        // Use WooCommerce API status as the source of truth (HPOS-safe, includes custom statuses)
        $status_slug = $order->get_status();
        
        // Get delivery type from Compatibility Manager
        $delivery_info = KDSAMREF_Compatibility_Manager::get_delivery_type_info($order);
        $delivery_type = isset($delivery_info['class']) ? $delivery_info['class'] : 'pickup';
        $delivery_type_name = isset($delivery_info['label']) ? $delivery_info['label'] : 'Takeaway';

        // Get compatibility mode
        $compatibility_mode = KDSAMREF_Compatibility_Manager::get_mode();
        
        // Get Orderable data if available with error handling
        $orderable_data = array();
        $tip_info = null;
        $fees_info = array();
        
        if ($compatibility_mode === 'orderable' && class_exists('KDSAMREF_Orderable_Integration')) {
            try {
                            $orderable_data = KDSAMREF_Orderable_Integration::get_orderable_data($order_id);
            $tip_info = KDSAMREF_Orderable_Integration::get_tip_amount($order_id);
            $fees_info = KDSAMREF_Orderable_Integration::get_order_fees($order_id);
                
                // Orderable data loaded successfully
            } catch (Exception $e) {
                // Log error but continue processing (only in debug mode)
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    // Error getting Orderable data for order
                }
            }
        }
        
        // Ensure orderable_data has all required keys with default values
        $orderable_data = array_merge(array(
            'delivery_date' => null,
            'delivery_time' => null,
            'pickup_date' => null,
            'pickup_time' => null,
            'service_type' => null,
            'table_number' => null,
            'location' => null,
            'is_orderable_active' => ($compatibility_mode === 'orderable')
        ), $orderable_data);

        // WordPress timezone'unda tarihi formatla
        $wp_timezone = wp_timezone();
        $order_date_utc = $order->get_date_created();
        $order_date_wp = clone $order_date_utc;
        $order_date_wp->setTimezone($wp_timezone);

        $order_data = array(
            'id' => $order_id,
            'number' => $order->get_order_number(),
            'status' => $status_slug,
            'post_status' => $post_status,
            // Use normalized slug to avoid label/status mismatch on custom statuses
            'status_name' => $this->get_status_name($status_slug),
            'date_created' => $order_date_wp->format('Y-m-d\\TH:i:sP'), // ISO format with timezone
            'date_created_wp' => $order_date_wp->format('Y-m-d H:i:s'), // WordPress timezone simple format
            'date_created_raw' => $order_date_utc->format('Y-m-d H:i:s'), // UTC ham tarihi
            'time_ago' => $this->get_time_ago($order->get_date_created()),
            'customer' => array(
                'name' => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
                'phone' => $order->get_billing_phone(),
                'email' => $order->get_billing_email(),
            ),
            'delivery' => array(
                'type' => $delivery_type,
                'type_name' => $delivery_type_name,
                'address' => $this->get_formatted_address($order),
                'table_number' => get_post_meta($order_id, '_kdsamref_table_number', true) ?: ($orderable_data['table_number'] ?? ''),
                'pickup_time' => get_post_meta($order_id, '_kdsamref_pickup_time', true) ?: ($orderable_data['pickup_time'] ?? ''),
                // Orderable specific data
                'scheduled_date' => $orderable_data['delivery_date'] ?: $orderable_data['pickup_date'],
                'scheduled_time' => $orderable_data['delivery_time'] ?: $orderable_data['pickup_time'],
                'orderable_service' => $orderable_data['service_type'] ?? '',
                'location' => $orderable_data['location'] ?? '',
                'formatted_schedule' => $this->format_scheduled_datetime($orderable_data),
                'time_until_scheduled' => $this->get_time_until_scheduled($orderable_data),
            ),
            'items' => $this->get_order_items($order),
            'total' => $order->get_total(), // Bu zaten TVA dahil toplam
            'total_formatted' => wc_price($order->get_total(), array('currency' => $order->get_currency())), // Formatlanmış toplam
            'currency' => $order->get_currency() ?: get_woocommerce_currency(), // WooCommerce default para birimini kullan
            'currency_symbol' => get_woocommerce_currency_symbol($order->get_currency() ?: get_woocommerce_currency()), // WooCommerce default sembolünü kullan
            'special_instructions' => get_post_meta($order_id, '_kdsamref_special_instructions', true),
            'payment_method' => $order->get_payment_method_title(),
            'payment_method_title' => $order->get_payment_method_title(),
            'payment_status' => $order->get_payment_method() === 'cod' ? 'pending' : ($order->is_paid() ? 'paid' : 'pending'),
            'transaction_id' => $order->get_transaction_id(),
            'payment_date' => $order->get_date_paid() ? $order->get_date_paid()->format('Y-m-d H:i:s') : null,
            'card_last4' => get_post_meta($order_id, '_stripe_source_id', true) ? get_post_meta($order_id, '_stripe_last4', true) : null,
            'card_brand' => get_post_meta($order_id, '_stripe_source_id', true) ? get_post_meta($order_id, '_stripe_brand', true) : null,
            'cash_amount' => get_post_meta($order_id, '_kdsamref_cash_amount', true),
            'change_amount' => get_post_meta($order_id, '_kdsamref_change_amount', true),
            'staff_name' => get_post_meta($order_id, '_kdsamref_staff_name', true),
            // Enhanced Orderable data (from thankyou page insights)
            'tip_info' => $tip_info,
            'fees' => $fees_info,
            'has_tip' => !empty($tip_info),
            'total_with_breakdown' => array(
                'subtotal' => $order->get_subtotal(),
                'subtotal_formatted' => wc_price($order->get_subtotal(), array('currency' => $order->get_currency() ?: get_woocommerce_currency())),
                'tax_total' => $order->get_total_tax(),
                'tax_total_formatted' => wc_price($order->get_total_tax(), array('currency' => $order->get_currency() ?: get_woocommerce_currency())),
                'fees_total' => array_sum(array_column($fees_info, 'amount')),
                'fees_total_formatted' => wc_price(array_sum(array_column($fees_info, 'amount')), array('currency' => $order->get_currency() ?: get_woocommerce_currency())),
                'total' => $order->get_total(),
                'total_formatted' => wc_price($order->get_total(), array('currency' => $order->get_currency() ?: get_woocommerce_currency()))
            ),
            // Compatibility info
            'compatibility_mode' => $compatibility_mode,
            'is_orderable_order' => ($compatibility_mode === 'orderable' && !empty($orderable_data['service_type'])),
        );

        // Apply compatibility formatting
        $order_data = KDSAMREF_Compatibility_Manager::format_order_data($order, $order_data);

        return $order_data;
    }

    /**
     * Detect delivery type from shipping method
     */
    private function detect_delivery_type($order) {
        $shipping_methods = $order->get_shipping_methods();
        
        if (empty($shipping_methods)) {
            return 'surplace'; // Default to dine-in if no shipping
        }

        foreach ($shipping_methods as $shipping_method) {
            $method_id = $shipping_method->get_method_id();
            
            if (strpos($method_id, 'local_pickup') !== false) {
                return 'emporter';
            } elseif (strpos($method_id, 'local_delivery') !== false) {
                return 'livraison';
            }
        }

        return 'livraison'; // Default to delivery
    }

    /**
     * Get formatted address
     */
    private function get_formatted_address($order) {
        $address = array();
        
        if ($order->get_shipping_address_1()) {
            $address[] = $order->get_shipping_address_1();
            if ($order->get_shipping_address_2()) {
                $address[] = $order->get_shipping_address_2();
            }
            $address[] = $order->get_shipping_postcode() . ' ' . $order->get_shipping_city();
        }

        return implode(', ', $address);
    }

    /**
     * Get order items formatted - Updated with better currency handling
     */
    private function get_order_items($order) {
        $items = array();
        $currency = $order->get_currency() ?: get_woocommerce_currency(); // WooCommerce default para birimini kullan
        
        foreach ($order->get_items() as $item_id => $item) {
            $product = $item->get_product();
            $items[] = array(
                'name' => $item->get_name(),
                'quantity' => $item->get_quantity(),
                'price' => $item->get_total() + $item->get_total_tax(), // TVA dahil fiyat
                'price_formatted' => wc_price($item->get_total() + $item->get_total_tax(), array('currency' => $currency)), // Formatlanmış TVA dahil fiyat
                'price_excl_tax' => $item->get_total(), // TVA hariç fiyat
                'tax' => $item->get_total_tax(), // TVA miktarı
                'product_id' => $item->get_product_id(),
                'variation_id' => $item->get_variation_id(),
                'meta' => $this->get_item_meta($item),
            );
        }

        return $items;
    }

    /**
     * Get item meta data
     */
    private function get_item_meta($item) {
        $meta = array();
        $item_meta = $item->get_meta_data();
        
        // Technical meta keys to filter out
        $technical_keys = array(
            '_qty', '_tax_class', '_product_id', '_variation_id',
            '_wallee_unique_line_item_id', '_wallee_coupon_discount_line_item_discounts',
            '_wallee_', '_wc_', '_woocommerce_', '_orderable_'
        );
        
        foreach ($item_meta as $meta_data) {
            // Check if this is a technical meta field
            $is_technical = false;
            foreach ($technical_keys as $tech_key) {
                if ($meta_data->key === $tech_key || strpos($meta_data->key, $tech_key) === 0) {
                    $is_technical = true;
                    break;
                }
            }
            
            // Skip technical fields and empty values
            if ($is_technical || empty($meta_data->value)) {
                continue;
            }
            
            $meta[] = array(
                'key' => $meta_data->key,
                'value' => $meta_data->value,
                'display_key' => wc_attribute_label($meta_data->key),
                'display_value' => $meta_data->value,
            );
        }

        return $meta;
    }

    /**
     * Get status name in French
     */
    public function get_status_name($status) {
        $status_names = array(
            // Distinguish between WooCommerce processing (New) and custom preparing
            'processing' => __('Nouvelle', 'kds-report-for-orderable'),
            'preparing' => __('En Préparation', 'kds-report-for-orderable'),
            'ready-pickup' => __('Prêt', 'kds-report-for-orderable'),
            'completed' => __('Livré', 'kds-report-for-orderable'),
            'cancelled' => __('Annulé', 'kds-report-for-orderable'),
            'refunded' => __('Remboursé', 'kds-report-for-orderable'),
            'failed' => __('Échoué', 'kds-report-for-orderable'),
        );

        return isset($status_names[$status]) ? $status_names[$status] : ucfirst($status);
    }

    /**
     * Get delivery type name in French
     */
    public function get_delivery_type_name($type) {
        $type_names = array(
            'livraison' => __('Livraison', 'kds-report-for-orderable'),
            'delivery' => __('Livraison', 'kds-report-for-orderable'),
            'emporter' => __('À Emporter', 'kds-report-for-orderable'),
            'pickup' => __('À Emporter', 'kds-report-for-orderable'),
            'takeaway' => __('À Emporter', 'kds-report-for-orderable'),
            'surplace' => __('Sur Place', 'kds-report-for-orderable'),
            'dine-in' => __('Sur Place', 'kds-report-for-orderable'),
        );

        return isset($type_names[$type]) ? $type_names[$type] : ucfirst($type);
    }

    /**
     * Format order date to WordPress timezone
     */
    private function format_order_date($date) {
        // UTC'den WordPress timezone'una çevir
        $wp_timezone = wp_timezone();
        $order_date = clone $date;
        
        // Eğer UTC'de ise WordPress timezone'una çevir
        if ($order_date->getTimezone()->getName() === 'UTC') {
            $order_date->setTimezone($wp_timezone);
        }
        
        return $order_date->format('Y-m-d H:i:s');
    }

    /**
     * Get time ago string - Updated to use WordPress timezone
     */
    private function get_time_ago($date) {
        // WordPress saati ve timezone'unu kullan
        $current_wp_time = new DateTime(current_time('Y-m-d H:i:s'), wp_timezone());
        $order_time = clone $date;
        
        // Eğer sipariş tarihi UTC'de ise, WordPress timezone'una çevir
        if ($order_time->getTimezone()->getName() === 'UTC') {
            $order_time->setTimezone(wp_timezone());
        }
        
        $time_diff = $current_wp_time->getTimestamp() - $order_time->getTimestamp();
        
        if ($time_diff < 0) {
            return __('À l\'instant', 'kds-report-for-orderable');
        } elseif ($time_diff < 60) {
            /* translators: %d: seconds */
            return sprintf(__('Il y a %1$d secondes', 'kds-report-for-orderable'), $time_diff);
        } elseif ($time_diff < 3600) {
            $minutes = floor($time_diff / 60);
            /* translators: 1: minutes, 2: plural suffix */
            return sprintf(__('Il y a %1$d minute%2$s', 'kds-report-for-orderable'), $minutes, $minutes > 1 ? 's' : '');
        } elseif ($time_diff < 86400) {
            $hours = floor($time_diff / 3600);
            /* translators: 1: hours, 2: plural suffix */
            return sprintf(__('Il y a %1$d heure%2$s', 'kds-report-for-orderable'), $hours, $hours > 1 ? 's' : '');
        } else {
            $days = floor($time_diff / 86400);
            /* translators: 1: days, 2: plural suffix */
            return sprintf(__('Il y a %1$d jour%2$s', 'kds-report-for-orderable'), $days, $days > 1 ? 's' : '');
        }
    }

    /**
     * Update order status
     */
    public function update_order_status($order_id, $new_status) {
        $order = wc_get_order($order_id);
        
        if (!$order) {
            return false;
        }

        // Remove 'wc-' prefix if present
        $new_status = str_replace('wc-', '', $new_status);

        // Validate status - include custom statuses from Orderable Pro
        $valid_statuses = array_keys(wc_get_order_statuses());
        $valid_statuses = array_map(function($status) {
            return str_replace('wc-', '', $status);
        }, $valid_statuses);

        // Add Orderable Pro custom statuses if available
        if (class_exists('Orderable_Custom_Order_Status_Pro_Helper')) {
            try {
                $orderable_custom_statuses = Orderable_Custom_Order_Status_Pro_Helper::get_custom_order_statuses();
                foreach ($orderable_custom_statuses as $status) {
                    $valid_statuses[] = $status->post_name;
                }
            } catch (Exception $e) {
                // Silent fail for Orderable Pro status loading
            }
        }

        // Add plugin custom statuses from settings
        $admin = new KDSAMREF_Admin();
        $settings = $admin->get_all_settings();
        $custom_statuses = $settings['custom_statuses'] ?? array();
        foreach ($custom_statuses as $status_slug => $status_data) {
            $valid_statuses[] = $status_slug;
        }

        // Register custom statuses with WooCommerce if not already registered
        foreach ($custom_statuses as $status_slug => $status_data) {
            if (!in_array($status_slug, $valid_statuses)) {
                // Register the custom status
                $this->register_custom_order_status($status_slug, $status_data['label']);
            }
        }

        if (!in_array($new_status, $valid_statuses)) {
            return false;
        }

        // Update status
        
        try {
            $result = $order->update_status($new_status, __('Status updated from KDS dashboard.', 'kds-report-for-orderable'));
        } catch (Exception $e) {
            return false;
        }

        // Add order note
        $order->add_order_note(
            /* translators: %s: new status label */
            sprintf(esc_html__('Order status changed to %s via KDS dashboard.', 'kds-report-for-orderable'), 
            esc_html($this->get_status_name($new_status)))
        );

        return true;
    }

    /**
     * Register custom order status with WooCommerce
     */
    private function register_custom_order_status($status_slug, $status_label) {
        // Register the status with WooCommerce
        register_post_status($status_slug, array(
            'label' => $status_label,
            'public' => true,
            'exclude_from_search' => false,
            'show_in_admin_all_list' => true,
            'show_in_admin_status_list' => true,
            /* translators: %s: number of orders */
            'label_count' => _n_noop(
                'Orders <span class="count">(%s)</span>',
                'Orders <span class="count">(%s)</span>',
                'kds-report-for-orderable'
            )
        ));

        // Add to WooCommerce order statuses
        add_filter('wc_order_statuses', function($order_statuses) use ($status_slug, $status_label) {
            $order_statuses['wc-' . $status_slug] = $status_label;
            return $order_statuses;
        });
    }

    /**
     * Get order statistics - Updated for new design with WordPress timezone
     * Only shows processing and completed order statistics
     */
    public function get_order_statistics() {
        // WordPress saatini kullan - düzeltilmiş date calculation
        $wp_timezone = wp_timezone();
        $today = new DateTime('today', $wp_timezone);
        $yesterday = new DateTime('yesterday', $wp_timezone);
        
        $today_str = $today->format('Y-m-d');
        $yesterday_str = $yesterday->format('Y-m-d');
        
        $stats = array(
            'processing' => 0,
            'preparing' => 0,
            'ready' => 0,
            'completed_today' => 0,
            'total_today' => 0,
            'revenue_today' => 0,
            'total_all' => 0,
            'processing_all' => 0,
            'completed_all' => 0,
        );

        // Get compatibility-aware statuses
        $valid_statuses = KDSAMREF_Compatibility_Manager::get_valid_order_statuses();
        $forbidden_statuses = KDSAMREF_Compatibility_Manager::get_forbidden_statuses();

        // Get orders for today and yesterday (for free version compatibility)
        $args = array(
            'limit' => -1,
            'date_created' => $yesterday_str . '...' . $today_str . ' 23:59:59',
            'status' => $valid_statuses,
            'return' => 'objects'
        );

        $orders = wc_get_orders($args);

        foreach ($orders as $order) {
            $status = $order->get_status();
            $order_date = $order->get_date_created()->format('Y-m-d');
            
            // Skip forbidden statuses
            if (in_array($status, $forbidden_statuses)) {
                continue;
            }
            
            // Count for all dates
            $stats['total_all']++;
            
            if (in_array($status, ['processing', 'preparing'])) {
                $stats['processing_all']++;
            } elseif (in_array($status, ['ready-pickup', 'completed'])) {
                $stats['completed_all']++;
            }
            
            // Count for today only
            if ($order_date === $today_str) {
                $stats['total_today']++;
                $stats['revenue_today'] += floatval($order->get_total());

                switch ($status) {
                    case 'processing':
                        $stats['processing']++;
                        break;
                    case 'preparing':
                        $stats['preparing']++;
                        break;
                    case 'ready-pickup':
                        $stats['ready']++;
                        break;
                    case 'completed':
                        $stats['completed_today']++;
                        break;
                }
            }
        }

        return $stats;
    }

    /**
     * Sync with Orderable Pro custom statuses
     */
    public function sync_orderable_pro_statuses() {
        if (!class_exists('KDSAMREF_Admin')) {
            return false;
        }
        
        $admin = new KDSAMREF_Admin();
        return $admin->sync_orderable_pro_statuses();
    }

    /**
     * Handle order status changes
     */
    public function on_order_status_changed($order_id, $old_status, $new_status, $order) {
        // You can add webhooks or notifications here
        do_action('kdsamref_order_status_changed', $order_id, $old_status, $new_status, $order);
    }

    /**
     * Add order note
     */
    public function add_order_note($order_id, $note, $is_customer_note = false) {
        $order = wc_get_order($order_id);
        
        if (!$order) {
            return false;
        }

        $order->add_order_note($note, $is_customer_note);
        return true;
    }

    /**
     * Get orders by delivery type
     */
    public function get_orders_by_delivery_type($delivery_type, $limit = 50) {
        // Note: Using direct query for meta filtering - this is acceptable for performance
        global $wpdb;

        $order_ids = $wpdb->get_col($wpdb->prepare(
            "SELECT post_id FROM {$wpdb->postmeta} 
             WHERE meta_key = '_kdsamref_delivery_type' 
             AND meta_value = %s 
             LIMIT %d",
            $delivery_type,
            $limit
        ));

        if (empty($order_ids)) {
            return array();
        }

        $args = array(
            'post__in' => $order_ids,
            'limit' => $limit,
            'orderby' => 'date',
            'order' => 'DESC',
            'return' => 'objects',
            'type' => 'shop_order',
            'status' => array('processing', 'preparing', 'ready-pickup', 'completed'),
        );

        $orders = wc_get_orders($args);
        $formatted_orders = array();

        foreach ($orders as $order) {
            $formatted_orders[] = $this->format_order_data($order);
        }

        return $formatted_orders;
    }
    
    /**
     * Format scheduled datetime from Orderable data
     */
    private function format_scheduled_datetime($orderable_data) {
        if (class_exists('KDSAMREF_Orderable_Integration')) {
            $date = ($orderable_data['delivery_date'] ?? null) ?: ($orderable_data['pickup_date'] ?? null);
            $time = ($orderable_data['delivery_time'] ?? null) ?: ($orderable_data['pickup_time'] ?? null);
            
            return KDSAMREF_Orderable_Integration::format_scheduled_time($date, $time);
        }
        return null;
    }

    /**
     * Get time until scheduled delivery/pickup
     */
    private function get_time_until_scheduled($orderable_data) {
        if (class_exists('KDSAMREF_Orderable_Integration')) {
            $date = ($orderable_data['delivery_date'] ?? null) ?: ($orderable_data['pickup_date'] ?? null);
            $time = ($orderable_data['delivery_time'] ?? null) ?: ($orderable_data['pickup_time'] ?? null);
            
            return KDSAMREF_Orderable_Integration::get_time_until_scheduled($date, $time);
        }
        return null;
    }

    public function get_orders_by_date_range($start_date, $end_date, $limit = 100) {
        // Build allowed statuses from settings (processing/completed + enabled custom statuses)
        $admin = new KDSAMREF_Admin();
        $settings = $admin->get_all_settings();
        $custom_statuses = $settings['custom_statuses'] ?? array();
        $allowed_statuses = array('processing', 'completed');
        foreach ($custom_statuses as $slug => $statusData) {
            if (!empty($slug) && (!isset($statusData['enabled']) || (int)$statusData['enabled'] === 1)) {
                if (!in_array($slug, $allowed_statuses, true)) {
                    $allowed_statuses[] = $slug;
                }
            }
        }

        $args = array(
            'limit' => $limit,
            'orderby' => 'date',
            'order' => 'DESC',
            'return' => 'objects',
            'type' => 'shop_order',
            'status' => $allowed_statuses,
            'date_created' => $start_date . '...' . $end_date,
        );
        $orders = wc_get_orders($args);
        $formatted_orders = array();
        foreach ($orders as $order) {
            $formatted_orders[] = $this->format_order_data($order);
        }
        return $formatted_orders;
    }
}
