<?php
/**
 * Admin Class
 * 
 * Handles admin settings and configuration
 */

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

class KDSAMREF_Admin {

    /**
     * Constructor
     */
    public function __construct() {
        add_action('admin_init', array($this, 'init_settings'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_woocommerce_order_status_styles'));
        
        // Filter WooCommerce order actions to show only next steps
        add_filter('woocommerce_admin_order_actions', array($this, 'filter_order_actions'), 10, 2);
        
        // Removed duplicate AJAX handler - handled in KDSAMREF_Ajax_Handler class
    }

    /**
     * Initialize settings
     */
    public function init_settings() {
        // Register the consolidated settings option; UI is rendered via template.
        register_setting('kdsamref_settings', 'kdsamref_settings', array(
            'sanitize_callback' => array($this, 'sanitize_settings')
        ));
    }

    /**
     * Sanitize settings array for register_setting
     */
    public function sanitize_settings($input) {
        if (!is_array($input)) {
            return array();
        }
        $output = array();
        $map_bool = function($v){ return empty($v) ? 0 : 1; };
        $output['max_orders_limit'] = isset($input['max_orders_limit']) ? max(1, intval($input['max_orders_limit'])) : 100;
        $output['default_font_size'] = isset($input['default_font_size']) ? max(50, min(200, intval($input['default_font_size']))) : 100;
        $output['auto_refresh_interval'] = isset($input['auto_refresh_interval']) ? max(0, intval($input['auto_refresh_interval'])) : 15;
        $output['enable_notifications'] = $map_bool($input['enable_notifications'] ?? 1);
        $output['notification_sound'] = $map_bool($input['notification_sound'] ?? 1);
        $output['notification_volume'] = isset($input['notification_volume']) ? floatval($input['notification_volume']) : 0.3;
        $output['disable_refresh_notifications'] = $map_bool($input['disable_refresh_notifications'] ?? 0);
        $output['show_completed_orders'] = $map_bool($input['show_completed_orders'] ?? 1);
        $output['completed_orders_opacity'] = isset($input['completed_orders_opacity']) ? floatval($input['completed_orders_opacity']) : 0.8;
        $output['compact_mode'] = $map_bool($input['compact_mode'] ?? 0);
        $output['show_order_numbers'] = $map_bool($input['show_order_numbers'] ?? 1);
        $output['show_customer_names'] = $map_bool($input['show_customer_names'] ?? 1);
        $output['show_product_options'] = $map_bool($input['show_product_options'] ?? 1);
        $output['show_tips'] = $map_bool($input['show_tips'] ?? 1);
        $output['show_fees'] = $map_bool($input['show_fees'] ?? 1);
        $output['delivery_badge_color'] = sanitize_hex_color($input['delivery_badge_color'] ?? '#4ade80');
        $output['pickup_badge_color'] = sanitize_hex_color($input['pickup_badge_color'] ?? '#a78bfa');
        $output['dine_in_badge_color'] = sanitize_hex_color($input['dine_in_badge_color'] ?? '#60a5fa');
        $output['border_color_primary'] = sanitize_hex_color($input['border_color_primary'] ?? '#dee2e6');
        $output['border_color_secondary'] = sanitize_hex_color($input['border_color_secondary'] ?? '#e9ecef');
        $output['card_background_color'] = sanitize_hex_color($input['card_background_color'] ?? '#ffffff');
        $output['dashboard_background_color'] = sanitize_hex_color($input['dashboard_background_color'] ?? '#f8f9fa');
        // Arrays
        $output['status_order'] = array_map('sanitize_text_field', isset($input['status_order']) && is_array($input['status_order']) ? $input['status_order'] : array());
        $output['workflow_steps'] = array_map('sanitize_text_field', isset($input['workflow_steps']) && is_array($input['workflow_steps']) ? $input['workflow_steps'] : array());
        $output['custom_statuses'] = (isset($input['custom_statuses']) && is_array($input['custom_statuses'])) ? $this->sanitize_custom_statuses($input['custom_statuses']) : array();
        $output['status_colors'] = (isset($input['status_colors']) && is_array($input['status_colors'])) ? array_map('sanitize_hex_color', $input['status_colors']) : array();
        $output['status_labels'] = (isset($input['status_labels']) && is_array($input['status_labels'])) ? array_map('sanitize_text_field', $input['status_labels']) : array();
        return $output;
    }

    private function sanitize_custom_statuses($statuses) {
        $clean = array();
        foreach ($statuses as $slug => $data) {
            $slug = sanitize_key($slug);
            if (!$slug) { continue; }
            $clean[$slug] = array(
                'label' => sanitize_text_field($data['label'] ?? ''),
                'color' => sanitize_hex_color($data['color'] ?? '#007cba'),
                'enabled' => empty($data['enabled']) ? 0 : 1,
                'source' => sanitize_text_field($data['source'] ?? 'custom'),
                'status_type' => sanitize_text_field($data['status_type'] ?? 'custom'),
                'icon' => sanitize_text_field($data['icon'] ?? ''),
                'icon_family' => sanitize_text_field($data['icon_family'] ?? '')
            );
        }
        return $clean;
    }

    /**
     * General settings section callback
     */
    public function general_settings_callback() {
        echo '<p>' . esc_html__('Configure general KDS orders settings.', 'kds-report-for-orderable') . '</p>';
    }

    /**
     * Enqueue WooCommerce order status styles
     */
    public function enqueue_woocommerce_order_status_styles() {
        $screen = get_current_screen();
        
        // Only load on WooCommerce orders page (support both old and new screen IDs)
        if (!$screen || !in_array($screen->id, array('edit-shop_order', 'shop_order', 'woocommerce_page_wc-orders'))) {
            return;
        }

        // Try different option names for custom statuses
        $custom_statuses = get_option('kdsamref_custom_statuses', array());
        
        if (empty($custom_statuses)) {
            // Try alternative option name
            $settings = get_option('kdsamref_settings', array());
            
            if (!empty($settings) && isset($settings['custom_statuses'])) {
                $custom_statuses = $settings['custom_statuses'];
            }
        }
        
        if (empty($custom_statuses)) {
            // Load default styles anyway for testing
            $this->load_default_styles();
            return;
        }

        // Enqueue FontAwesome
        wp_enqueue_style(
            'kdsamref-fontawesome-woocommerce',
            KDSAMREF_PLUGIN_URL . 'assets/fonts/fontawesome/css/all.min.css',
            array(),
            '6.4.0'
        );

        // Enqueue our custom styles
        wp_enqueue_style(
            'kdsamref-woocommerce-order-status',
            KDSAMREF_PLUGIN_URL . 'assets/css/woocommerce-order-status.css',
            array('kdsamref-fontawesome-woocommerce'),
            KDSAMREF_VERSION
        );

        // Generate dynamic CSS for custom statuses
        $this->generate_dynamic_order_status_css($custom_statuses);
    }

    /**
     * Load default styles for testing
     */
    private function load_default_styles() {
        // Enqueue FontAwesome
        wp_enqueue_style(
            'kdsamref-fontawesome-woocommerce',
            KDSAMREF_PLUGIN_URL . 'assets/fonts/fontawesome/css/all.min.css',
            array(),
            '6.4.0'
        );

        // Enqueue our custom styles
        wp_enqueue_style(
            'kdsamref-woocommerce-order-status',
            KDSAMREF_PLUGIN_URL . 'assets/css/woocommerce-order-status.css',
            array('kdsamref-fontawesome-woocommerce'),
            KDSAMREF_VERSION
        );
    }

    /**
     * Generate dynamic CSS for custom order statuses
     */
    private function generate_dynamic_order_status_css($custom_statuses) {
        $css = '';
        
        foreach ($custom_statuses as $slug => $status_data) {
            if (empty($status_data['enabled'])) {
                continue;
            }

            $color = $status_data['color'] ?? '#007cba';
            $icon = $status_data['icon'] ?? '';
            $text_color = wc_hex_is_light($color) ? '#000' : '#fff';

            // Convert icon name to Unicode
            $icon_code = $this->get_fontawesome_unicode($icon);

            $css .= "
                .order-status.status-{$slug} {
                    background-color: {$color} !important;
                    color: {$text_color} !important;
                    border-color: {$color} !important;
                }
                
                .order-status.status-{$slug}:before {
                    content: \"{$icon_code}\";
                    font-family: \"Font Awesome 6 Free\" !important;
                    font-weight: 900 !important;
                    margin-right: 5px;
                    display: inline-block;
                }
                
                .widefat .column-wc_actions .button.wc-action-button-{$slug}:after {
                    font-family: \"Font Awesome 6 Free\" !important;
                    content: \"{$icon_code}\" !important;
                    color: {$color} !important;
                    font-weight: 900 !important;
                    display: inline-block;
                }
                
                .woocommerce-order-data__heading .order-status.status-{$slug} {
                    background-color: {$color} !important;
                    color: {$text_color} !important;
                    border-color: {$color} !important;
                }
                
                .woocommerce-order-notes .order-status.status-{$slug} {
                    background-color: {$color} !important;
                    color: {$text_color} !important;
                    border-color: {$color} !important;
                }
            ";
        }

        if (!empty($css)) {
            wp_add_inline_style('kdsamref-woocommerce-order-status', wp_kses_post($css));
        }
    }

    /**
     * Get FontAwesome Unicode for icon name
     */
    private function get_fontawesome_unicode($icon_name) {
        // Common FontAwesome 6 icon mappings
        $icon_map = array(
            'fa-cog' => '\f013',
            'fa-check' => '\f00c',
            'fa-times' => '\f00d',
            'fa-clock' => '\f017',
            'fa-fire' => '\f06d',
            'fa-star' => '\f005',
            'fa-heart' => '\f004',
            'fa-thumbs-up' => '\f164',
            'fa-thumbs-down' => '\f165',
            'fa-exclamation' => '\f12a',
            'fa-question' => '\f128',
            'fa-info' => '\f129',
            'fa-triangle-exclamation' => '\f071',
            'fa-bell' => '\f0f3',
            'fa-flag' => '\f024',
            'fa-tag' => '\f02b',
            'fa-bookmark' => '\f02e',
            'fa-calendar' => '\f133',
            'fa-calendar-check' => '\f274',
            'fa-calendar-xmark' => '\f273',
            'fa-calendar-plus' => '\f271',
            'fa-calendar-minus' => '\f272',
            'fa-hourglass' => '\f254',
            'fa-hourglass-start' => '\f251',
            'fa-hourglass-half' => '\f252',
            'fa-hourglass-end' => '\f253',
            'fa-stopwatch' => '\f2f2',
            'fa-timer' => '\f2f2',
            'fa-shopping-cart' => '\f07a',
            'fa-shopping-bag' => '\f290',
            'fa-box' => '\f466',
            'fa-boxes' => '\f468',
            'fa-truck' => '\f0d1',
            'fa-shipping-fast' => '\f48b',
            'fa-route' => '\f4d7',
            'fa-map-marker-alt' => '\f3c5',
            'fa-location-dot' => '\f3c5',
            'fa-phone' => '\f095',
            'fa-envelope' => '\f0e0',
            'fa-user' => '\f007',
            'fa-users' => '\f0c0',
            'fa-user-check' => '\f4fc',
            'fa-user-clock' => '\f4fd',
            'fa-user-cog' => '\f4fe',
            'fa-user-edit' => '\f4ff',
            'fa-user-plus' => '\f234',
            'fa-user-minus' => '\f503',
            'fa-user-times' => '\f235',
            'fa-credit-card' => '\f09d',
            'fa-money-bill' => '\f0d6',
            'fa-coins' => '\f51e',
            'fa-wallet' => '\f555',
            'fa-cash-register' => '\f788',
            'fa-receipt' => '\f543',
            'fa-file-invoice' => '\f570',
            'fa-chart-line' => '\f201',
            'fa-chart-bar' => '\f080',
            'fa-chart-pie' => '\f200',
            'fa-percentage' => '\f541',
            'fa-dollar-sign' => '\f155',
            'fa-euro-sign' => '\f153',
            'fa-circle-check' => '\f058',
            'fa-circle-xmark' => '\f057',
            'fa-circle-exclamation' => '\f06a',
            'fa-circle-info' => '\f05a',
            'fa-circle-question' => '\f059',
            'fa-circle-plus' => '\f055',
            'fa-circle-minus' => '\f056',
            'fa-circle-pause' => '\f28b',
            'fa-circle-play' => '\f144',
            'fa-circle-stop' => '\f28d',
            'fa-circle-dot' => '\f192',
            'fa-circle-notch' => '\f1ce',
            'fa-play' => '\f04b',
            'fa-pause' => '\f04c',
            'fa-stop' => '\f04d',
            'fa-forward' => '\f04e',
            'fa-backward' => '\f04a',
            'fa-fast-forward' => '\f050',
            'fa-fast-backward' => '\f049',
            'fa-step-forward' => '\f051',
            'fa-step-backward' => '\f048',
            'fa-redo' => '\f01e',
            'fa-undo' => '\f0e2',
            'fa-sync' => '\f021',
            'fa-rotate' => '\f2f1',
            'fa-arrows-rotate' => '\f021',
            'fa-refresh' => '\f021',
            'fa-file' => '\f15b',
            'fa-file-alt' => '\f15c',
            'fa-file-text' => '\f15c',
            'fa-file-pdf' => '\f1c1',
            'fa-file-word' => '\f1c2',
            'fa-file-excel' => '\f1c3',
            'fa-file-image' => '\f1c5',
            'fa-file-video' => '\f1c8',
            'fa-file-audio' => '\f1c7',
            'fa-file-archive' => '\f1c6',
            'fa-file-code' => '\f1c9',
            'fa-file-contract' => '\f56c',
            'fa-file-invoice-dollar' => '\f571',
            'fa-comment' => '\f075',
            'fa-comments' => '\f086',
            'fa-comment-dots' => '\f4ad',
            'fa-comment-slash' => '\f4b3',
            'fa-comment-medical' => '\f7f5',
            'fa-comment-dollar' => '\f651',
            'fa-phone-square' => '\f098',
            'fa-phone-volume' => '\f2a0',
            'fa-phone-slash' => '\f3dd',
            'fa-envelope-open' => '\f2b6',
            'fa-envelope-square' => '\f199',
            'fa-at' => '\f1fa',
            'fa-lock' => '\f023',
            'fa-unlock' => '\f09c',
            'fa-key' => '\f084',
            'fa-shield' => '\f132',
            'fa-shield-alt' => '\f3ed',
            'fa-shield-check' => '\f3ed',
            'fa-shield-virus' => '\e06c',
            'fa-user-shield' => '\f505',
            'fa-user-lock' => '\f502',
            'fa-user-secret' => '\f21b',
            'fa-eye' => '\f06e',
            'fa-eye-slash' => '\f070',
            'fa-eye-low-vision' => '\f2a8',
            'fa-desktop' => '\f108',
            'fa-laptop' => '\f109',
            'fa-tablet' => '\f10a',
            'fa-mobile' => '\f10b',
            'fa-server' => '\f233',
            'fa-database' => '\f1c0',
            'fa-network-wired' => '\f6ff',
            'fa-wifi' => '\f1eb',
            'fa-bluetooth' => '\f293',
            'fa-satellite-dish' => '\f7c0',
            'fa-microchip' => '\f2db',
            'fa-memory' => '\f538',
            'fa-hard-drive' => '\f0a0',
            'fa-heartbeat' => '\f21e',
            'fa-heart-pulse' => '\f21e',
            'fa-stethoscope' => '\f0f1',
            'fa-user-md' => '\f0f0',
            'fa-user-nurse' => '\f82f',
            'fa-hospital' => '\f0f8',
            'fa-clinic-medical' => '\f7f2',
            'fa-pills' => '\f484',
            'fa-prescription-bottle' => '\f485',
            'fa-thermometer' => '\f491',
            'fa-temperature-high' => '\f769',
            'fa-temperature-low' => '\f76b',
            'fa-utensils' => '\f2e7',
            'fa-cutlery' => '\f2e7',
            'fa-coffee' => '\f0f4',
            'fa-mug-hot' => '\f7b6',
            'fa-pizza-slice' => '\f818',
            'fa-hamburger' => '\f805',
            'fa-ice-cream' => '\f810',
            'fa-cookie' => '\f563',
            'fa-cake-candles' => '\f1fd',
            'fa-wine-glass' => '\f4e3',
            'fa-beer' => '\f0fc',
            'fa-glass-martini' => '\f000',
            'fa-cocktail' => '\f561',
            'fa-futbol' => '\f1e3',
            'fa-basketball' => '\f434',
            'fa-volleyball' => '\f45f',
            'fa-running' => '\f70c',
            'fa-walking' => '\f554',
            'fa-biking' => '\f84a',
            'fa-swimming' => '\f5c4',
            'fa-skiing' => '\f7c9',
            'fa-snowboarding' => '\f7ce',
            'fa-dumbbell' => '\f44b',
            'fa-sun' => '\f185',
            'fa-moon' => '\f186',
            'fa-cloud' => '\f0c2',
            'fa-cloud-rain' => '\f73d',
            'fa-cloud-sun' => '\f6c4',
            'fa-cloud-moon' => '\f6c3',
            'fa-bolt' => '\f0e7',
            'fa-snowflake' => '\f2dc',
            'fa-umbrella' => '\f0e9',
            'fa-wind' => '\f72e',
            'fa-leaf' => '\f06c',
            'fa-tree' => '\f1bb',
            'fa-seedling' => '\f4d8',
            'fa-car' => '\f1b9',
            'fa-bus' => '\f207',
            'fa-train' => '\f238',
            'fa-plane' => '\f072',
            'fa-ship' => '\f21a',
            'fa-bicycle' => '\f206',
            'fa-motorcycle' => '\f21c',
            'fa-taxi' => '\f1ba',
            'fa-van-shuttle' => '\f5b6',
            'fa-rocket' => '\f135',
            'fa-helicopter' => '\f533',
            'fa-satellite' => '\f7bf',
            'fa-music' => '\f001',
            'fa-video' => '\f03d',
            'fa-camera' => '\f030',
            'fa-photo-film' => '\f87c',
            'fa-gamepad' => '\f11b',
            'fa-dice' => '\f522',
            'fa-chess' => '\f439',
            'fa-trophy' => '\f091',
            'fa-medal' => '\f5a2',
            'fa-award' => '\f559',
            'fa-gift' => '\f06b',
            'fa-birthday-cake' => '\f1fd',
            'fa-party-horn' => '\f1fd',
            'fa-briefcase' => '\f0b1',
            'fa-suitcase' => '\f0f2',
            'fa-building' => '\f1ad',
            'fa-industry' => '\f275',
            'fa-warehouse' => '\f494',
            'fa-store' => '\f54e',
            'fa-cart-shopping' => '\f07a',
            'fa-cart-plus' => '\f217',
            'fa-cart-arrow-down' => '\f218',
            'fa-cart-flatbed' => '\f474',
            'fa-dolly' => '\f472',
            'fa-graduation-cap' => '\f19d',
            'fa-book' => '\f02d',
            'fa-book-open' => '\f518',
            'fa-chalkboard' => '\f51b',
            'fa-chalkboard-user' => '\f51c',
            'fa-school' => '\f549',
            'fa-university' => '\f19c',
            'fa-library' => '\f549',
            'fa-microscope' => '\f610',
            'fa-flask' => '\f0c3',
            'fa-atom' => '\f5d2',
            'fa-dna' => '\f471',
            'fa-exclamation-triangle' => '\f071',
            'fa-radiation' => '\f7b9',
            'fa-biohazard' => '\f780',
            'fa-skull-crossbones' => '\f714',
            'fa-virus' => '\e074',
            'fa-virus-slash' => '\e075',
            'fa-mask' => '\f6fa',
            'fa-head-side-mask' => '\f963',
            'fa-head-side-cough' => '\f961',
            'fa-hand-holding-medical' => '\f05c',
            'fa-first-aid' => '\f479',
            'fa-kit-medical' => '\f479'
        );

        // Return Unicode if found, otherwise return the original icon name
        return isset($icon_map[$icon_name]) ? $icon_map[$icon_name] : $icon_name;
    }



    /**
     * Auto refresh field callback
     */
    public function auto_refresh_callback() {
        $settings = get_option('kdsamref_settings', array());
        $interval = isset($settings['auto_refresh_interval']) ? $settings['auto_refresh_interval'] : 15;
        ?>
        <input type="number" name="kdsamref_settings[auto_refresh_interval]" value="<?php echo esc_attr($interval); ?>" min="5" max="300" />
        <span class="description"><?php esc_html_e('seconds (5-300)', 'kds-report-for-orderable'); ?></span>
        <?php
    }

    /**
     * Notifications field callback
     */
    public function notifications_callback() {
        $settings = get_option('kdsamref_settings', array());
        $notifications = isset($settings['enable_notifications']) ? $settings['enable_notifications'] : 1;
        ?>
        <input type="checkbox" name="kdsamref_settings[enable_notifications]" value="1" <?php checked(1, $notifications); ?> />
        <span class="description"><?php esc_html_e('Enable browser notifications for new orders', 'kds-report-for-orderable'); ?></span>
        <?php
    }

    /**
     * Get all settings with defaults
     */
    public function get_all_settings() {
        $defaults = array(
            'max_orders_limit' => 100,
            'default_font_size' => 100,
            'auto_refresh_interval' => 15,
            'enable_notifications' => 1,
            'notification_sound' => 1,
            'notification_volume' => 0.3,
            'disable_refresh_notifications' => 0,
            'show_completed_orders' => 1,
            'completed_orders_opacity' => 0.8,

            'compact_mode' => 0,
            'show_order_numbers' => 1,
            'show_customer_names' => 1,
            'show_product_options' => 1,
            'show_tips' => 1,
            'show_fees' => 1,
                    'delivery_badge_color' => '#4ade80', // Pastel yeşil
        'pickup_badge_color' => '#a78bfa', // Pastel mor
        'dine_in_badge_color' => '#60a5fa', // Pastel mavi
            'show_debug_menu' => 1,
            // UI Colors
            'border_color_primary' => '#dee2e6',
            'border_color_secondary' => '#e9ecef',
            'card_background_color' => '#ffffff',
            'dashboard_background_color' => '#f8f9fa',
            // Custom statuses and workflow - boş bırak, WooCommerce'den gelecek
            'custom_statuses' => array(),
            'workflow_steps' => array(),
            'status_order' => array(),
            'status_colors' => array(),
            'status_labels' => array()
        );

        $settings = get_option('kdsamref_settings', array());
        
        // Merge settings with defaults, but preserve existing values
        $merged_settings = wp_parse_args($settings, $defaults);
        
        return $merged_settings;
    }

    /**
     * Get dashboard settings for JavaScript
     */
    public function get_dashboard_settings() {
        $settings = $this->get_all_settings();
        
        // Filter settings for dashboard use
        return array(
            'maxOrdersLimit' => $settings['max_orders_limit'],
            'defaultFontSize' => $settings['default_font_size'],
            'autoRefreshInterval' => $settings['auto_refresh_interval'],
            'showCompletedOrders' => $settings['show_completed_orders'],
            'completedOrdersOpacity' => $settings['completed_orders_opacity'],
            'tabletMode' => false,
            'deliveryBadgeColor' => $settings['delivery_badge_color'],
            'pickupBadgeColor' => $settings['pickup_badge_color'],
            'dineInBadgeColor' => $settings['dine_in_badge_color'],
            // Status order and colors
            'statusOrder' => $settings['status_order'],
            'statusColors' => $settings['status_colors'],
            'statusLabels' => $settings['status_labels'],
            // UI Colors
            'borderColorPrimary' => $settings['border_color_primary'],
            'borderColorSecondary' => $settings['border_color_secondary'],
            'cardBackgroundColor' => $settings['card_background_color'],
            'dashboardBackgroundColor' => $settings['dashboard_background_color'],
            // Custom statuses and workflow
            'customStatuses' => $settings['custom_statuses'],
            'workflowSteps' => $settings['workflow_steps']
        );
    }

    /**
     * Get setting value
     */
    public function get_setting($key, $default = null) {
        $settings = $this->get_all_settings();
        return isset($settings[$key]) ? $settings[$key] : $default;
    }
    
    /**
     * Update settings
     */
    public function update_settings($new_settings) {
        $current_settings = $this->get_all_settings();
        $merged_settings = array_merge($current_settings, $new_settings);
        
        // Check if settings actually changed
        if ($current_settings === $merged_settings) {
            // No changes, return true (success)
            return true;
        }
        
        $result = update_option('kdsamref_settings', $merged_settings);
        
        // WordPress update_option returns false if value didn't change
        // This is normal behavior, not an error
        if ($result === false) {
            // Check if the value was actually the same
            $saved_value = get_option('kdsamref_settings', array());
            if ($saved_value === $merged_settings) {
                return true; // Success - value was already correct
            }
        }
        
        return $result;
    }

    /**
     * Sync Orderable Pro custom statuses
     */
    public function sync_orderable_pro_statuses() {
        if (!class_exists('Orderable_Custom_Order_Status_Pro_Helper')) {
            return array(
                'success' => false,
                'message' => __('Orderable Pro Custom Order Status plugin is not active', 'kds-report-for-orderable')
            );
        }

        try {
            $orderable_custom_statuses = Orderable_Custom_Order_Status_Pro_Helper::get_custom_order_statuses();
            $settings = $this->get_all_settings();
            $current_custom_statuses = $settings['custom_statuses'] ?? array();
            $updated = false;

            // Get current Orderable Pro status slugs
            $orderable_status_slugs = array();
            if (!empty($orderable_custom_statuses)) {
                foreach ($orderable_custom_statuses as $status) {
                    $orderable_status_slugs[] = $status->post_name;
                }
            }

            // Remove statuses that no longer exist in Orderable Pro
            foreach ($current_custom_statuses as $slug => $status_data) {
                if (isset($status_data['source']) && $status_data['source'] === 'orderable_pro') {
                    if (!in_array($slug, $orderable_status_slugs)) {
                        unset($current_custom_statuses[$slug]);
                        $updated = true;
                    }
                }
            }

            // Add or update statuses from Orderable Pro
            if (!empty($orderable_custom_statuses)) {
                foreach ($orderable_custom_statuses as $status) {
                    $status_slug = $status->post_name;
                    $status_title = $status->post_title;
                    
                    // Get color from Orderable Pro settings
                    $status_color = '#007cba'; // Default color
                    if (isset($status->data) && isset($status->data['color'])) {
                        $status_color = $status->data['color'];
                    } else {
                        // Fallback: try to get color from post meta
                        $status_color = get_post_meta($status->ID, 'orderable_cos_color', true) ?: '#007cba';
                    }

                    // Get icon and icon_family from Orderable Pro settings
                    $status_icon = '';
                    $status_icon_family = '';
                    if (isset($status->data)) {
                        $status_icon = $status->data['icon'] ?? '';
                        $status_icon_family = $status->data['icon_family'] ?? '';
                    } else {
                        // Fallback: try to get icon from post meta
                        $status_icon = get_post_meta($status->ID, 'orderable_cos_icon', true) ?: '';
                        $status_icon_family = get_post_meta($status->ID, 'orderable_cos_icon_family', true) ?: '';
                    }

                    if (!isset($current_custom_statuses[$status_slug])) {
                        // Add new status
                        $current_custom_statuses[$status_slug] = array(
                            'label' => $status_title,
                            'color' => $status_color,
                            'icon' => $status_icon,
                            'icon_family' => $status_icon_family,
                            'source' => 'orderable_pro'
                        );
                        $updated = true;
                    } else {
                        // Update existing status with current Orderable Pro data
                        $current_custom_statuses[$status_slug]['label'] = $status_title;
                        $current_custom_statuses[$status_slug]['color'] = $status_color;
                        $current_custom_statuses[$status_slug]['icon'] = $status_icon;
                        $current_custom_statuses[$status_slug]['icon_family'] = $status_icon_family;
                        $current_custom_statuses[$status_slug]['source'] = 'orderable_pro';
                        $updated = true;
                    }
                }
            }

            if ($updated) {
                $settings['custom_statuses'] = $current_custom_statuses;
                $this->update_settings($settings);
                return array(
                    'success' => true,
                    'message' => __('Statuses synced successfully', 'kds-report-for-orderable')
                );
            }

            return array(
                'success' => true,
                'message' => __('No changes needed - statuses are already in sync', 'kds-report-for-orderable')
            );
        } catch (Exception $e) {
            // Error syncing Orderable Pro statuses
            return array(
                'success' => false,
                /* translators: %s: error message */
                'message' => sprintf(esc_html__('Error syncing statuses: %s', 'kds-report-for-orderable'), esc_html($e->getMessage()))
            );
        }
    }

    /**
     * Register custom statuses with WooCommerce
     */
    public function register_custom_statuses_with_wc() {
        $settings = $this->get_all_settings();
        $custom_statuses = $settings['custom_statuses'] ?? array();
        
        foreach ($custom_statuses as $slug => $status_data) {
            if (!empty($slug) && !empty($status_data['label'])) {
                $status_type = $status_data['status_type'] ?? 'custom';
                
                // For core status modifications, we don't register a new post status
                // Instead, we modify the existing WooCommerce status behavior
                if ($status_type === 'custom') {
                    register_post_status('wc-' . $slug, array(
                        'label' => $status_data['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 custom statuses to WooCommerce order statuses
     */
    public function add_custom_statuses_to_wc($order_statuses) {
        $settings = $this->get_all_settings();
        $custom_statuses = $settings['custom_statuses'] ?? array();
        
        foreach ($custom_statuses as $slug => $status_data) {
            if (!empty($slug) && !empty($status_data['label'])) {
                $status_type = $status_data['status_type'] ?? 'custom';
                
                if ($status_type === 'custom') {
                    // Add new custom status
                    $order_statuses['wc-' . $slug] = $status_data['label'];
                } else {
                    // Modify existing core status
                    $order_statuses['wc-' . $slug] = $status_data['label'];
                }
            }
        }
        
        return $order_statuses;
    }

    /**
     * Add custom order actions to admin panel
     */
    public function add_custom_order_actions($actions, $order) {
        $settings = $this->get_all_settings();
        $custom_statuses = $settings['custom_statuses'] ?? array();
        
        foreach ($custom_statuses as $slug => $status_data) {
            if (!empty($slug) && !empty($status_data['label'])) {
                $actions[$slug] = array(
                    'url' => wp_nonce_url(
                        admin_url('admin-ajax.php?action=woocommerce_mark_order_status&order_id=' . $order->get_id() . '&status=' . $slug),
                        'woocommerce-mark-order-status'
                    ),
                    'name' => $status_data['label'],
                    'action' => $slug,
                );
            }
        }
        
        return $actions;
    }

    /**
     * Add custom bulk actions
     */
    public function add_custom_bulk_actions($actions) {
        $settings = $this->get_all_settings();
        $custom_statuses = $settings['custom_statuses'] ?? array();
        
        foreach ($custom_statuses as $slug => $status_data) {
            if (!empty($slug) && !empty($status_data['label'])) {
                $actions['mark_' . $slug] = sprintf(
                    /* translators: %s: status label */
                    esc_html__('Change status to %s', 'kds-report-for-orderable'),
                    esc_html($status_data['label'])
                );
            }
        }
        
        return $actions;
    }

    /**
     * Filter WooCommerce order actions to show only next steps
     */
    public function filter_order_actions($actions, $order) {
        $settings = $this->get_all_settings();
        $workflow_steps = $settings['workflow_steps'] ?? array('processing', 'completed');
        $current_status = $order->get_status();
        
        // Normalize current status (remove wc- prefix if present)
        $current_status = str_replace('wc-', '', $current_status);
        
        // Normalize workflow steps (remove wc- prefix if present)
        $normalized_workflow_steps = array_map(function($step) {
            return str_replace('wc-', '', $step);
        }, $workflow_steps);

        // Find the index of the current status in the workflow steps
        $current_step_index = array_search($current_status, $normalized_workflow_steps);

        // If the current status is not in the workflow or is the last step, remove all actions
        if ($current_step_index === false || $current_step_index === count($normalized_workflow_steps) - 1) {
            return array();
        }

        // Get the next step slug
        $next_step_slug = $normalized_workflow_steps[$current_step_index + 1];
        
        // Add wc- prefix back for WooCommerce action matching
        $next_step_with_prefix = 'wc-' . $next_step_slug;

        // Filter actions to only include the next step's action
        $filtered_actions = array();
        foreach ($actions as $action_key => $action_data) {
            // Check if this action matches the next step
            if (isset($action_data['action']) && 
                ($action_data['action'] === $next_step_slug || $action_data['action'] === $next_step_with_prefix)) {
                $filtered_actions[$action_key] = $action_data;
            }
        }

        return $filtered_actions;
    }

    /**
     * Clear order statistics cache
     */
    public function clear_order_statistics_cache() {
        // Clear any cached order statistics
        wp_cache_delete('kdsamref_order_statistics', 'kdsamref');
        wp_cache_delete('kdsamref_custom_status_counts', 'kdsamref');
        
        // Clear WooCommerce order cache
        if (function_exists('wc_delete_shop_order_transients')) {
            wc_delete_shop_order_transients();
        }
        
        // Clear any custom status related caches
        delete_transient('kdsamref_custom_status_data');
        delete_transient('kdsamref_order_counts');
    }


    /**
     * Custom status page content
     */
    public function custom_status_page() {
        // Handle form submission
        if (isset($_POST['submit']) && isset($_POST['_wpnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'kdsamref_custom_status')) {
            $this->save_custom_status();
        }

        $settings = $this->get_all_settings();
        $custom_statuses = $settings['custom_statuses'] ?? array();
        
        // Sync with Orderable Pro if available
        if (class_exists('Orderable_Custom_Order_Status_Pro_Helper')) {
            $this->sync_orderable_pro_statuses();
            // Refresh settings after sync
            $settings = $this->get_all_settings();
            $custom_statuses = $settings['custom_statuses'] ?? array();
        }
        
        // Make variables available to template
        $admin = $this;
        
        include KDSAMREF_PLUGIN_PATH . 'templates/custom-status-page.php';
    }

    /**
     * Workflow page
     */
    public function workflow_page() {
        // Handle form submission
        if (isset($_POST['submit']) && isset($_POST['_wpnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'kdsamref_workflow')) {
            $this->save_workflow();
        }

        // Force refresh of settings to ensure we have the latest data
        $settings = $this->get_all_settings();
        
        // Clear any potential caching issues by re-fetching settings
        wp_cache_delete('kdsamref_settings', 'options');
        $settings = $this->get_all_settings();
        
        include KDSAMREF_PLUGIN_PATH . 'templates/workflow-page.php';
    }

    /**
     * Save custom status
     */
    private function save_custom_status() {
        if (!current_user_can('manage_kdsamref_orders')) {
            return;
        }

        $edit_slug = sanitize_text_field($_POST['edit_slug'] ?? '');
        $status_type = sanitize_text_field($_POST['status_type'] ?? '');
        $slug = sanitize_text_field($_POST['status_slug'] ?? '');
        $label = sanitize_text_field($_POST['status_label'] ?? '');
        $color = sanitize_hex_color($_POST['status_color'] ?? '#007cba');
        $icon = sanitize_text_field($_POST['status_icon'] ?? '');
        $icon_family = sanitize_text_field($_POST['status_icon_family'] ?? 'fontawesome');
        $enabled = isset($_POST['status_enabled']) ? 1 : 0;

        if (empty($slug) || empty($label)) {
            echo '<div class="notice notice-error"><p>' . esc_html__('Slug and label are required.', 'kds-report-for-orderable') . '</p></div>';
            return;
        }

        $settings = $this->get_all_settings();
        $custom_statuses = $settings['custom_statuses'] ?? array();

        // Check if this is an edit operation
        if (!empty($edit_slug)) {
            // Remove old status if slug changed
            if ($edit_slug !== $slug && isset($custom_statuses[$edit_slug])) {
                unset($custom_statuses[$edit_slug]);
            }
        }

        // Validate status type
        if ($status_type === 'custom') {
            // Custom status - validate slug uniqueness
            $wc_statuses = wc_get_order_statuses();
            $existing_slugs = array_keys($wc_statuses);
            $existing_slugs = array_map(function($slug) {
                return str_replace('wc-', '', $slug);
            }, $existing_slugs);
            
            if (in_array($slug, $existing_slugs) && $slug !== $edit_slug) {
            echo '<div class="notice notice-error"><p>' . esc_html__('This slug already exists in WooCommerce statuses.', 'kds-report-for-orderable') . '</p></div>';
                return;
            }
        } else {
            // Core status modification - use the core status slug
            $slug = $status_type;
        }

        $custom_statuses[$slug] = array(
            'label' => $label,
            'color' => $color,
            'enabled' => $enabled,
            'source' => 'custom',
            'status_type' => $status_type,
            'icon' => $icon,
            'icon_family' => $icon_family
        );

        $settings['custom_statuses'] = $custom_statuses;
        $this->update_settings($settings);

        // Re-register with WooCommerce
        $this->register_custom_statuses_with_wc();

        $action_text = !empty($edit_slug) ? 'updated' : 'saved';
        $status_type_text = $status_type === 'custom' ? 'Custom status' : 'Core status modification';
        /* translators: 1: status type text, 2: action text */
        echo '<div class="notice notice-success"><p>' . sprintf(esc_html__('%1$s %2$s successfully!', 'kds-report-for-orderable'), esc_html($status_type_text), esc_html($action_text)) . '</p></div>';
    }

    /**
     * Save workflow
     */
    private function save_workflow() {
        // Fix permission check
        if (!current_user_can('manage_woocommerce') && !current_user_can('administrator')) {
            echo '<div class="notice notice-error"><p>' . esc_html__('Permission denied', 'kds-report-for-orderable') . '</p></div>';
            return;
        }

        $settings = $this->get_all_settings();
        
        if (isset($_POST['kdsamref_settings']['workflow_steps']) && is_array($_POST['kdsamref_settings']['workflow_steps'])) {
            $workflow_steps = array();
            $raw_workflow_steps = map_deep($_POST['kdsamref_settings']['workflow_steps'], 'sanitize_text_field');
            
            foreach ($raw_workflow_steps as $step) {
                $step = sanitize_text_field($step);
                if (!empty($step)) {
                    $workflow_steps[] = $step;
                }
            }
            
            // Ensure first step is always 'processing' and last step is always 'completed'
            if (empty($workflow_steps) || $workflow_steps[0] !== 'processing') {
                $workflow_steps = array_merge(['processing'], array_filter($workflow_steps, function($step) { 
                    return $step !== 'processing' && $step !== 'completed'; 
                }));
            }
            if (end($workflow_steps) !== 'completed') {
                $workflow_steps = array_merge(array_filter($workflow_steps, function($step) { 
                    return $step !== 'completed'; 
                }), ['completed']);
            }
            
            $settings['workflow_steps'] = $workflow_steps;
            
            // Use our improved update_settings method
            $result = $this->update_settings($settings);
            
            if ($result) {
                echo '<div class="notice notice-success"><p>' . esc_html__('Workflow saved successfully!', 'kds-report-for-orderable') . '</p></div>';
            } else {
                echo '<div class="notice notice-error"><p>' . esc_html__('Failed to save workflow', 'kds-report-for-orderable') . '</p></div>';
            }
        } else {
            echo '<div class="notice notice-error"><p>' . esc_html__('No workflow steps found', 'kds-report-for-orderable') . '</p></div>';
        }
    }
    
    // Duplicate ajax_delete_custom_status method removed - handled in KDSAMREF_Ajax_Handler class
}
