<?php
/**
 * AJAX Handler Class
 * 
 * Handles AJAX requests for the restaurant orders dashboard
 */

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

class KDSAMREF_Ajax_Handler {

    /**
     * Constructor
     */
    public function __construct() {
        // Add AJAX hooks
        // Centralized AJAX registrations
        add_action('wp_ajax_kdsamref_get_orders', array($this, 'get_orders'));
        add_action('wp_ajax_kdsamref_update_order_status', array($this, 'update_order_status'));
        add_action('wp_ajax_kdsamref_get_order_stats', array($this, 'get_order_stats'));
        add_action('wp_ajax_kdsamref_add_order_note', array($this, 'add_order_note'));
        add_action('wp_ajax_kdsamref_get_single_order', array($this, 'get_single_order'));
        add_action('wp_ajax_kdsamref_search_orders', array($this, 'search_orders'));
        add_action('wp_ajax_kdsamref_get_orders_by_date_range', array($this, 'get_orders_by_date_range'));
        // Removed legacy core-license dismiss endpoint

        add_action('wp_ajax_kdsamref_get_settings', array($this, 'get_settings'));
        
        // Custom status management AJAX hooks
        add_action('wp_ajax_kdsamref_save_custom_status', array($this, 'save_custom_status'));
        add_action('wp_ajax_kdsamref_delete_custom_status', array($this, 'delete_custom_status'));
        add_action('wp_ajax_kdsamref_get_custom_statuses', array($this, 'get_custom_statuses'));
        add_action('wp_ajax_kdsamref_toggle_custom_status', array($this, 'toggle_custom_status'));
        add_action('wp_ajax_kdsamref_sync_orderable_pro_statuses', array($this, 'sync_orderable_pro_statuses'));

        // Stock management AJAX hooks
        add_action('wp_ajax_kdsamref_get_stock_items', array($this, 'get_stock_items'));
        add_action('wp_ajax_kdsamref_update_stock_quantity', array($this, 'update_stock_quantity'));

    }

    /**
     * Enhanced security verification with rate limiting and logging
     */
    private function verify_request() {
        // Debug logging for AJAX requests
        if (defined('WP_DEBUG') && WP_DEBUG) {
            $action = sanitize_text_field(wp_unslash($_POST['action'] ?? 'unknown'));
            $ip = $this->get_client_ip();
            // AJAX request logged
        }
        
        // Rate limiting check
        $this->check_rate_limit();
        
        // Enhanced nonce verification with proper sanitization
        if (!isset($_POST['nonce'])) {
            $this->log_security_event('missing_nonce', [
                'ip' => $this->get_client_ip(),
                'user_agent' => sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'] ?? '')),
                'endpoint' => sanitize_text_field(wp_unslash($_POST['action'] ?? 'unknown'))
            ]);
            wp_send_json_error(array(
                'message' => esc_html__('Security verification required', 'kds-report-for-orderable')
            ));
        }
        
        $nonce = sanitize_text_field(wp_unslash($_POST['nonce']));
        if (!wp_verify_nonce($nonce, 'kdsamref_nonce')) {
            $this->log_security_event('invalid_nonce', [
                'ip' => $this->get_client_ip(),
                'user_id' => get_current_user_id(),
                'nonce_provided' => sanitize_text_field(wp_unslash($_POST['nonce'])),
                'endpoint' => sanitize_text_field(wp_unslash($_POST['action'] ?? 'unknown'))
            ]);
            wp_send_json_error(array(
                'message' => esc_html__('Security check failed', 'kds-report-for-orderable')
            ));
        }

        // Enhanced user permission check with capability hierarchy
        $required_caps = [
            'manage_kdsamref_orders',
            'manage_woocommerce', 
            'shop_manager',
            'gestion_commandes',
            'order_manager',
            'administrator'
        ];
        
        $user_can_access = false;
        foreach ($required_caps as $cap) {
            if (current_user_can($cap)) {
                $user_can_access = true;
                break;
            }
        }
        
        if (!$user_can_access) {
            $this->log_security_event('insufficient_permissions', [
                'ip' => $this->get_client_ip(),
                'user_id' => get_current_user_id(),
                'user_roles' => wp_get_current_user()->roles ?? [],
                'endpoint' => sanitize_text_field(wp_unslash($_POST['action'] ?? 'unknown'))
            ]);
            wp_send_json_error(array(
                'message' => esc_html__('Insufficient permissions', 'kds-report-for-orderable')
            ));
        }
        
        // Additional security headers
        if (!headers_sent()) {
            header('X-Content-Type-Options: nosniff');
            header('X-Frame-Options: SAMEORIGIN');
            header('X-XSS-Protection: 1; mode=block');
        }
    }
    
    /**
     * Clear rate limit for development/testing
     */
    public function clear_rate_limit() {
        $ip = $this->get_client_ip();
        $key = 'kdsamref_rate_limit_' . md5($ip);
        delete_transient($key);
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // Rate limit cleared
        }
        
