<?php
/**
 * Orderable Integration Helper
 * 
 * This file helps detect Orderable plugin meta fields
 */

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

class KDSAMREF_Orderable_Integration {

    /**
     * Cached field mappings to avoid repeated database queries
     */
    private static $field_cache = array();
    
    /**
     * Whether Orderable is active (cached result)
     */
    private static $orderable_active = null;

    /**
     * Constructor - Initialize integration
     */
    public function __construct() {
        $this->init_hooks();

    }
    
    /**
     * Initialize hooks
     */
    private function init_hooks() {
        // Hook into order display to add Orderable data
        add_action('woocommerce_admin_order_data_after_shipping_address', array($this, 'display_orderable_data'));
        
        // Hook into order status changes to clear cache
        add_action('woocommerce_order_status_changed', array($this, 'clear_order_cache'), 10, 3);
        
        // Hook into order save to clear cache
        add_action('woocommerce_process_shop_order_meta', array($this, 'clear_order_cache'), 10, 1);
    }
    
    /**
     * Clear order cache when order is updated
     */
    public function clear_order_cache($order_id) {
        if ($order_id) {
            wp_cache_delete('kdsamref_orderable_data_' . $order_id, 'kdsamref_orderable');
        }
    }

    

    
    /**
     * Display Orderable data in WooCommerce order admin
     */
    public function display_orderable_data($order) {
        // Check if this is a valid order with an ID (not a new order being created)
        if (!$order || !$order->get_id() || $order->get_id() <= 0) {
            return;
        }
        
        // Check if we're on a new order page
        global $pagenow;
        if ($pagenow === 'post-new.php' && isset($_GET['post_type']) && sanitize_text_field(wp_unslash($_GET['post_type'])) === 'shop_order') {
            return;
        }
        
        // Check if the order exists in database
        if (!get_post($order->get_id())) {
            return;
        }
        
        $orderable_data = self::get_orderable_data($order->get_id());
        
        // Ensure all required keys exist
        $orderable_data = array_merge(array(
            'service_type' => '',
            'table_number' => '',
            'delivery_date' => '',
            'delivery_time' => '',
            'pickup_date' => '',
            'pickup_time' => ''
        ), $orderable_data);
        
        if (empty(array_filter($orderable_data))) {
            return;
        }
        
        echo '<div class="kdsamref-orderable-data" style="margin-top: 15px; padding: 10px; background: #f9f9f9; border-radius: 4px;">';
        echo '<h4>' . esc_html__('Orderable Information', 'kds-report-for-orderable') . '</h4>';
        
        if (!empty($orderable_data['service_type'])) {
            echo '<p><strong>' . esc_html__('Service Type:', 'kds-report-for-orderable') . '</strong> ' . esc_html($orderable_data['service_type']) . '</p>';
        }
        
        if (!empty($orderable_data['table_number'])) {
            echo '<p><strong>' . esc_html__('Table Number:', 'kds-report-for-orderable') . '</strong> ' . esc_html($orderable_data['table_number']) . '</p>';
        }
        
        $scheduled = self::format_scheduled_time(
            $orderable_data['delivery_date'] ?: $orderable_data['pickup_date'],
            $orderable_data['delivery_time'] ?: $orderable_data['pickup_time']
        );
        
        if ($scheduled) {
            echo '<p><strong>' . esc_html__('Scheduled Time:', 'kds-report-for-orderable') . '</strong> ' . esc_html($scheduled) . '</p>';
        }
        
        echo '</div>';
    }
    


    /**
     * Get tip/pourboire amount from order (from thankyou page pattern)
     */
    public static function get_tip_amount($order_id) {
        // Check if this is a valid order ID
        if (!$order_id || $order_id <= 0) {
            return null;
        }
        
        $order = wc_get_order($order_id);
        if (!$order) {
            return null;
        }

        $order_fees = $order->get_fees();
        foreach ($order_fees as $fee) {
            $fee_name = strtolower($fee->get_name());
            
            // Check for tip in multiple languages (from thankyou page code)
            if ($fee_name === 'tip' || 
                $fee_name === 'pourboire' ||
                $fee->get_name() === __('Tip', 'kds-report-for-orderable')) {
                return array(
                    'amount' => $fee->get_amount(),
                    'formatted' => wc_price($fee->get_amount()),
                    'name' => 'Pourboire'
                );
            }
        }

        return null;
    }

    /**
     * Get all fees from order with French translations
     */
    public static function get_order_fees($order_id) {
        // Check if this is a valid order ID
        if (!$order_id || $order_id <= 0) {
            return array();
        }
        
        $order = wc_get_order($order_id);
        if (!$order) {
            return array();
        }

        $fees = array();
        $order_fees = $order->get_fees();
        
        foreach ($order_fees as $fee) {
            $fee_name = $fee->get_name();
            
            // Translate common fee names to French (from thankyou page pattern)
            if (strtolower($fee_name) === 'tip' || $fee_name === __('Tip', 'kds-report-for-orderable')) {
                $fee_name = 'Pourboire';
            }
            
            $fees[] = array(
                'name' => $fee_name,
                'amount' => $fee->get_amount(),
                'formatted' => wc_price($fee->get_amount())
            );
        }

        return $fees;
    }

    /**
     * Check if Orderable plugin is active (with caching)
     */
    public static function is_orderable_active() {
        if (self::$orderable_active === null) {
            self::$orderable_active = class_exists('Orderable') || 
                                    (function_exists('is_plugin_active') && is_plugin_active('orderable/orderable.php')) ||
                                    (function_exists('is_plugin_active') && is_plugin_active('orderable-pro/orderable-pro.php'));
        }
        return self::$orderable_active;
    }
    




    /**
     * Get delivery date from Orderable
     */
    public static function get_delivery_date($order_id) {
        $possible_keys = array(
            'orderable_order_date',     // Without underscore prefix (from debug)
            '_orderable_delivery_date',
            '_delivery_date',
            '_wc_delivery_date',
            '_orderable_scheduled_date',
            '_orderable_order_date'     // With underscore prefix
        );

        foreach ($possible_keys as $key) {
            $value = get_post_meta($order_id, $key, true);
            if (!empty($value)) {
                return $value;
            }
        }

        return null;
    }

    /**
     * Get delivery time from Orderable
     */
    public static function get_delivery_time($order_id) {
        $possible_keys = array(
            'orderable_order_time',     // Without underscore prefix (from debug)
            '_orderable_delivery_time',
            '_delivery_time',
            '_wc_delivery_time',
            '_orderable_scheduled_time',
            '_orderable_order_time'     // With underscore prefix
        );

        foreach ($possible_keys as $key) {
            $value = get_post_meta($order_id, $key, true);
            if (!empty($value)) {
                return $value;
            }
        }

        return null;
    }

    /**
     * Get pickup date from Orderable
     */
    public static function get_pickup_date($order_id) {
        $possible_keys = array(
            'orderable_order_date',     // Orderable uses same fields for pickup
            '_orderable_pickup_date',
            '_pickup_date',
            '_wc_pickup_date',
            '_orderable_order_date'
        );

        foreach ($possible_keys as $key) {
            $value = get_post_meta($order_id, $key, true);
            if (!empty($value)) {
                return $value;
            }
        }

        return null;
    }

    /**
     * Get pickup time from Orderable
     */
    public static function get_pickup_time($order_id) {
        $possible_keys = array(
            'orderable_order_time',     // Orderable uses same fields for pickup
            '_orderable_pickup_time',
            '_pickup_time',
            '_wc_pickup_time',
            '_orderable_order_time'
        );

        foreach ($possible_keys as $key) {
            $value = get_post_meta($order_id, $key, true);
            if (!empty($value)) {
                return $value;
            }
        }

        return null;
    }

    /**
     * Get service type from Orderable
     */
    public static function get_service_type($order_id) {
        $possible_keys = array(
            '_orderable_service_type',
            '_service_type',
            '_orderable_location_type',
            '_location_type'
        );

        foreach ($possible_keys as $key) {
            $value = get_post_meta($order_id, $key, true);
            if (!empty($value)) {
                return $value;
            }
        }

        return null;
    }

    /**
     * Get table number from Orderable
     */
    public static function get_table_number($order_id) {
        // Primary Orderable meta keys (from thankyou page code)
        $primary_keys = array(
            '_orderable_table',
            '_orderable_table_id'
        );
        
        // Check primary Orderable fields first
        foreach ($primary_keys as $key) {
            $value = get_post_meta($order_id, $key, true);
            if (!empty($value)) {
                return $value;
            }
        }
        
        // Fallback to common table meta keys (from thankyou page pattern)
        $fallback_keys = array(
            '_table_number',
            'table_number',
            '_table',
            'table',
            '_orderable_table_number'
        );

        foreach ($fallback_keys as $key) {
            $value = get_post_meta($order_id, $key, true);
            if (!empty($value)) {
                return $value;
            }
        }

        return null;
    }

    /**
     * Get location/restaurant from Orderable
     */
    public static function get_location($order_id) {
        $possible_keys = array(
            '_orderable_location',
            '_restaurant_location',
            '_orderable_store'
        );

        foreach ($possible_keys as $key) {
            $value = get_post_meta($order_id, $key, true);
            if (!empty($value)) {
                return $value;
            }
        }

        return null;
    }