        wp_send_json_success([
            'message' => esc_html__('Rate limit cleared', 'kds-report-for-orderable')
        ]);
    }

    /**
     * Enhanced security helper functions
     */
    private function check_rate_limit() {
        // Temporarily disable rate limiting for development
        return;
        
        $ip = $this->get_client_ip();
        $key = 'kdsamref_rate_limit_' . md5($ip);
        $limit = 100; // requests per minute
        $window = 60; // seconds
        
        $current = get_transient($key);
        if ($current === false) {
            set_transient($key, 1, $window);
        } else {
            if ($current >= $limit) {
                $this->log_security_event('rate_limit_exceeded', [
                    'ip' => $ip,
                    'requests' => $current,
                    'limit' => $limit,
                    'window' => $window
                ]);
                wp_send_json_error(array(
                    'message' => esc_html__('Rate limit exceeded. Please wait before making more requests.', 'kds-report-for-orderable')
                ));
            }
            set_transient($key, $current + 1, $window);
        }
    }
    
    private function get_client_ip() {
        $ip_fields = ['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'];
        
        foreach ($ip_fields as $field) {
            if (!empty($_SERVER[$field])) {
                $ip = sanitize_text_field($_SERVER[$field]);
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                    return $ip;
                }
            }
        }
        
        return sanitize_text_field($_SERVER['REMOTE_ADDR'] ?? 'unknown');
    }
    
    private function log_security_event($event_type, $data = []) {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // Security event logged
        }
        
        // Store in database for security monitoring
        $security_log = get_option('kdsamref_security_log', []);
        $security_log[] = [
            'timestamp' => current_time('mysql'),
            'event_type' => $event_type,
            'data' => $data
        ];
        
        // Keep only last 1000 events
        if (count($security_log) > 1000) {
            $security_log = array_slice($security_log, -1000);
        }
        
        update_option('kdsamref_security_log', $security_log);
    }
    
    private function sanitize_payment_method($method) {
        $allowed_methods = ['cash', 'card', 'mobile'];
        $method = sanitize_text_field($method);
        
        if (!in_array($method, $allowed_methods)) {
            wp_send_json_error([
                'message' => esc_html__('Invalid payment method', 'kds-report-for-orderable')
            ]);
        }
        
        return $method;
    }
    
    private function sanitize_payment_details($details) {
        if (!is_array($details)) {
            return [];
        }
        
        $sanitized = [];
        
        // Sanitize numeric fields
        $numeric_fields = ['amount', 'cash_received', 'change'];
        foreach ($numeric_fields as $field) {
            if (isset($details[$field])) {
                $value = floatval($details[$field]);
                if ($value >= 0 && $value <= 999999.99) {
                    $sanitized[$field] = round($value, 2);
                }
            }
        }
        
        // Sanitize text fields
        $text_fields = ['method', 'transaction_id', 'processor', 'qr_code'];
        foreach ($text_fields as $field) {
            if (isset($details[$field])) {
                $sanitized[$field] = sanitize_text_field($details[$field]);
            }
        }
        
        return $sanitized;
    }
    
    private function validate_staff_id($staff_id) {
        $staff_id = intval($staff_id);
        
        if ($staff_id <= 0) {
            wp_send_json_error([
                'message' => esc_html__('Staff member selection is required', 'kds-report-for-orderable')
            ]);
        }
        
        // Verify staff exists and is active
        // Note: Using direct query for custom staff table - this is acceptable for custom tables
        global $wpdb;
        $staff_table = $wpdb->prefix . 'kdsamref_staff';
        $staff = $wpdb->get_row($wpdb->prepare(
            "SELECT id, name, role, is_active FROM {$staff_table} WHERE id = %d",
            $staff_id
        ));
        
        if (!$staff || !$staff->is_active) {
            wp_send_json_error([
                'message' => esc_html__('Invalid or inactive staff member', 'kds-report-for-orderable')
            ]);
        }
        
        return $staff_id;
    }
    
    private function validate_order_items($raw_items) {
        if (!is_array($raw_items) || empty($raw_items)) {
            return [];
        }
        
        $validated_items = [];
        
        foreach ($raw_items as $item) {
            if (!is_array($item)) continue;
            
            // Validate required fields
            $product_id = intval($item['id'] ?? 0);
            $quantity = intval($item['quantity'] ?? 0);
            $price = floatval($item['price'] ?? 0);
            
            if ($product_id <= 0 || $quantity <= 0 || $price < 0) {
                continue; // Skip invalid items
            }
            
            // Verify product exists
            $product = wc_get_product($product_id);
            if (!$product || !$product->exists()) {
                continue;
            }
            
            // Sanitize item data
            $validated_item = [
                'id' => $product_id,
                'name' => sanitize_text_field($item['name'] ?? $product->get_name()),
                'price' => round($price, 2),
                'quantity' => min(999, $quantity), // Max 999 quantity
                'total' => round($price * $quantity, 2)
            ];
            
            // Validate options if present
            if (isset($item['options']) && is_array($item['options'])) {
                $validated_item['options'] = $this->sanitize_product_options($item['options']);
            }
            
            $validated_items[] = $validated_item;
        }
        
        return $validated_items;
    }
    
    private function sanitize_product_options($options) {
        $sanitized = [];
        
        foreach ($options as $key => $value) {
            $clean_key = sanitize_key($key);
            
            if (is_array($value)) {
                $sanitized[$clean_key] = array_map('sanitize_text_field', $value);
            } else {
                $sanitized[$clean_key] = sanitize_text_field($value);
            }
        }
        
        return $sanitized;
    }
    
    private function validate_business_rules($items, $payment_method, $payment_details) {
        // Check minimum order value
        $min_order_value = floatval(get_option('kdsamref_min_order_value', 0));
        if ($min_order_value > 0) {
            $order_total = array_sum(array_column($items, 'total'));
            if ($order_total < $min_order_value) {
                wp_send_json_error([
                    'message' => sprintf(
                        /* translators: %s: minimum order value */
                        __('Minimum order value is %s', 'kds-report-for-orderable'),
                        wc_price($min_order_value)
                    )
                ]);
            }
        }
        
        // Validate cash payment
        if ($payment_method === 'cash') {
            $cash_received = floatval($payment_details['cash_received'] ?? 0);
            $amount_due = floatval($payment_details['amount'] ?? 0);
            
            if ($cash_received < $amount_due) {
                wp_send_json_error([
                    'message' => esc_html__('Insufficient cash received', 'kds-report-for-orderable')
                ]);
            }
        }
    }
    
    private function is_store_open() {
        // Check if store hours functionality is enabled
        $enable_store_hours = get_option('kdsamref_enable_store_hours', false);
        if (!$enable_store_hours) {
            return true; // Always open if not configured
        }
        
        $current_time = current_time('Hi'); // Format: HHMM
        $current_day = strtolower(current_time('l')); // monday, tuesday, etc.
        
        $store_hours = get_option('kdsamref_store_hours', []);
        
        if (empty($store_hours[$current_day])) {
            return false; // Closed if no hours set for today
        }
        
        $today_hours = $store_hours[$current_day];
        $open_time = str_replace(':', '', $today_hours['open'] ?? '0000');
        $close_time = str_replace(':', '', $today_hours['close'] ?? '2359');
        
        return ($current_time >= $open_time && $current_time <= $close_time);
    }
    
    /**
     * Check if user can access kdsamref orders
     */
    private function user_can_access_kdsamref_orders() {
        return current_user_can('manage_kdsamref_orders') || 
               current_user_can('manage_woocommerce') || 
               current_user_can('shop_manager') || 
               current_user_can('gestion_commandes') || 
               current_user_can('order_manager') ||
               current_user_can('administrator');
    }

    /**
     * HTTP request helper using WordPress HTTP API
     */
    private function make_http_request($url, $method = 'GET', $params = array(), $headers = array()) {
        $args = array(
            'method' => strtoupper($method),
            'timeout' => 20,
            'headers' => $headers,
        );
        
        if (strtoupper($method) === 'POST') {
            $args['body'] = $params;
        }
        
        $response = wp_remote_request($url, $args);
        
        if (is_wp_error($response)) {
            return array('ok' => false, 'error' => $response->get_error_message());
        }
        
        $code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if ($code >= 200 && $code < 300) {
            return array('ok' => true, 'data' => $data);
        }
        
        $msg = isset($data['error']['message']) ? $data['error']['message'] : ('HTTP ' . $code);
        return array('ok' => false, 'error' => $msg);
    }

    /**
     * Get orders via AJAX
     */
    public function get_orders() {
        $this->verify_request();

        $status = isset($_POST['status']) ? sanitize_text_field($_POST['status']) : 'any';
        $limit = isset($_POST['limit']) ? intval($_POST['limit']) : 50;
        $delivery_type = isset($_POST['delivery_type']) ? sanitize_text_field($_POST['delivery_type']) : '';

        $order_manager = new KDSAMREF_Order_Manager();

        if (!empty($delivery_type)) {
            $orders = $order_manager->get_orders_by_delivery_type($delivery_type, $limit);
        } else {
            $orders = $order_manager->get_orders($status, $limit);
        }

        wp_send_json_success(array(
            'orders' => $orders,
            'count' => count($orders),
            'timestamp' => current_time('timestamp')
        ));
    }

    /**
     * Update order status via AJAX
     */
    public function update_order_status() {
        $this->verify_request();

        $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;
        $new_status = isset($_POST['new_status']) ? sanitize_text_field($_POST['new_status']) : '';
        $note = isset($_POST['note']) ? sanitize_textarea_field($_POST['note']) : '';

        if (defined('WP_DEBUG') && WP_DEBUG) {
            // Update order status called
        }

        if (!$order_id || !$new_status) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // Invalid parameters
            }
            wp_send_json_error(array(
                'message' => __('Invalid parameters', 'kds-report-for-orderable')
            ));
        }

        $order_manager = new KDSAMREF_Order_Manager();
        $result = $order_manager->update_order_status($order_id, $new_status);

        if (defined('WP_DEBUG') && WP_DEBUG) {
            // Update order status result
        }

        if ($result) {
            // Add custom note if provided
            if (!empty($note)) {
                $order_manager->add_order_note($order_id, $note);
            }

            // Get updated order data
            $order = wc_get_order($order_id);
            $updated_order = $order_manager->format_order_data($order);

            if (defined('WP_DEBUG') && WP_DEBUG) {
                // Order status updated successfully
            }
            wp_send_json_success(array(
                'message' => esc_html__('Order status updated successfully', 'kds-report-for-orderable'),
                'order' => $updated_order
            ));
        } else {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // Failed to update order status
            }
            wp_send_json_error(array(
                'message' => esc_html__('Failed to update order status', 'kds-report-for-orderable')
            ));
        }
    }

    /**
     * Get order statistics via AJAX
     */
    public function get_order_stats() {
        $this->verify_request();

        $order_manager = new KDSAMREF_Order_Manager();
        $stats = $order_manager->get_order_statistics();

        wp_send_json_success(array(
            'stats' => $stats,
            'timestamp' => current_time('timestamp')
        ));
    }

    /**
     * Add order note via AJAX
     */
    public function add_order_note() {
        $this->verify_request();

        // Check if user can add order notes
        if (!current_user_can('manage_woocommerce') && !current_user_can('shop_manager') && !current_user_can('gestion_commandes') && !current_user_can('order_manager')) {
            wp_send_json_error(array(
                'message' => esc_html__('Permission denied - Cannot add order notes', 'kds-report-for-orderable')
            ));
        }

        $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;
        $note = isset($_POST['note']) ? sanitize_textarea_field($_POST['note']) : '';
        $is_customer_note = isset($_POST['is_customer_note']) ? (bool) $_POST['is_customer_note'] : false;

        if (!$order_id || !$note) {
            wp_send_json_error(array(
                'message' => __('Invalid parameters', 'kds-report-for-orderable')
            ));
        }

        $order_manager = new KDSAMREF_Order_Manager();
        $result = $order_manager->add_order_note($order_id, $note, $is_customer_note);

        if ($result) {
            wp_send_json_success(array(
                'message' => __('Note added successfully', 'kds-report-for-orderable')
            ));
        } else {
            wp_send_json_error(array(
                'message' => esc_html__('Failed to add note', 'kds-report-for-orderable')
            ));
        }
    }

    /**
     * Get single order via AJAX
     */
    public function get_single_order() {
        $this->verify_request();

        // Check if user can view orders
        if (!current_user_can('manage_woocommerce') && !current_user_can('shop_manager') && !current_user_can('gestion_commandes') && !current_user_can('order_manager')) {
            wp_send_json_error(array(
                'message' => esc_html__('Permission denied - Cannot view order details', 'kds-report-for-orderable')
            ));
        }

        $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;

        if (!$order_id) {
            wp_send_json_error(array(
                'message' => esc_html__('Invalid order ID', 'kds-report-for-orderable')
            ));
        }

        $order = wc_get_order($order_id);
        
        if (!$order) {
            wp_send_json_error(array(
                'message' => __('Order not found', 'kds-report-for-orderable')
            ));
        }

        $order_manager = new KDSAMREF_Order_Manager();
        $order_data = $order_manager->format_order_data($order);

        wp_send_json_success(array(
            'order' => $order_data
        ));
    }

    /**
     * Search orders via AJAX
     * Uses meta_query for customer name search - necessary for restaurant functionality
     * Performance optimized with limit parameter and indexed meta keys
     */
    public function search_orders() {
        $this->verify_request();

        // Check if user can view orders
        if (!current_user_can('manage_woocommerce') && !current_user_can('shop_manager') && !current_user_can('gestion_commandes') && !current_user_can('order_manager')) {
            wp_send_json_error(array(
                'message' => esc_html__('Permission denied - Cannot search orders', 'kds-report-for-orderable')
            ));
        }

        $search_term = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '';
        $limit = isset($_POST['limit']) ? absint($_POST['limit']) : 50;

        if (empty($search_term)) {
            wp_send_json_error(array(
                'message' => esc_html__('Search term is required', 'kds-report-for-orderable')
            ));
        }

        $args = array(
            'limit' => $limit,
            'orderby' => 'date',
            'order' => 'DESC',
            'return' => 'objects',
            // Meta query necessary for customer name search functionality
            // Limited by $limit parameter to prevent performance issues
            'meta_query' => array(
                'relation' => 'OR',
                array(
                    'key' => '_billing_first_name',
                    'value' => $search_term,
                    'compare' => 'LIKE'
                ),
                array(
                    'key' => '_billing_last_name',
                    'value' => $search_term,
                    'compare' => 'LIKE'
                ),
                array(
                    'key' => '_billing_phone',
                    'value' => $search_term,
                    'compare' => 'LIKE'
                )
            )
        );

        // Also search by order number
        if (is_numeric($search_term)) {
            unset($args['meta_query']);
            $args['orderby'] = 'ID';
            $args['include'] = array($search_term);
        }

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

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

        wp_send_json_success(array(
            'orders' => $formatted_orders,
            'count' => count($formatted_orders),
            'search_term' => $search_term
        ));
    }

    /**
     * Update delivery information via AJAX
     */
    public function update_delivery_info() {
        $this->verify_request();

        // Check if user can manage orders
        if (!current_user_can('manage_woocommerce') && !current_user_can('shop_manager') && !current_user_can('gestion_commandes') && !current_user_can('order_manager')) {
            wp_send_json_error(array(
                'message' => esc_html__('Permission denied - Cannot update delivery info', 'kds-report-for-orderable')
            ));
        }

        $order_id = isset($_POST['order_id']) ? absint($_POST['order_id']) : 0;
        $delivery_type = isset($_POST['delivery_type']) ? sanitize_text_field(wp_unslash($_POST['delivery_type'])) : '';
        $table_number = isset($_POST['table_number']) ? sanitize_text_field(wp_unslash($_POST['table_number'])) : '';
        $pickup_time = isset($_POST['pickup_time']) ? sanitize_text_field(wp_unslash($_POST['pickup_time'])) : '';
        $special_instructions = isset($_POST['special_instructions']) ? sanitize_textarea_field(wp_unslash($_POST['special_instructions'])) : '';

        if (!$order_id) {
            wp_send_json_error(array(
                'message' => esc_html__('Invalid order ID', 'kds-report-for-orderable')
            ));
        }

        $order = wc_get_order($order_id);
        
        if (!$order) {
            wp_send_json_error(array(
                'message' => __('Order not found', 'kds-report-for-orderable')
            ));
        }

        // Update meta fields
        if ($delivery_type) {
            update_post_meta($order_id, '_kdsamref_delivery_type', $delivery_type);
        }
        
        if ($table_number) {
            update_post_meta($order_id, '_kdsamref_table_number', $table_number);
        }
        
        if ($pickup_time) {
            update_post_meta($order_id, '_kdsamref_pickup_time', $pickup_time);
        }
        
        if ($special_instructions) {
            update_post_meta($order_id, '_kdsamref_special_instructions', $special_instructions);
        }

        // Get updated order data
        $order_manager = new KDSAMREF_Order_Manager();
        $updated_order = $order_manager->format_order_data($order);

        wp_send_json_success(array(
            'message' => esc_html__('Delivery information updated successfully', 'kds-report-for-orderable'),
            'order' => $updated_order
        ));
    }

    /**
     * Get orders for specific time range - Updated to use WordPress timezone
     */
    public function get_orders_by_date_range() {
        $this->verify_request();

        // Check if user can view orders
        if (!$this->user_can_access_kdsamref_orders()) {
            wp_die(esc_html__('Permission denied', 'kds-report-for-orderable'));
        }

        // Get request parameters with proper sanitization
        $start_date = isset($_POST['start_date']) ? sanitize_text_field(wp_unslash($_POST['start_date'])) : '';
        $end_date = isset($_POST['end_date']) ? sanitize_text_field(wp_unslash($_POST['end_date'])) : '';
        $limit = isset($_POST['limit']) ? absint($_POST['limit']) : 100;
        $date_filter_type = isset($_POST['date_filter_type']) ? sanitize_text_field(wp_unslash($_POST['date_filter_type'])) : 'created';
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // AJAX request parameters logged
        }
        
        if (empty($start_date) || empty($end_date)) {
            wp_send_json_error(esc_html__('Invalid date parameters', 'kds-report-for-orderable'));
        }
        
        // Validate dates
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $start_date) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $end_date)) {
            wp_send_json_error(esc_html__('Invalid date format', 'kds-report-for-orderable'));
        }
        
        // Get WordPress timezone for proper 24h cycle handling
        $wp_timezone = wp_timezone();
        $current_wp_time = new DateTime(current_time('Y-m-d H:i:s'), $wp_timezone);
        
        // Create start and end datetime objects in WordPress timezone
        $start_datetime = new DateTime($start_date . ' 00:00:00', $wp_timezone);
        $end_datetime = new DateTime($end_date . ' 23:59:59', $wp_timezone);
        
        // Convert to UTC for WooCommerce query (WC stores dates in UTC)
        $start_datetime_utc = clone $start_datetime;
        $end_datetime_utc = clone $end_datetime;
        $start_datetime_utc->setTimezone(new DateTimeZone('UTC'));
        $end_datetime_utc->setTimezone(new DateTimeZone('UTC'));
        
        // Use WooCommerce date range format
        $date_range = $start_datetime_utc->format('Y-m-d H:i:s') . '...' . $end_datetime_utc->format('Y-m-d H:i:s');
        
        // Debug data for frontend
        $debug_24h = array(
            'requested_date' => $start_date,
            'wp_range' => $start_datetime->format('Y-m-d H:i:s') . ' - ' . $end_datetime->format('Y-m-d H:i:s'),
            'utc_range' => $start_datetime_utc->format('Y-m-d H:i:s') . ' - ' . $end_datetime_utc->format('Y-m-d H:i:s'),
            'current_wp_time' => $current_wp_time->format('Y-m-d H:i:s'),
            'timezone_offset_hours' => $wp_timezone->getOffset($current_wp_time) / 3600,
            'date_filter_type' => $date_filter_type
        );
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // Date filter type logged
        }
        
        // Build query arguments based on filter type
        // Use compatibility-aware statuses (includes Orderable + custom statuses)
        if (!class_exists('KDSAMREF_Compatibility_Manager')) {
            require_once KDSAMREF_PLUGIN_PATH . 'includes/class-kdsamref-compatibility-manager.php';
        }
        $valid_statuses = KDSAMREF_Compatibility_Manager::get_valid_order_statuses();
        $args = array(
            'limit' => $limit,
            'orderby' => 'date',
            'order' => 'DESC',
            'return' => 'objects',
            'type' => 'shop_order',
            'status' => $valid_statuses,
        );
        
        if ($date_filter_type === 'created') {
            // Filter by order creation date
            // Use WordPress timezone directly for more accurate filtering
            $args['date_created'] = $start_datetime->format('Y-m-d H:i:s') . '...' . $end_datetime->format('Y-m-d H:i:s');
            // Using order creation date filter
        } else {
            // Filter by delivery date (Orderable meta fields)
            // First get all orders, then filter by delivery date
            $args = array(
                'limit' => -1, // Get all orders first
                'orderby' => 'date',
                'order' => 'DESC',
                'return' => 'objects',
                'type' => 'shop_order',
                'status' => $valid_statuses,
            );
            
            // Using delivery date filter
        }
        
        // Debug: Log query args (sanitized)
        if (defined('WP_DEBUG') && WP_DEBUG) {
            $safe_args = array(
                'limit' => $args['limit'],
                'orderby' => $args['orderby'],
                'order' => $args['order'],
                'type' => $args['type'],
                'status_count' => count($args['status'])
            );
            if (isset($args['date_created'])) {
                $safe_args['date_created'] = $args['date_created'];
            }
            // WC query args and date range logged
        }
        
        $orders = wc_get_orders($args);
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // Orders found count logged
        }
        
        // If filtering by delivery date, filter the orders manually
        if ($date_filter_type === 'delivery') {
            $filtered_orders = array();
        $orderable_fields = array(
                'orderable_delivery_date',
                '_orderable_delivery_date', 
                '_delivery_date',
                'orderable_pickup_date',
                '_orderable_pickup_date',
                '_pickup_date',
                // Additional possible field names
                'delivery_date',
                'pickup_date',
                '_orderable_order_date',
                'orderable_order_date',
                '_orderable_scheduled_date',
                'orderable_scheduled_date',
                '_wc_delivery_date',
                '_wc_pickup_date',
                'delivery_time',
                'pickup_time',
                '_orderable_delivery_time',
                '_orderable_pickup_time'
            );
            
            foreach ($orders as $order) {
                $order_id = $order->get_id();
                $delivery_date = null;
                $normalized_date = null;
                $meta_value = null;
                
                foreach ($orderable_fields as $field) {
                    $meta_value = get_post_meta($order_id, $field, true);
                    if (!empty($meta_value)) {
                        $delivery_date = $meta_value;
                        // Order delivery date found
                        
                        // Try to normalize the date format
                        $normalized_date = $this->normalize_orderable_date($delivery_date);
                        if ($normalized_date) {
                            $delivery_date = $normalized_date;
                            // Order date normalized
                        }
                        break;
                    }
                }
                
                // Debug: Show all meta fields for first few orders
                if ($order_id <= 33285) { // Only for first few orders to avoid spam
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                        $all_meta = get_post_meta($order_id);
                        $orderable_meta = array();
                        foreach ($all_meta as $key => $value) {
                            if (strpos($key, 'orderable') !== false || strpos($key, 'delivery') !== false || strpos($key, 'pickup') !== false) {
                                $orderable_meta[$key] = $value;
                            }
                        }
                        if (!empty($orderable_meta)) {
                            $safe_meta = array();
                            foreach ($orderable_meta as $key => $value) {
                                // Only log non-sensitive fields
                                if (strpos($key, 'password') === false && 
                                    strpos($key, 'token') === false && 
                                    strpos($key, 'secret') === false &&
                                    strpos($key, 'key') === false) {
                                    $safe_meta[$key] = $value;
                                }
                            }
                            // Safe Orderable meta fields logged
                        }
                    }
                }
                
                // Order final delivery date logged
                
                // If delivery date matches the requested date, include this order
                $date_matches = false;
                
                // Exact match
                if ($delivery_date && $delivery_date === $start_date) {
                    $date_matches = true;
                    // Exact date match
                }
                // Try normalized comparison
                elseif ($normalized_date && $normalized_date === $start_date) {
                    $date_matches = true;
                    // Normalized date match
                }
                // Try partial match (in case there's extra time info)
                elseif ($delivery_date && strpos($delivery_date, $start_date) === 0) {
                    $date_matches = true;
                    // Partial date match
                }
                
                if ($date_matches) {
                    $filtered_orders[] = $order;
                    // Order included - delivery date matches
                } else {
                    // Order excluded - delivery date doesn't match
                }
            }
            $orders = $filtered_orders;
            // After delivery date filtering
            
            // Apply limit after filtering
            if ($limit > 0 && count($orders) > $limit) {
                $orders = array_slice($orders, 0, $limit);
                // Applied limit, final count
            }
        }

        $formatted_orders = array();

        $order_manager = new KDSAMREF_Order_Manager();
        
        foreach ($orders as $order) {
            $order_data = $order_manager->format_order_data($order);
            if ($order_data) {
                $formatted_orders[] = $order_data;
                
                // Debug: Log first few orders with their actual dates
                if (defined('WP_DEBUG') && WP_DEBUG && count($formatted_orders) <= 3) {
                    // Order details logged
                }
            }
        }
        
        // Debug: Log final result with date analysis
        // Final formatted orders count
        if (count($formatted_orders) > 0) {
            $order_dates = array();
            foreach ($formatted_orders as $order) {
                $order_dates[] = array(
                    'id' => $order['id'],
                    'date_created' => $order['date_created'],
                    'date_created_wp' => $order['date_created_wp'],
                    'date_created_raw' => $order['date_created_raw']
                );
            }
            // Order dates analysis
        }

        wp_send_json_success(array(
            'orders' => $formatted_orders,
            'count' => count($formatted_orders),
            'date_filter_type' => $date_filter_type,
            'date_range' => array(
                'start' => $start_date,
                'end' => $end_date,
                'wp_timezone' => $wp_timezone->getName(),
                'current_wp_time' => current_time('Y-m-d H:i:s'),
                'start_wp_datetime' => $start_datetime->format('Y-m-d H:i:s T'),
                'end_wp_datetime' => $end_datetime->format('Y-m-d H:i:s T'),
                'start_query_datetime' => $start_datetime_utc->format('Y-m-d H:i:s T'),
                'end_query_datetime' => $end_datetime_utc->format('Y-m-d H:i:s T'),
                // 24h cycle debug
                'debug_24h' => array(
                    'requested_date' => $start_date,
                    'wp_range' => $start_datetime->format('Y-m-d H:i:s T') . ' to ' . $end_datetime->format('Y-m-d H:i:s T'),
                    'query_range' => $start_datetime_utc->format('Y-m-d H:i:s T') . ' to ' . $end_datetime_utc->format('Y-m-d H:i:s T'),
                    'current_wp_time' => current_time('Y-m-d H:i:s'),
                    'timezone_offset_hours' => ($wp_timezone->getOffset(new DateTime()) / 3600)
                )
            )
        ));
    }
    

    /**
     * Bulk update order statuses
     */
    public function bulk_update_orders() {
        $this->verify_request();

        // Check if user can manage orders
        if (!current_user_can('manage_woocommerce') && !current_user_can('shop_manager') && !current_user_can('gestion_commandes') && !current_user_can('order_manager')) {
            wp_send_json_error(array(
                'message' => __('Permission denied - Cannot bulk update orders', 'kds-report-for-orderable')
            ));
        }

        $order_ids = isset($_POST['order_ids']) ? array_map('intval', $_POST['order_ids']) : array();
        $new_status = isset($_POST['new_status']) ? sanitize_text_field($_POST['new_status']) : '';

        if (empty($order_ids) || !$new_status) {
            wp_send_json_error(array(
                'message' => __('Invalid parameters', 'kds-report-for-orderable')
            ));
        }

        $order_manager = new KDSAMREF_Order_Manager();
        $success_count = 0;
        $error_count = 0;

        foreach ($order_ids as $order_id) {
            $result = $order_manager->update_order_status($order_id, $new_status);
            if ($result) {
                $success_count++;
            } else {
                $error_count++;
            }
        }

        wp_send_json_success(array(
            'message' => sprintf(
                /* translators: 1: number of successful orders, 2: number of errors */
                esc_html__('%1$d orders updated successfully, %2$d errors', 'kds-report-for-orderable'),
                esc_html($success_count),
                esc_html($error_count)
            ),
            'success_count' => $success_count,
            'error_count' => $error_count
        ));
    }
    


    /**
     * Get settings via AJAX
     */
    public function get_settings() {
        $this->verify_request();
        
        $admin = new KDSAMREF_Admin();
        $settings = $admin->get_all_settings();
        
        wp_send_json_success($settings);
    }
    
    /**
     * Save custom status via AJAX
     */
    public function save_custom_status() {
        // Verify nonce for custom status
        if (!isset($_POST['nonce'])) {
            wp_send_json_error(array(
                'message' => __('Security token missing', 'kds-report-for-orderable')
            ));
        }
        
        $nonce = sanitize_text_field(wp_unslash($_POST['nonce']));
        if (!wp_verify_nonce($nonce, 'kdsamref_custom_status')) {
            wp_send_json_error(array(
                'message' => __('Security check failed', 'kds-report-for-orderable')
            ));
        }
        
        // Check user permissions
        if (!current_user_can('manage_woocommerce') && !current_user_can('administrator')) {
            wp_send_json_error(array(
                'message' => __('Permission denied', 'kds-report-for-orderable')
            ));
        }
        
        $status_slug = isset($_POST['status_slug']) ? sanitize_title($_POST['status_slug']) : '';
        $status_label = isset($_POST['status_label']) ? sanitize_text_field($_POST['status_label']) : '';
        $status_color = isset($_POST['status_color']) ? sanitize_hex_color($_POST['status_color']) : '#007cba';
        $status_icon = isset($_POST['status_icon']) ? sanitize_text_field($_POST['status_icon']) : '';
        $status_icon_family = isset($_POST['status_icon_family']) ? sanitize_text_field($_POST['status_icon_family']) : 'fontawesome';
        $status_enabled = isset($_POST['status_enabled']) ? 1 : 0;
        $status_type = isset($_POST['status_type']) ? sanitize_text_field($_POST['status_type']) : 'custom';
        $edit_slug = isset($_POST['edit_slug']) ? sanitize_title($_POST['edit_slug']) : '';
        
        // Validation
        if (empty($status_slug) || empty($status_label)) {
            wp_send_json_error(array(
                'message' => esc_html__('Please fill in all required fields', 'kds-report-for-orderable')
            ));
        }
        
        // Validate slug format for custom statuses
        if ($status_type === 'custom') {
            if (!preg_match('/^[a-z0-9_-]+$/', $status_slug)) {
                wp_send_json_error(array(
                    'message' => esc_html__('Slug can only contain lowercase letters, numbers, underscores and hyphens', 'kds-report-for-orderable')
                ));
            }
            
            if (strlen($status_slug) < 2 || strlen($status_slug) > 20) {
                wp_send_json_error(array(
                    'message' => esc_html__('Slug must be between 2-20 characters', 'kds-report-for-orderable')
                ));
            }
        }
        
        // Validate label length
        if (strlen($status_label) > 50) {
            wp_send_json_error(array(
                'message' => esc_html__('Status name cannot exceed 50 characters', 'kds-report-for-orderable')
            ));
        }
        
        $admin = new KDSAMREF_Admin();
        $settings = $admin->get_all_settings();
        $custom_statuses = $settings['custom_statuses'] ?? array();
        
        // Check if slug already exists (for new statuses)
        if (empty($edit_slug) && isset($custom_statuses[$status_slug])) {
            wp_send_json_error(array(
                'message' => esc_html__('A status with this slug already exists', 'kds-report-for-orderable')
            ));
        }
        
        // Prepare status data
        $status_data = array(
            'label' => $status_label,
            'color' => $status_color,
            'icon' => $status_icon,
            'icon_family' => $status_icon_family,
            'enabled' => $status_enabled,
            'status_type' => $status_type,
            'source' => 'custom'
        );
        
        // Update or add status
        if (!empty($edit_slug) && $edit_slug !== $status_slug) {
            // Renaming existing status
            if (isset($custom_statuses[$edit_slug])) {
                unset($custom_statuses[$edit_slug]);
            }
        }
        
        $custom_statuses[$status_slug] = $status_data;
        
        // Save settings
        $settings['custom_statuses'] = $custom_statuses;
        $result = $admin->update_settings($settings);
        
        // Debug: Log the save operation (sanitized)
        // Saving custom status and result
        
        // Only log full settings in debug mode
        if (defined('WP_DEBUG') && WP_DEBUG) {
            $safe_settings = array();
            foreach ($settings 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_settings[$key] = $value;
                }
            }
            // Safe settings before save
        }
        
        // Always return success (update_settings handles false returns properly)
        wp_send_json_success(array(
            'message' => esc_html__('Status saved successfully', 'kds-report-for-orderable'),
            'status' => $status_data
        ));
    }
    
    /**
     * Delete custom status via AJAX
     */
    public function delete_custom_status() {
        // Verify nonce for custom status
        if (!isset($_POST['nonce'])) {
            wp_send_json_error(array(
                'message' => __('Security token missing', 'kds-report-for-orderable')
            ));
        }
        
        $nonce = sanitize_text_field(wp_unslash($_POST['nonce']));
        if (!wp_verify_nonce($nonce, 'kdsamref_custom_status')) {
            wp_send_json_error(array(
                'message' => __('Security check failed', 'kds-report-for-orderable')
            ));
        }
        
        // Check user permissions
        if (!current_user_can('manage_woocommerce') && !current_user_can('administrator')) {
            wp_send_json_error(array(
                'message' => __('Permission denied', 'kds-report-for-orderable')
            ));
        }
        
        $status_slug = isset($_POST['status_slug']) ? sanitize_title($_POST['status_slug']) : '';
        
        if (empty($status_slug)) {
            wp_send_json_error(array(
                'message' => __('Invalid status slug', 'kds-report-for-orderable')
            ));
        }
        
        $admin = new KDSAMREF_Admin();
        $settings = $admin->get_all_settings();
        $custom_statuses = $settings['custom_statuses'] ?? array();
        
        // Check if status exists and is not auto-synced
        if (!isset($custom_statuses[$status_slug])) {
            wp_send_json_error(array(
                'message' => __('Status not found', 'kds-report-for-orderable')
            ));
        }
        
        $status_data = $custom_statuses[$status_slug];
        if (isset($status_data['source']) && $status_data['source'] === 'orderable_pro') {
            wp_send_json_error(array(
                'message' => esc_html__('Cannot delete auto-synced status', 'kds-report-for-orderable')
            ));
        }
        
        // Remove status
        unset($custom_statuses[$status_slug]);
        
        // Save settings
        $settings['custom_statuses'] = $custom_statuses;
        $result = $admin->update_settings($settings);
        
        // Always return success for delete operations (update_settings handles false returns properly)
        wp_send_json_success(array(
            'message' => esc_html__('Status deleted successfully', 'kds-report-for-orderable')
        ));
    }
    
    /**
     * Get custom statuses via AJAX
     */
    public function get_custom_statuses() {
        // Verify nonce for custom status
        if (!isset($_POST['nonce'])) {
            wp_send_json_error(array(
                'message' => __('Security token missing', 'kds-report-for-orderable')
            ));
        }
        
        $nonce = sanitize_text_field(wp_unslash($_POST['nonce']));
        if (!wp_verify_nonce($nonce, 'kdsamref_custom_status')) {
            wp_send_json_error(array(
                'message' => __('Security check failed', 'kds-report-for-orderable')
            ));
        }
        
        // Check user permissions
        if (!current_user_can('manage_woocommerce') && !current_user_can('administrator')) {
            wp_send_json_error(array(
                'message' => __('Permission denied', 'kds-report-for-orderable')
            ));
        }
        
        $admin = new KDSAMREF_Admin();
        $settings = $admin->get_all_settings();
        $custom_statuses = $settings['custom_statuses'] ?? array();
        
        wp_send_json_success(array(
            'statuses' => $custom_statuses
        ));
    }

    /**
     * Toggle custom status enabled/disabled
     */
    public function toggle_custom_status() {
        // Verify nonce for custom status
        if (!isset($_POST['nonce'])) {
            wp_send_json_error(array(
                'message' => __('Security token missing', 'kds-report-for-orderable')
            ));
        }
        
        $nonce = sanitize_text_field(wp_unslash($_POST['nonce']));
        if (!wp_verify_nonce($nonce, 'kdsamref_custom_status')) {
            wp_send_json_error(array(
                'message' => __('Security check failed', 'kds-report-for-orderable')
            ));
        }
        
        // Check user permissions
        if (!current_user_can('manage_woocommerce') && !current_user_can('administrator')) {
            wp_send_json_error(array(
                'message' => __('Permission denied', 'kds-report-for-orderable')
            ));
        }
        
        $status_slug = isset($_POST['status_slug']) ? sanitize_title($_POST['status_slug']) : '';
        $enabled = isset($_POST['enabled']) ? sanitize_text_field($_POST['enabled']) : '1';
        
        if (empty($status_slug)) {
            wp_send_json_error(array(
                'message' => __('Invalid status slug', 'kds-report-for-orderable')
            ));
        }
        
        $admin = new KDSAMREF_Admin();
        $settings = $admin->get_all_settings();
        $custom_statuses = $settings['custom_statuses'] ?? array();
        
        // Check if status exists
        if (!isset($custom_statuses[$status_slug])) {
            wp_send_json_error(array(
                'message' => __('Status not found', 'kds-report-for-orderable')
            ));
        }
        
        // Update the enabled status
        $custom_statuses[$status_slug]['enabled'] = ($enabled === '1') ? 1 : 0;
        
        // Save settings
        $settings['custom_statuses'] = $custom_statuses;
        $result = $admin->update_settings($settings);
        
        // Always return success (update_settings handles false returns properly)
        $action_text = ($enabled === '1') ? esc_html__('activated', 'kds-report-for-orderable') : esc_html__('deactivated', 'kds-report-for-orderable');
        wp_send_json_success(array(
            /* translators: %s: action text (activated/deactivated) */
            'message' => sprintf(esc_html__('Status %s successfully', 'kds-report-for-orderable'), esc_html($action_text))
        ));
    }

    /**
     * Sync Orderable Pro statuses via AJAX
     */
    public function sync_orderable_pro_statuses() {
        // Verify nonce for custom status
        if (!isset($_POST['nonce'])) {
            wp_send_json_error(array(
                'message' => __('Security token missing', 'kds-report-for-orderable')
            ));
        }
        
        $nonce = sanitize_text_field(wp_unslash($_POST['nonce']));
        if (!wp_verify_nonce($nonce, 'kdsamref_custom_status')) {
            wp_send_json_error(array(
                'message' => __('Security check failed', 'kds-report-for-orderable')
            ));
        }

        // Check if user can manage orders
        if (!current_user_can('manage_woocommerce') && !current_user_can('shop_manager') && !current_user_can('gestion_commandes') && !current_user_can('order_manager')) {
            wp_send_json_error(array(
                'message' => __('Permission denied - Cannot sync statuses', 'kds-report-for-orderable')
            ));
        }

        $order_manager = new KDSAMREF_Order_Manager();
        $sync_result = $order_manager->sync_orderable_pro_statuses();

        if (is_array($sync_result) && isset($sync_result['success'])) {
            if ($sync_result['success']) {
                wp_send_json_success(array(
                    'message' => $sync_result['message']
                ));
            } else {
                wp_send_json_error(array(
                    'message' => $sync_result['message']
                ));
            }
        } else {
            // Fallback for old format
            if ($sync_result) {
                wp_send_json_success(array(
                    'message' => esc_html__('Statuses synced successfully', 'kds-report-for-orderable')
                ));
            } else {
                wp_send_json_error(array(
                    'message' => esc_html__('Failed to sync statuses', 'kds-report-for-orderable')
                ));
            }
        }
    }

    /**
     * Normalize Orderable date format to Y-m-d
     */
    private function normalize_orderable_date($date_string) {
        if (empty($date_string)) {
            return false;
        }
        
        // Normalizing date string
        
        // Try different date formats
        $formats = array(
            'Y-m-d',           // 2025-07-29
            'd/m/Y',           // 29/07/2025
            'd F Y',           // 29 juillet 2025
            'j F Y',           // 29 juillet 2025
            'Y-m-d H:i:s',     // 2025-07-29 19:00:00
            'd-m-Y',           // 29-07-2025
        );
        
        foreach ($formats as $format) {
            $date = DateTime::createFromFormat($format, $date_string);
            if ($date !== false) {
                $normalized = $date->format('Y-m-d');
                // Successfully normalized using format
                return $normalized;
            }
        }
        
        // If no format matches, try to extract date from French string
        if (preg_match('/(\d{1,2})\s+(janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre)\s+(\d{4})/i', $date_string, $matches)) {
            $month_map = array(
                'janvier' => 1, 'février' => 2, 'mars' => 3, 'avril' => 4,
                'mai' => 5, 'juin' => 6, 'juillet' => 7, 'août' => 8,
                'septembre' => 9, 'octobre' => 10, 'novembre' => 11, 'décembre' => 12
            );
            
            $day = intval($matches[1]);
            $month = $month_map[strtolower($matches[2])];
            $year = intval($matches[3]);
            
            $normalized = sprintf('%04d-%02d-%02d', $year, $month, $day);
            // Successfully normalized French date
            return $normalized;
        }
        
        // Failed to normalize date string
        return false;
    }

    /**
     * Get stock items for stock management
     */
    public function get_stock_items() {
        $this->verify_request();

        try {
            $stock_items = array();

            // Check if WooCommerce is active
            if (!class_exists('WooCommerce')) {
                wp_send_json_error(array(
                    'message' => esc_html__('WooCommerce is not active', 'kds-report-for-orderable')
                ));
                return;
            }

            // Get all published products, not just those with stock management enabled
            $args = array(
                'post_type' => 'product',
                'post_status' => 'publish',
                'posts_per_page' => -1
            );

            $products = get_posts($args);

            foreach ($products as $product) {
                $wc_product = wc_get_product($product->ID);
                if (!$wc_product) continue;

                $stock_quantity = $wc_product->get_stock_quantity();
                $stock_status = $wc_product->get_stock_status();
                $manage_stock = $wc_product->get_manage_stock();
                $price = $wc_product->get_price();
                $sku = $wc_product->get_sku();
                $categories = get_the_terms($product->ID, 'product_cat');
                $category_name = '';
                $parent_category = '';
                
                if ($categories) {
                    $category = $categories[0];
                    $category_name = $category->name;
                    
                    // Get parent category if exists
                    if ($category->parent > 0) {
                        $parent = get_term($category->parent, 'product_cat');
                        if ($parent && !is_wp_error($parent)) {
                            $parent_category = $parent->name;
                        }
                    }
                }

                // Determine status based on stock status and quantity
                $status = 'in-stock';
                if ($stock_status === 'outofstock') {
                    $status = 'out-of-stock';
                } elseif ($stock_status === 'onbackorder') {
                    $status = 'low-stock';
                } elseif ($manage_stock && $stock_quantity !== null) {
                    if ($stock_quantity === 0) {
                        $status = 'out-of-stock';
                    } elseif ($stock_quantity <= 5) {
                        $status = 'low-stock';
                    }
                }

                $stock_items[] = array(
                    'id' => $product->ID,
                    'name' => $product->post_title,
                    'sku' => $sku ?: 'SKU-' . $product->ID,
                    'category' => $category_name,
                    'parent_category' => $parent_category,
                    'price' => wc_price($price),
                    'quantity' => $stock_quantity !== null ? $stock_quantity : 0,
                    'status' => $status,
                    'stock_status' => $stock_status,
                    'manage_stock' => $manage_stock
                );
            }

            wp_send_json_success(array(
                'stock_items' => $stock_items
            ));

        } catch (Exception $e) {
            wp_send_json_error(array(
                'message' => esc_html__('Failed to load stock items', 'kds-report-for-orderable'),
                'error' => $e->getMessage()
            ));
        }
    }

    /**
     * Update stock quantity
     */
    public function update_stock_quantity() {
        $this->verify_request();

        try {
            $product_id = intval($_POST['product_id']);
            $new_quantity = intval($_POST['quantity']);
            $new_stock_status = sanitize_text_field($_POST['stock_status'] ?? '');

            if ($product_id <= 0) {
                wp_send_json_error(array(
                    'message' => esc_html__('Invalid product ID', 'kds-report-for-orderable')
                ));
            }

            if ($new_quantity < 0) {
                wp_send_json_error(array(
                    'message' => esc_html__('Quantity cannot be negative', 'kds-report-for-orderable')
                ));
            }

            // Check if WooCommerce is active
            if (!class_exists('WooCommerce')) {
                wp_send_json_error(array(
                    'message' => esc_html__('WooCommerce is not active', 'kds-report-for-orderable')
                ));
            }

            $product = wc_get_product($product_id);
            if (!$product) {
                wp_send_json_error(array(
                    'message' => esc_html__('Product not found', 'kds-report-for-orderable')
                ));
            }

            // Enable stock management if not already enabled
            if (!$product->get_manage_stock()) {
                $product->set_manage_stock(true);
            }

            // Update stock quantity
            $product->set_stock_quantity($new_quantity);
            
            // Update stock status if provided, otherwise determine based on quantity
            if (!empty($new_stock_status)) {
                $product->set_stock_status($new_stock_status);
            } else {
                // Auto-determine stock status based on quantity
                if ($new_quantity === 0) {
                    $product->set_stock_status('outofstock');
                } elseif ($new_quantity <= 5) {
                    $product->set_stock_status('onbackorder');
                } else {
                    $product->set_stock_status('instock');
                }
            }

            $product->save();

            // Get updated product data
            $stock_quantity = $product->get_stock_quantity();
            $stock_status = $product->get_stock_status();
            $manage_stock = $product->get_manage_stock();
            
            // Determine status for response
            $status = 'in-stock';
            if ($stock_status === 'outofstock') {
                $status = 'out-of-stock';
            } elseif ($stock_status === 'onbackorder') {
                $status = 'low-stock';
            } elseif ($manage_stock && $stock_quantity !== null) {
                if ($stock_quantity === 0) {
                    $status = 'out-of-stock';
                } elseif ($stock_quantity <= 5) {
                    $status = 'low-stock';
                }
            }

            wp_send_json_success(array(
                'message' => esc_html__('Stock updated successfully', 'kds-report-for-orderable'),
                'product_id' => $product_id,
                'new_quantity' => $stock_quantity,
                'new_status' => $status,
                'stock_status' => $stock_status,
                'manage_stock' => $manage_stock
            ));

        } catch (Exception $e) {
            wp_send_json_error(array(
                'message' => esc_html__('Failed to update stock', 'kds-report-for-orderable'),
                'error' => $e->getMessage()
            ));
        }
    }
    
}