    /**
     * Get all Orderable data for an order with intelligent field detection
     */
    public static function get_orderable_data($order_id) {
        // Check if this is a valid order ID
        if (!$order_id || $order_id <= 0) {
            // Invalid order ID
            return array(
                'delivery_date' => null,
                'delivery_time' => null,
                'pickup_date' => null,
                'pickup_time' => null,
                'service_type' => null,
                'table_number' => null,
                'location' => null,
                'is_orderable_active' => self::is_orderable_active()
            );
        }
        
        // Use cache if available for this order
        $cache_key = 'kdsamref_orderable_data_' . $order_id;
        $cached_data = wp_cache_get($cache_key, 'kdsamref_orderable');
        
        if ($cached_data !== false) {
            // Using cached data for order
            return $cached_data;
        }
        
        // First try standard field names
        $data = array(
            'delivery_date' => self::get_delivery_date($order_id),
            'delivery_time' => self::get_delivery_time($order_id),
            'pickup_date' => self::get_pickup_date($order_id),
            'pickup_time' => self::get_pickup_time($order_id),
            'service_type' => self::get_service_type($order_id),
            'table_number' => self::get_table_number($order_id),
            'location' => self::get_location($order_id),
            'is_orderable_active' => self::is_orderable_active()
        );
        
        // Debug log the data
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // Log only non-sensitive data
        $safe_data = array();
        foreach ($data as $key => $value) {
            if (strpos($key, 'password') === false && 
                strpos($key, 'token') === false && 
                strpos($key, 'secret') === false &&
                strpos($key, 'key') === false &&
                strpos($key, 'api') === false) {
                $safe_data[$key] = $value;
            }
        }
        // Safe Orderable data for order
        }
        
        // Cache the result for this order for 15 minutes
        wp_cache_set($cache_key, $data, 'kdsamref_orderable', 15 * MINUTE_IN_SECONDS);
        
        return $data;
    }
    

    






    /**
     * Format delivery/pickup datetime for display
     */
    public static function format_scheduled_time($date, $time) {
        if (empty($date)) {
            return null;
        }

        // Convert Orderable date format to WordPress timezone
        $formatted_date = self::convert_orderable_date_to_wp($date);
        
        $datetime_string = $formatted_date;
        if (!empty($time)) {
            $datetime_string .= ' ' . $time;
        }

        try {
            $wp_timezone = wp_timezone();
            $datetime = new DateTime($datetime_string, $wp_timezone);
            return $datetime->format('d/m/Y H:i');
        } catch (Exception $e) {
            return $datetime_string; // Return original if parsing fails
        }
    }
    
    /**
     * Convert Orderable date format to WordPress timezone
     */
    private static function convert_orderable_date_to_wp($orderable_date) {
        if (empty($orderable_date)) {
            return null;
        }
        
        // Orderable date format: "28 juillet 2025" or "28/07/2025" or "2025-07-28"
        $wp_timezone = wp_timezone();
        
        // Try different date formats
        $formats = array(
            'd F Y',      // "28 juillet 2025"
            'd/m/Y',      // "28/07/2025"
            'Y-m-d',      // "2025-07-28"
            'd-m-Y',      // "28-07-2025"
        );
        
        foreach ($formats as $format) {
            try {
                $datetime = DateTime::createFromFormat($format, $orderable_date, $wp_timezone);
                if ($datetime !== false) {
                    return $datetime->format('Y-m-d');
                }
            } catch (Exception $e) {
                continue;
            }
        }
        
        // If all formats fail, return original
        return $orderable_date;
    }

    /**
     * Get human readable time remaining until delivery/pickup
     */
    public static function get_time_until_scheduled($date, $time) {
        if (empty($date)) {
            return null;
        }

        // Convert Orderable date format to WordPress timezone
        $formatted_date = self::convert_orderable_date_to_wp($date);
        
        $datetime_string = $formatted_date;
        if (!empty($time)) {
            $datetime_string .= ' ' . $time;
        }

        try {
            $wp_timezone = wp_timezone();
            $scheduled_time = new DateTime($datetime_string, $wp_timezone);
            $now = new DateTime('now', $wp_timezone);
            
            if ($scheduled_time > $now) {
                $diff = $now->diff($scheduled_time);
                if ($diff->days > 0) {
                    /* translators: %d: number of days */
                    return sprintf(__('Dans %d jour(s)', 'kds-report-for-orderable'), $diff->days);
                } elseif ($diff->h > 0) {
                    /* translators: %d: number of hours */
                    return sprintf(__('Dans %d heure(s)', 'kds-report-for-orderable'), $diff->h);
                } else {
                    /* translators: %d: number of minutes */
                    return sprintf(__('Dans %d minute(s)', 'kds-report-for-orderable'), $diff->i);
                }
            } else {
                $diff = $scheduled_time->diff($now);
                if ($diff->days > 0) {
                    /* translators: %d: number of days */
                    return sprintf(__('Il y a %d jour(s)', 'kds-report-for-orderable'), $diff->days);
                } elseif ($diff->h > 0) {
                    /* translators: %d: number of hours */
                    return sprintf(__('Il y a %d heure(s)', 'kds-report-for-orderable'), $diff->h);
                } else {
                    /* translators: %d: number of minutes */
                    return sprintf(__('Il y a %d minute(s)', 'kds-report-for-orderable'), $diff->i);
                }
            }
        } catch (Exception $e) {
            return null;
        }
    }
    

    

}
