<?php
/**
 * Plugin Name: KDS & Report for Orderable
 * Plugin URI: https://codeon.ch/orderable-kds
 * Description: Modern tablet-optimized restaurant order management system for WooCommerce with real-time tracking, Modern interface, Orderable integration, custom workflows, and advanced analytics. Enhanced security version.
 * Version: 3.0.2
 * Author: Codeon
 * Author URI: https://codeon.ch
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: kds-report-for-orderable
 * Domain Path: /languages
 * Requires at least: 5.0
 * Tested up to: 6.8
 * Requires PHP: 7.4
 * WC requires at least: 7.0
 * WC tested up to: 10.0.0
 * Security-Enhanced: true
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Define plugin constants
define('KDSAMREF_PLUGIN_FILE', __FILE__);
define('KDSAMREF_PLUGIN_BASENAME', plugin_basename(__FILE__));
define('KDSAMREF_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('KDSAMREF_PLUGIN_URL', plugin_dir_url(__FILE__));
define('KDSAMREF_VERSION', '3.0.2');

/**
 * Main KDS & Report for Orderable Class
 */
class KDSAMREF_Main {

    /**
     * Single instance of the class
     */
    protected static $_instance = null;
    
    /**
     * Flag to prevent recursive initialization
     */
    private $initialized = false;

    /**
     * Get instance
     */
    public static function instance() {
        if (is_null(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * Constructor
     */
    public function __construct() {
        // Legacy constants removed - using KDSAMREF_ prefix only

        // Declare HPOS compatibility
        add_action('before_woocommerce_init', array($this, 'declare_hpos_compatibility'));
        
        // Initialize hooks
        $this->init_hooks();
        
        // Include required files
        $this->includes();
        
        // Initialize classes after WooCommerce is loaded
        add_action('woocommerce_loaded', array($this, 'init_classes'));
    }

    /**
     * Initialize hooks
     */
    private function init_hooks() {
        // Check if WooCommerce is active
        add_action('plugins_loaded', array($this, 'check_woocommerce'));
        
        // Load text domain for translations
        add_action('plugins_loaded', array($this, 'load_textdomain'));
        
        // Initialize plugin
        add_action('init', array($this, 'init'));
        
        // Add admin menu
        add_action('admin_menu', array($this, 'admin_menu'));
        
        // Enqueue admin scripts and styles
        add_action('admin_enqueue_scripts', array($this, 'admin_scripts'));
        
        // Enqueue admin styles and scripts for specific pages
        add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_styles'));
        add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'));
        
        // Add custom order statuses
        add_action('init', array($this, 'register_custom_order_statuses'));
        add_filter('wc_order_statuses', array($this, 'add_custom_order_statuses'));
        
        // Add custom order actions to admin panel
        add_filter('woocommerce_admin_order_actions', array($this, 'add_custom_order_actions'), 10, 2);
        add_filter('bulk_actions-edit-shop_order', array($this, 'add_custom_bulk_actions'), 20);
        
        // AJAX handlers are registered in KDSAMREF_Ajax_Handler class
        // License-related AJAX handled by Pro


        // Add custom meta boxes
        add_action('add_meta_boxes', array($this, 'add_order_meta_boxes'));
        add_action('save_post', array($this, 'save_order_meta'));
        
        // Sync with Orderable Pro custom statuses
        add_action('wp_trash_post', array($this, 'sync_orderable_pro_statuses_on_delete'), 10, 1);
        add_action('before_delete_post', array($this, 'sync_orderable_pro_statuses_on_delete'), 10, 1);
        add_action('save_post', array($this, 'sync_orderable_pro_statuses_on_save'), 10, 1);
        add_action('kdsamref_sync_orderable_pro_statuses', array($this, 'sync_custom_statuses_with_orderable_pro'));
    }

    /**
     * Sync with Orderable Pro custom statuses on delete
     */
    public function sync_orderable_pro_statuses_on_delete($post_id) {
        // Check if this is an Orderable Pro custom status post
        if (get_post_type($post_id) === 'orderable_status') {
            // Trigger sync after a short delay to ensure the post is fully deleted
            wp_schedule_single_event(time() + 2, 'kdsamref_sync_orderable_pro_statuses');
        }
    }

    /**
     * Sync with Orderable Pro custom statuses on save
     */
    public function sync_orderable_pro_statuses_on_save($post_id) {
        // Check if this is an Orderable Pro custom status post
        if (get_post_type($post_id) === 'orderable_status') {
            // Trigger sync after a short delay to ensure the post is fully saved
            wp_schedule_single_event(time() + 2, 'kdsamref_sync_orderable_pro_statuses');
        }
    }

    /**
     * Sync custom statuses with Orderable Pro
     */
    public function sync_custom_statuses_with_orderable_pro() {
        if (isset($this->admin)) {
            $this->admin->sync_orderable_pro_statuses();
        }
    }

    /**
     * Load plugin text domain (WordPress.org auto-loads translations)
     */
    public function load_textdomain() {
        // WordPress.org automatically loads translations for plugins hosted on wordpress.org
        // This method is kept for backward compatibility with self-hosted installations
    }

    /**
     * Check if WooCommerce is active
     */
    public function check_woocommerce() {
        if (!class_exists('WooCommerce')) {
            deactivate_plugins(plugin_basename(__FILE__));
            wp_die(
                esc_html__('KDS & Report for Orderable requires WooCommerce to be installed and active.', 'kds-report-for-orderable'),
                esc_html__('Plugin Activation Error', 'kds-report-for-orderable'),
                array('back_link' => true)
            );
        }
        
        // Add custom capability to administrator role
        $this->add_kdsamref_orders_capability();
    }

    /**
     * Add custom kdsamref orders capability
     */
    private function add_kdsamref_orders_capability() {
        $admin_role = get_role('administrator');
        if ($admin_role) {
            $admin_role->add_cap('manage_kdsamref_orders');
        }
        
        $shop_manager_role = get_role('shop_manager');
        if ($shop_manager_role) {
            $shop_manager_role->add_cap('manage_kdsamref_orders');
        }
    }

    // No load_plugin_textdomain method needed

    /**
     * Initialize plugin
     */
    public function init() {
        // Check if WooCommerce is active
        if (!class_exists('WooCommerce')) {
            add_action('admin_notices', array($this, 'woocommerce_missing_notice'));
            return;
        }

        // Include required files
        $this->includes();
        
        // Run migration if needed
        $this->maybe_run_migration();

        // Initialize classes (with WooCommerce check)
        $this->init_classes();

        // Add admin menu
        add_action('admin_menu', array($this, 'admin_menu'));
        
        // Add custom order statuses
        add_action('init', array($this, 'register_custom_order_statuses'));
        add_filter('wc_order_statuses', array($this, 'add_custom_order_statuses'));
        
        // Add custom order actions to admin panel
        add_filter('woocommerce_admin_order_actions', array($this, 'add_custom_order_actions'), 10, 2);
        add_filter('bulk_actions-edit-shop_order', array($this, 'add_custom_bulk_actions'), 20);

        // AJAX handlers are registered in KDSAMREF_Ajax_Handler class
        // License-related AJAX handled by Pro

        // Add custom meta boxes
        add_action('add_meta_boxes', array($this, 'add_order_meta_boxes'));
        add_action('save_post', array($this, 'save_order_meta'));
        

    }
    


    /**
     * Include required files
     */
    private function includes() {
        // Core components only (license moved to Pro)
        // Include core components
        // Try to load Composer autoload (for Stripe SDK, etc.)
        $composerAutoload = KDSAMREF_PLUGIN_PATH . 'vendor/autoload.php';
        if (file_exists($composerAutoload)) {
            require_once $composerAutoload;
        }
        require_once KDSAMREF_PLUGIN_PATH . 'includes/class-kdsamref-order-manager.php';
        require_once KDSAMREF_PLUGIN_PATH . 'includes/class-kdsamref-ajax-handler.php';
        require_once KDSAMREF_PLUGIN_PATH . 'includes/class-kdsamref-admin.php';
        
        // Include Orderable integration if available
        if (file_exists(KDSAMREF_PLUGIN_PATH . 'includes/class-kdsamref-orderable-integration.php')) {
            include_once KDSAMREF_PLUGIN_PATH . 'includes/class-kdsamref-orderable-integration.php';
        }
        

        
        // Include Monthly Reports integration if available
        if (file_exists(KDSAMREF_PLUGIN_PATH . 'includes/class-kdsamref-monthly-reports.php')) {
            include_once KDSAMREF_PLUGIN_PATH . 'includes/class-kdsamref-monthly-reports.php';
        }
    }

    /**
     * Initialize classes
     */
    public function init_classes() {
        // Prevent recursive calls
        if ($this->initialized) {
            return;
        }
        
        // Check if WooCommerce is fully loaded
        if (!function_exists('wc_get_orders') || !class_exists('WC_Order')) {
            // WooCommerce not ready yet, try again later
            if (!$this->initialized) {
                add_action('woocommerce_loaded', array($this, 'init_classes'));
            }
            return;
        }
        
        // Mark as initialized
        $this->initialized = true;
        
        // Initialize license manager if available
        if (class_exists('KDSAMREF_License_Manager')) {
            $this->license_manager = new KDSAMREF_License_Manager();
        }
        
        // Initialize core components
        if (class_exists('KDSAMREF_Order_Manager')) {
            $this->order_manager = new KDSAMREF_Order_Manager();
        }
        if (class_exists('KDSAMREF_Ajax_Handler')) {
            $this->ajax_handler = new KDSAMREF_Ajax_Handler();
        }
        if (class_exists('KDSAMREF_Admin')) {
            $this->admin = new KDSAMREF_Admin();
        }
        
        // Track plugin initialization for analytics (if license manager available)
        // Telemetry disabled for WordPress.org compliance
        
        // Initialize Orderable integration if available and WooCommerce is ready
        if (class_exists('KDSAMREF_Orderable_Integration') && function_exists('wc_get_orders') && class_exists('WC_Order')) {
            try {
                $this->orderable_integration = new KDSAMREF_Orderable_Integration();
            } catch (Exception $e) {
                // Log integration errors only in debug mode
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    // Failed to initialize Orderable integration
                }
            }
        }
        
        // Initialize Monthly Reports integration if available
        if (class_exists('KDSAMREF_Monthly_Reports_Integration')) {
            try {
                $this->monthly_reports_integration = new KDSAMREF_Monthly_Reports_Integration();
            } catch (Exception $e) {
                // Log integration errors only in debug mode
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    // Failed to initialize Monthly Reports integration
                }
            }
        }
        

    }
    
    /**
     * Declare HPOS compatibility
     */
    public function declare_hpos_compatibility() {
        if (class_exists('\Automattic\WooCommerce\Utilities\FeaturesUtil')) {
            // Declare compatibility with custom order tables (HPOS)
            \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__, true);
            
            // Declare compatibility with cart checkout blocks
            \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('cart_checkout_blocks', __FILE__, true);
            
            // Declare compatibility with product blocks
            \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('product_block_editor', __FILE__, true);
        }
    }
    
    /**
     * Maybe run migration
     */
    private function maybe_run_migration() {
        if (class_exists('KDSAMREF_Migration')) {
            KDSAMREF_Migration::run();
            
            // Show migration notice if migration was needed
            if (class_exists('KDSAMREF_Migration') && KDSAMREF_Migration::is_migration_needed()) {
                add_action('admin_notices', array($this, 'migration_complete_notice'));
            }
        }
    }
    
    /**
     * Migration complete notice
     */
    public function migration_complete_notice() {
        // Only show to users who can manage kdsamref orders
        if (!$this->user_can_access_kdsamref_orders()) {
            return;
        }
        
        // Only show on kdsamref pages
        $screen = get_current_screen();
        if (!$screen || strpos($screen->base, 'kdsamref-') === false) {
            return;
        }
        
        if (!class_exists('KDSAMREF_Migration')) {
            return;
        }
        
        $migration_status = KDSAMREF_Migration::get_migration_status();
        
        ?>
        <div class="notice notice-success is-dismissible">
            <p>
                <strong><?php esc_html_e('KDS & Report for Orderable', 'kds-report-for-orderable'); ?></strong>
            </p>
            <p>
                <?php esc_html_e('System successfully migrated to Orderable-focused mode! Compatibility mode has been removed for better performance.', 'kds-report-for-orderable'); ?>
            </p>
            <p>
                <small>
                    <?php 
                    /* translators: 1: orderable status html, 2: migration version */
                    echo sprintf(
                        /* translators: 1: orderable status html, 2: migration version */ esc_html__('Orderable Status: %1$s | Migration Version: %2$s', 'kds-report-for-orderable'),
                        wp_kses_post($migration_status['orderable_active'] ? '<span style="color: green;">✓ Active</span>' : '<span style="color: orange;">⚠ Not Detected</span>'),
                        esc_html($migration_status['target_version'])
                    );
                    ?>
                </small>
            </p>
        </div>
        <?php
    }

    /**
     * WooCommerce missing notice
     */
    public function woocommerce_missing_notice() {
        ?>
        <div class="notice notice-error">
            <p><?php esc_html_e('KDS & Report for Orderable requires WooCommerce to be installed and active.', 'kds-report-for-orderable'); ?></p>
        </div>
        <?php
    }

    /**
     * Check if user has kdsamref orders access
     */
    public function user_can_access_kdsamref_orders() {
        // Check for custom kdsamref orders capability first
        if (current_user_can('manage_kdsamref_orders')) {
            return true;
        }
        
        // Fallback to WooCommerce and custom role checks
        return current_user_can('manage_woocommerce') || 
               current_user_can('shop_manager') || 
               current_user_can('gestion_commandes') || 
               current_user_can('order_manager') ||
               current_user_can('administrator');
    }

    /**
     * Add admin menu
     */
    public function admin_menu() {
        // Use custom capability for menu items
        $capability = current_user_can('manage_kdsamref_orders') ? 'manage_kdsamref_orders' : 'manage_woocommerce';
        
        // Main menu
        add_menu_page(
            __('KDS & Report for Orderable', 'kds-report-for-orderable'),
            __('KDS & Report for Orderable', 'kds-report-for-orderable'),
            $capability,
            'kdsamref-dashboard',
            array($this, 'admin_page'),
            'dashicons-food',
            56
        );

        // Dashboard submenu (same as main page)
        add_submenu_page(
            'kdsamref-dashboard',
            __('Order Dashboard', 'kds-report-for-orderable'),
            __('Dashboard', 'kds-report-for-orderable'),
            $capability,
            'kdsamref-dashboard',
            array($this, 'admin_page')
        );

        // Settings submenu
        add_submenu_page(
            'kdsamref-dashboard',
            __('Settings', 'kds-report-for-orderable'),
            __('Settings', 'kds-report-for-orderable'),
            $capability,
            'kdsamref-settings',
            array($this, 'settings_page')
        );
        
        // Custom Order Statuses submenu
        add_submenu_page(
            'kdsamref-dashboard',
            __('Custom Order Statuses', 'kds-report-for-orderable'),
            __('Order Statuses', 'kds-report-for-orderable'),
            $capability,
            'kdsamref-order-statuses',
            array($this, 'custom_status_page')
        );
        
        // Workflow Management submenu (Pro feature) – always visible, locked when not Pro
        $has_workflow = function_exists('kdsamref_has_feature') ? kdsamref_has_feature('workflows') : false;
        $workflow_title = __('Workflow', 'kds-report-for-orderable') . ($has_workflow ? '' : ' <i class="fas fa-lock"></i>');
        add_submenu_page(
            'kdsamref-dashboard',
            __('Workflow Management', 'kds-report-for-orderable'),
            $workflow_title,
            $capability,
            'kdsamref-workflow',
            array($this, 'workflow_page')
        );
        
        // Monthly Reports submenu (Pro feature) – always visible, locked when not Pro
        $has_monthly_reports = function_exists('kdsamref_has_feature') ? kdsamref_has_feature('monthly_reports') : false;
        $monthly_reports_title = __('Monthly Reports', 'kds-report-for-orderable') . ($has_monthly_reports ? '' : ' <i class="fas fa-lock"></i>');
        add_submenu_page(
            'kdsamref-dashboard',
            __('Monthly Reports', 'kds-report-for-orderable'),
            $monthly_reports_title,
            $capability,
            'kdsamref-monthly-reports',
            array($this, 'monthly_reports_page')
        );
        
        // Pro Features page - only visible when Pro is not active
        $is_pro_active = function_exists('kdsamref_is_pro_active') ? kdsamref_is_pro_active() : false;
        if (!$is_pro_active) {
            add_submenu_page(
                'kdsamref-dashboard',
                __('Pro Features', 'kds-report-for-orderable'),
                __('Pro Features', 'kds-report-for-orderable') . ' 🚀',
                $capability,
                'kdsamref-pro-features',
                array($this, 'pro_features_page')
            );
        }
        
    
    }

    /**
     * Admin page
     */
    public function admin_page() {
        include_once KDSAMREF_PLUGIN_PATH . 'templates/admin-dashboard.php';
    }

    /**
     * Settings page
     */
    public function settings_page() {
        include_once KDSAMREF_PLUGIN_PATH . 'templates/admin-settings.php';
    }
    
    /**
     * Custom status page
     */
    public function custom_status_page() {
        // Delegate to admin class
        if (isset($this->admin) && method_exists($this->admin, 'custom_status_page')) {
            $this->admin->custom_status_page();
        } else {
            echo '<div class="wrap"><h1>Custom Status Page</h1><p>Admin class not available.</p></div>';
        }
    }
    
    /**
     * Workflow page
     */
    public function workflow_page() {
        $has_workflow = function_exists('kdsamref_has_feature') ? kdsamref_has_feature('workflows') : false;
        if (!$has_workflow) {
            // Redirect to Pro Features page
            wp_redirect(admin_url('admin.php?page=kdsamref-pro-features'));
            exit;
        }
        if (isset($this->admin) && method_exists($this->admin, 'workflow_page')) {
            $this->admin->workflow_page();
        } else {
            echo '<div class="wrap"><h1>Workflow Page</h1><p>Admin class not available.</p></div>';
        }
    }
    
    /**
     * Monthly Reports page
     */
    public function monthly_reports_page() {
        // Gate by Pro feature
        $has_monthly_reports = function_exists('kdsamref_has_feature') ? kdsamref_has_feature('monthly_reports') : false;
        if (!$has_monthly_reports) {
            // Redirect to Pro Features page
            wp_redirect(admin_url('admin.php?page=kdsamref-pro-features'));
            exit;
        }
        
        // Compute and include monthly reports if available
        if (file_exists(KDSAMREF_PLUGIN_PATH . 'templates/monthly-reports.php')) {
            // Prepare inputs
            $current_month = isset($_GET['month']) ? sanitize_text_field($_GET['month']) : current_time('Y-m');
            $selected_category = isset($_GET['category']) ? intval($_GET['category']) : 0;

            // Fetch data via integration for consistency (handles HPOS, tips, etc.)
            if (!isset($this->monthly_reports_integration)) {
                require_once KDSAMREF_PLUGIN_PATH . 'includes/class-kdsamref-monthly-reports.php';
                $this->monthly_reports_integration = new KDSAMREF_Monthly_Reports_Integration();
            }

            $reports_data = $this->monthly_reports_integration->get_monthly_reports($current_month, $selected_category);
            $comparison_data = $this->monthly_reports_integration->get_monthly_comparison($current_month, $selected_category);
            $categories = $this->monthly_reports_integration->get_main_categories();

            // Extract variables for template
            extract(array(
                'current_month' => $current_month,
                'selected_category' => $selected_category,
                'reports_data' => $reports_data,
                'comparison_data' => $comparison_data,
                'categories' => $categories
            ));

            include_once KDSAMREF_PLUGIN_PATH . 'templates/monthly-reports.php';
        } else {
            echo '<div class="wrap"><h1>' . esc_html__('Monthly Reports', 'kds-report-for-orderable') . '</h1><p>' . esc_html__('Monthly reports template not found.', 'kds-report-for-orderable') . '</p></div>';
        }
    }
    
    /**
     * Pro Features page
     */
    public function pro_features_page() {
        include_once KDSAMREF_PLUGIN_PATH . 'templates/pro-features-page.php';
    }

    /**
     * Enqueue admin scripts
     */
    public function admin_scripts($hook) {
        
        // For other kdsamref pages
        if (strpos($hook, 'kdsamref-') !== false) {
            $enqueued_admin_js = false;
            // Check if this is the settings page
            if (strpos($hook, 'kdsamref-settings') !== false) {
                // Enqueue settings-specific CSS/JS
                wp_enqueue_style(
                    'kdsamref-settings-style',
                    KDSAMREF_PLUGIN_URL . 'assets/css/admin-settings.css',
                    array(),
                    KDSAMREF_VERSION
                );
                
                wp_enqueue_style(
                    'kdsamref-admin-settings-extended',
                    KDSAMREF_PLUGIN_URL . 'assets/css/admin-settings-extended.css',
                    array(),
                    KDSAMREF_VERSION
                );
                
                wp_enqueue_script(
                    'kdsamref-settings-script',
                    KDSAMREF_PLUGIN_URL . 'assets/js/admin-settings.js',
                    array('jquery'),
                    KDSAMREF_VERSION,
                    true
                );
                
                // Localize settings script
                wp_localize_script('kdsamref-settings-script', 'kdsamrefSettings', array(
                    'ajaxUrl' => admin_url('admin-ajax.php'),
                    'nonces' => array(
                        'license' => wp_create_nonce('kdsamref_license_nonce'),
                        'settings' => wp_create_nonce('kdsamref_settings')
                    ),
                    'strings' => array(
                        'automaticDetection' => __('Automatic Detection', 'kds-report-for-orderable'),
                        'orderableMode' => __('Orderable Mode (complete)', 'kds-report-for-orderable'),
                        'woocommerceMode' => __('WooCommerce Mode (standard)', 'kds-report-for-orderable'),
                        'selectedMode' => __('Selected mode: ', 'kds-report-for-orderable'),
                        'dontForgetToSave' => __('. Don\'t forget to save!', 'kds-report-for-orderable')
                    )
                ));
                
                // Also localize kdsamrefData for settings page compatibility
                wp_localize_script('kdsamref-settings-script', 'kdsamrefData', array(
                    'ajaxUrl' => admin_url('admin-ajax.php'),
                    'nonce' => wp_create_nonce('kdsamref_nonce')
                ));
            } else if (
                // Enqueue dashboard script ONLY on the actual dashboard page
                            $hook === 'toplevel_page_kdsamref-dashboard' ||
            $hook === 'kdsamref-dashboard_page_kdsamref-dashboard'
            ) {
                // Get current WordPress date and timezone info for dashboard
                $wp_timezone = wp_timezone();
                $current_wp_time = new DateTime('now', $wp_timezone);
                $yesterday_wp_time = new DateTime('yesterday', $wp_timezone);
                
                // Pro gating for auto-refresh
                $pro_active = function_exists('kdsamref_is_pro_active') ? kdsamref_is_pro_active() : false;
                
                // Admin settings for dashboard
                if (class_exists('KDSAMREF_Admin')) {
                    $admin = new KDSAMREF_Admin();
                    $settings = $admin->get_all_settings();
                    $custom_statuses = $settings['custom_statuses'] ?? array();
                } else {
                    $settings = array();
                    $custom_statuses = array();
                }
                
                // Map settings for JavaScript compatibility
                $js_settings = array(
                    'maxOrdersLimit' => $settings['max_orders_limit'] ?? 50,
                    'defaultFontSize' => $settings['default_font_size'] ?? 'medium',
                    'autoRefreshInterval' => $settings['auto_refresh_interval'] ?? 15,
                    'showCompletedOrders' => $settings['show_completed_orders'] ?? true,
                    'completedOrdersOpacity' => $settings['completed_orders_opacity'] ?? 0.6,
                    'compactMode' => $settings['compact_mode'] ?? false,
                    'deliveryBadgeColor' => $settings['delivery_badge_color'] ?? '#4ade80',
                    'pickupBadgeColor' => $settings['pickup_badge_color'] ?? '#a78bfa',
                    'dineInBadgeColor' => $settings['dine_in_badge_color'] ?? '#60a5fa',
                    'enable_notifications' => $settings['enable_notifications'] ?? true,
                    'notification_sound' => $settings['notification_sound'] ?? 1,
                    'notification_volume' => $settings['notification_volume'] ?? 0.5,
                    'disable_refresh_notifications' => $settings['disable_refresh_notifications'] ?? false,
                    'show_order_numbers' => $settings['show_order_numbers'] ?? true,
                    'show_customer_names' => $settings['show_customer_names'] ?? true,
                    'show_product_options' => $settings['show_product_options'] ?? true,
                    'show_tips' => $settings['show_tips'] ?? true,
                    'show_fees' => $settings['show_fees'] ?? true,
                );
                
                // Dashboard CSS/JS
                wp_enqueue_style(
                    'kdsamref-admin-style',
                    KDSAMREF_PLUGIN_URL . 'assets/css/admin.css',
                    array(),
                    KDSAMREF_VERSION
                );

                wp_enqueue_script(
                    'kdsamref-admin-script',
                    KDSAMREF_PLUGIN_URL . 'assets/js/admin.js',
                    array('jquery'),
                    KDSAMREF_VERSION,
                    true
                );
                
                    // Enqueue FontAwesome
    wp_enqueue_style(
        'kdsamref-fontawesome',
        KDSAMREF_PLUGIN_URL . 'assets/fonts/fontawesome/css/all.min.css',
        array(),
        '6.4.0'
    );
    
    // Enqueue dashboard extended styles
    wp_enqueue_style(
        'kdsamref-admin-dashboard-extended',
        KDSAMREF_PLUGIN_URL . 'assets/css/admin-dashboard-extended.css',
        array('kdsamref-fontawesome'),
        KDSAMREF_VERSION
    );
                
                // Localize data for dashboard
                wp_localize_script('kdsamref-admin-script', 'kdsamrefData', array(
                    'customStatuses' => $custom_statuses,
                    'ajaxUrl' => admin_url('admin-ajax.php'),
                    'pluginUrl' => KDSAMREF_PLUGIN_URL,
                    'nonce' => wp_create_nonce('kdsamref_nonce'),
                    'settings' => $js_settings,
                    // WordPress timezone data
                    'currentWpDate' => $current_wp_time->format('Y-m-d'),
                    'yesterdayWpDate' => $yesterday_wp_time->format('Y-m-d'),
                    'tomorrowWpDate' => (clone $current_wp_time)->modify('+1 day')->format('Y-m-d'),
                    'wpTimezoneOffset' => $wp_timezone->getOffset($current_wp_time) / 3600
                ));
                

            } else if (
                // Enqueue monthly reports CSS
                strpos($hook, 'kdsamref-monthly-reports') !== false
            ) {
                wp_enqueue_style(
                    'kdsamref-monthly-reports-style',
                    KDSAMREF_PLUGIN_URL . 'assets/css/monthly-reports.css',
                    array(),
                    KDSAMREF_VERSION
                );
                
            } else if (strpos($hook, 'kdsamref-order-statuses') !== false) {
                // Custom status page CSS
                wp_enqueue_style(
                    'kdsamref-custom-status-style',
                    KDSAMREF_PLUGIN_URL . 'assets/css/custom-status-page.css',
                    array(),
                    KDSAMREF_VERSION
                );
                
                // Custom status page scripts
                wp_enqueue_script(
                    'kdsamref-custom-status-script',
                    KDSAMREF_PLUGIN_URL . 'assets/js/custom-status-page.js',
                    array('jquery'),
                    KDSAMREF_VERSION,
                    true
                );
                
            } else if (strpos($hook, 'kdsamref-workflow') !== false) {
                
                // Workflow page CSS
                wp_enqueue_style(
                    'kdsamref-workflow-style',
                    KDSAMREF_PLUGIN_URL . 'assets/css/workflow-page.css',
                    array(),
                    KDSAMREF_VERSION
                );
                
            } else if (strpos($hook, 'kdsamref-pro-features') !== false) {
                // Pro Features page CSS
                wp_enqueue_style(
                    'kdsamref-pro-features-style',
                    KDSAMREF_PLUGIN_URL . 'assets/css/pro-features-page.css',
                    array(),
                    KDSAMREF_VERSION
                );
                
                // Pro Features page JavaScript
                wp_enqueue_script(
                    'kdsamref-pro-features-script',
                    KDSAMREF_PLUGIN_URL . 'assets/js/pro-features-page.js',
                    array('jquery'),
                    KDSAMREF_VERSION,
                    true
                );
                
                // Workflow page scripts
                wp_enqueue_script(
                    'kdsamref-workflow-script',
                    KDSAMREF_PLUGIN_URL . 'assets/js/workflow-page.js',
                    array('jquery', 'jquery-ui-sortable'),
                    KDSAMREF_VERSION,
                    true
                );
                
                // Get custom statuses for localization
                if (class_exists('KDSAMREF_Admin')) {
                    $admin = new KDSAMREF_Admin();
                    $settings = $admin->get_all_settings();
                    $custom_statuses = $settings['custom_statuses'] ?? array();
                } else {
                    $custom_statuses = array();
                }
                
                // Localize data for workflow page
                wp_localize_script('kdsamref-workflow-script', 'kdsamrefData', array(
                    'customStatuses' => $custom_statuses,
                    'ajaxUrl' => admin_url('admin-ajax.php'),
                    'pluginUrl' => KDSAMREF_PLUGIN_URL,
                    'nonce' => wp_create_nonce('kdsamref_workflow')
                ));
                
                // Get custom statuses for dashboard
                if (class_exists('KDSAMREF_Admin')) {
                    $admin = new KDSAMREF_Admin();
                    $settings = $admin->get_all_settings();
                    $custom_statuses = $settings['custom_statuses'] ?? array();
                } else {
                    $custom_statuses = array();
                }
                
                // Get current WordPress date and timezone info for dashboard
                $wp_timezone = wp_timezone();
                $current_wp_time = new DateTime('now', $wp_timezone);
                $yesterday_wp_time = new DateTime('yesterday', $wp_timezone);
                
                // Localize custom statuses for dashboard
                wp_localize_script('kdsamref-admin-script', 'kdsamrefCustomStatuses', $custom_statuses);
                
                                // Get settings for dashboard
                if (class_exists('KDSAMREF_Admin')) {
                    $admin = new KDSAMREF_Admin();
                    $dashboard_settings = $admin->get_all_settings();
                } else {
                    $dashboard_settings = array();
                }
                
                // Map settings for JavaScript compatibility
                $js_settings = array(
                    'maxOrdersLimit' => $dashboard_settings['max_orders_limit'] ?? 100,
                    'defaultFontSize' => $dashboard_settings['default_font_size'] ?? 14,
                    'autoRefreshInterval' => $dashboard_settings['auto_refresh_interval'] ?? 15,
                    'showCompletedOrders' => $dashboard_settings['show_completed_orders'] ?? true,
                    'completedOrdersOpacity' => $dashboard_settings['completed_orders_opacity'] ?? 0.5,
                    'compactMode' => $dashboard_settings['compact_mode'] ?? false,
                    'deliveryBadgeColor' => $dashboard_settings['delivery_badge_color'] ?? '#4ade80',
                    'pickupBadgeColor' => $dashboard_settings['pickup_badge_color'] ?? '#a78bfa',
                    'dineInBadgeColor' => $dashboard_settings['dine_in_badge_color'] ?? '#60a5fa',
                    'enable_notifications' => $dashboard_settings['enable_notifications'] ?? true,
                    'notification_sound' => $dashboard_settings['notification_sound'] ?? 1,
                    'notification_volume' => $dashboard_settings['notification_volume'] ?? 0.5,
                    'disable_refresh_notifications' => $dashboard_settings['disable_refresh_notifications'] ?? false,
                    'show_order_numbers' => $dashboard_settings['show_order_numbers'] ?? true,
                    'show_customer_names' => $dashboard_settings['show_customer_names'] ?? true,
                    'show_product_options' => $dashboard_settings['show_product_options'] ?? true,
                    'show_tips' => $dashboard_settings['show_tips'] ?? true,
                    'show_fees' => $dashboard_settings['show_fees'] ?? true,
                );
                
                // Localize data for main admin script
                wp_localize_script('kdsamref-admin-script', 'kdsamrefData', array(
                    'customStatuses' => $custom_statuses,
                    'ajaxUrl' => admin_url('admin-ajax.php'),
                    'pluginUrl' => plugin_dir_url(__FILE__),
                    'nonce' => wp_create_nonce('kdsamref_nonce'),
                    'settings' => $js_settings,
                    // WordPress timezone data
                    'currentWpDate' => $current_wp_time->format('Y-m-d'),
                    'yesterdayWpDate' => $yesterday_wp_time->format('Y-m-d'),
                    'tomorrowWpDate' => (clone $current_wp_time)->modify('+1 day')->format('Y-m-d'),
                    'wpTimezoneOffset' => $wp_timezone->getOffset($current_wp_time) / 3600
                ));
                

                
                $enqueued_admin_js = true;
            }
        }
        
        // Common JavaScript data for all kdsamref pages
        if (strpos($hook, 'kdsamref-') !== false) {
            // Get current WordPress date and timezone info
            $wp_timezone = wp_timezone();
            $current_wp_time = new DateTime('now', $wp_timezone);
            $yesterday_wp_time = new DateTime('yesterday', $wp_timezone);
            
            // Pro gating for auto-refresh
            $pro_active = function_exists('kdsamref_is_pro_active') ? kdsamref_is_pro_active() : false;
            

            
            // Admin settings
            if (class_exists('KDSAMREF_Admin')) {
                $admin = new KDSAMREF_Admin();
                $settings = $admin->get_all_settings();
                $custom_statuses = $settings['custom_statuses'] ?? array();
            } else {
                $settings = array();
                $custom_statuses = array();
            }
            
            // Determine auto refresh interval based on Pro status
            $auto_refresh_interval = $pro_active ? (int) ($settings['auto_refresh_interval'] ?? 15) : 0;
            
            // Check if Orderable is active (simplified)
            $orderable_active = class_exists('Orderable') || class_exists('Orderable_Main') || function_exists('orderable_init');
            
            // Get active plugins for detection
            $active_plugins = get_option('active_plugins', array());
            foreach ($active_plugins as $plugin) {
                if (strpos($plugin, 'orderable') !== false) {
                    $orderable_active = true;
                    break;
                }
            }
            
            // Map settings for JavaScript compatibility
            $js_settings = array(
                'maxOrdersLimit' => $settings['max_orders_limit'],
                'defaultFontSize' => $settings['default_font_size'],
                'autoRefreshInterval' => $auto_refresh_interval,
                'showCompletedOrders' => $settings['show_completed_orders'],
                'completedOrdersOpacity' => $settings['completed_orders_opacity'],
        
                'compactMode' => $settings['compact_mode'],
                'deliveryBadgeColor' => $settings['delivery_badge_color'],
                'pickupBadgeColor' => $settings['pickup_badge_color'],
                'dineInBadgeColor' => $settings['dine_in_badge_color'],
                // UI colors (camelCase for JS)
                'borderColorPrimary' => $settings['border_color_primary'] ?? null,
                'borderColorSecondary' => $settings['border_color_secondary'] ?? null,
                'cardBackgroundColor' => $settings['card_background_color'] ?? null,
                'dashboardBackgroundColor' => $settings['dashboard_background_color'] ?? null,
                'enable_notifications' => $settings['enable_notifications'],
                'notification_sound' => $settings['notification_sound'],
                'notification_volume' => $settings['notification_volume'],
                'disable_refresh_notifications' => $settings['disable_refresh_notifications'] ?? false,
                'show_order_numbers' => $settings['show_order_numbers'],
                'show_customer_names' => $settings['show_customer_names'],
                'show_product_options' => $settings['show_product_options'],
                'show_tips' => $settings['show_tips'],
                'show_fees' => $settings['show_fees'],
            );

            // Localize dashboard data for all kdsamref pages
            wp_localize_script('kdsamref-admin-script', 'kdsamrefData', array(
                'customStatuses' => $custom_statuses,
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'pluginUrl' => plugin_dir_url(__FILE__),
                'nonce' => wp_create_nonce('kdsamref_nonce'),
                // Pro status for UI gating
                'proActive' => $pro_active,
                // License shape kept for backward compatibility with JS
                'license' => array(
                    'valid' => $pro_active,
                    'is_premium' => $pro_active,
                    'realtime_enabled' => $pro_active,
                ),
                'realTimeEnabled' => $pro_active,
                'proLink' => 'https://codeon.ch/orderable-kds',
                'settings' => $js_settings,
                // Orderable integration status
                'orderableActive' => $orderable_active,
                'orderableMode' => $orderable_active ? 'orderable' : 'woocommerce',
                'compatibilityMode' => $orderable_active ? 'orderable' : 'woocommerce',
                // WordPress timezone data
                'wpTimezoneOffset' => $wp_timezone->getOffset($current_wp_time) / 3600,
                'currentWpDate' => $current_wp_time->format('Y-m-d'),
                'yesterdayWpDate' => $yesterday_wp_time->format('Y-m-d'),
                // Auto-refresh: 0 when Pro inactive
                'autoRefresh' => $auto_refresh_interval,
                // Status labels for CSS
                'statusLabels' => array(
                    'completed' => __('Completed', 'kds-report-for-orderable'),
                    'processing' => __('Processing', 'kds-report-for-orderable'),
                    'ready' => __('Ready', 'kds-report-for-orderable'),
                    'cooking' => __('Cooking', 'kds-report-for-orderable')
                ),
                'strings' => array(
                    'error' => __('Error occurred', 'kds-report-for-orderable'),
                    'loading' => __('Loading...', 'kds-report-for-orderable'),
                    'updated' => __('Updated successfully', 'kds-report-for-orderable'),
                    'orderError' => __('Error loading orders', 'kds-report-for-orderable'),
                    'connectionError' => __('Connection error', 'kds-report-for-orderable'),
                    'premiumFeature' => __('This is a premium feature. Please upgrade your license.', 'kds-report-for-orderable'),
                    'deliveryTypes' => array(
                        'emporter' => __('À Emporter', 'kds-report-for-orderable'),
                        'livraison' => __('Livraison', 'kds-report-for-orderable'),
                        'surplace' => __('Sur Place', 'kds-report-for-orderable'),
                        // WooCommerce mode types
                        'numerique' => __('Numérique', 'kds-report-for-orderable'),
                        'point-vente' => __('Point de Vente', 'kds-report-for-orderable'),
                        'retrait' => __('Retrait', 'kds-report-for-orderable')
                    ),
                    'labels' => array(
                        'table' => __('Table', 'kds-report-for-orderable'),
                        'total' => __('Total', 'kds-report-for-orderable'),
                        'tip' => __('Tips', 'kds-report-for-orderable')
                    ),
                    // JavaScript translations
                    'js' => array(
                        // Notifications
                        'newOrdersTitle' => __('New Orders!', 'kds-report-for-orderable'),
                        'newOrdersBody' => __('new order(s) received', 'kds-report-for-orderable'),
                        'notificationsAuthorized' => __('Notifications authorized! 🔔', 'kds-report-for-orderable'),
                        'orderUpdated' => __('Order updated!', 'kds-report-for-orderable'),
                        'orderNotFound' => __('Order not found', 'kds-report-for-orderable'),
                        'updateError' => __('Error during update', 'kds-report-for-orderable'),
                        'connectionError' => __('Connection error', 'kds-report-for-orderable'),
                        
                        // Modal content
                        'orderInformation' => __('Order Information', 'kds-report-for-orderable'),
                        'number' => __('Number', 'kds-report-for-orderable'),
                        'date' => __('Date', 'kds-report-for-orderable'),
                        'status' => __('Status', 'kds-report-for-orderable'),
                        'type' => __('Type', 'kds-report-for-orderable'),
                        'scheduled' => __('Scheduled', 'kds-report-for-orderable'),
                        'customer' => __('Customer', 'kds-report-for-orderable'),
                        'name' => __('Name', 'kds-report-for-orderable'),
                        'phone' => __('Phone', 'kds-report-for-orderable'),
                        'email' => __('Email', 'kds-report-for-orderable'),
                        'deliveryAddress' => __('Delivery Address', 'kds-report-for-orderable'),
                        'orderedItems' => __('Ordered Items', 'kds-report-for-orderable'),
                        'orderableDetails' => __('Orderable Details', 'kds-report-for-orderable'),
                        'location' => __('Location', 'kds-report-for-orderable'),
                        'specialInstructions' => __('Special Instructions', 'kds-report-for-orderable'),
                        
                        // UI elements
                        'all' => __('All', 'kds-report-for-orderable'),
                        'justNow' => __('Just now', 'kds-report-for-orderable'),
                        'exitFullscreen' => __('Exit fullscreen', 'kds-report-for-orderable'),
                        'fullscreen' => __('Fullscreen', 'kds-report-for-orderable'),
                        'fullscreenEnabled' => __('Fullscreen mode enabled! 🖥️', 'kds-report-for-orderable'),
                        'normalModeRestored' => __('Normal mode restored! 📱', 'kds-report-for-orderable'),
                        'completed' => __('Completed', 'kds-report-for-orderable'),
                        
                        // Time ago
                        'minAgo' => __('min ago', 'kds-report-for-orderable'),
                        'hAgo' => __('h ago', 'kds-report-for-orderable'),
                        'daysAgo' => __('days ago', 'kds-report-for-orderable'),
                        
                        // Refresh notifications
                        'refreshStarted' => __('Refresh started...', 'kds-report-for-orderable'),
                        'refreshCompleted' => __('Refresh completed!', 'kds-report-for-orderable'),
                        'autoRefresh' => __('Auto-refresh...', 'kds-report-for-orderable')
                    )
                )
                ));
        }
    }

    /**
     * Register custom order statuses
     */
    public function register_custom_order_statuses() {
        // Register default custom statuses
        register_post_status('wc-ready-pickup', array(
            'label' => _x('Ready for Pickup', 'Order status', 'kds-report-for-orderable'),
            '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('Ready for Pickup <span class="count">(%s)</span>', 'Ready for Pickup <span class="count">(%s)</span>', 'kds-report-for-orderable')
        ));

        register_post_status('wc-preparing', array(
            'label' => _x('Preparing', 'Order status', 'kds-report-for-orderable'),
            '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('Preparing <span class="count">(%s)</span>', 'Preparing <span class="count">(%s)</span>', 'kds-report-for-orderable')
        ));
        
        // Register custom statuses from settings
        if (class_exists('KDSAMREF_Admin')) {
            $admin = new KDSAMREF_Admin();
            $admin->register_custom_statuses_with_wc();
        }
    }

    /**
     * Add custom order statuses to WooCommerce
     */
    public function add_custom_order_statuses($order_statuses) {
        $new_order_statuses = array();

        foreach ($order_statuses as $key => $status) {
            $new_order_statuses[$key] = $status;
            
            if ('wc-processing' === $key) {
                $new_order_statuses['wc-preparing'] = _x('Preparing', 'Order status', 'kds-report-for-orderable');
                $new_order_statuses['wc-ready-pickup'] = _x('Ready for Pickup', 'Order status', 'kds-report-for-orderable');
            }
        }
        
        // Add custom statuses from settings
        if (class_exists('KDSAMREF_Admin')) {
            $admin = new KDSAMREF_Admin();
            $new_order_statuses = $admin->add_custom_statuses_to_wc($new_order_statuses);
        }

        return $new_order_statuses;
    }

    /**
     * Add custom order actions to admin panel
     */
    public function add_custom_order_actions($actions, $order) {
        if (class_exists('KDSAMREF_Admin')) {
            $admin = new KDSAMREF_Admin();
            return $admin->add_custom_order_actions($actions, $order);
        }
        return $actions;
    }

    /**
     * Add custom bulk actions
     */
    public function add_custom_bulk_actions($actions) {
        if (class_exists('KDSAMREF_Admin')) {
            $admin = new KDSAMREF_Admin();
            return $admin->add_custom_bulk_actions($actions);
        }
        return $actions;
    }

    /**
     * Add custom meta boxes
     */
    public function add_order_meta_boxes() {
        add_meta_box(
            'kdsamref_delivery_info',
            __('Restaurant Delivery Info', 'kds-report-for-orderable'),
            array($this, 'delivery_info_meta_box'),
            'shop_order',
            'side',
            'high'
        );
    }

    /**
     * Delivery info meta box
     */
    public function delivery_info_meta_box($post) {
        $delivery_type = get_post_meta($post->ID, '_kdsamref_delivery_type', true);
        $table_number = get_post_meta($post->ID, '_kdsamref_table_number', true);
        $pickup_time = get_post_meta($post->ID, '_kdsamref_pickup_time', true);
        $special_instructions = get_post_meta($post->ID, '_kdsamref_special_instructions', true);
        
        wp_nonce_field('kdsamref_save_meta', 'kdsamref_meta_nonce');
        ?>
        <p>
            <label for="kdsamref_delivery_type"><?php esc_html_e('Delivery Type:', 'kds-report-for-orderable'); ?></label>
            <select name="kdsamref_delivery_type" id="kdsamref_delivery_type" style="width: 100%;">
                <option value="livraison" <?php selected($delivery_type, 'livraison'); ?>><?php esc_html_e('Delivery', 'kds-report-for-orderable'); ?></option>
                <option value="emporter" <?php selected($delivery_type, 'emporter'); ?>><?php esc_html_e('Takeaway', 'kds-report-for-orderable'); ?></option>
                <option value="surplace" <?php selected($delivery_type, 'surplace'); ?>><?php esc_html_e('Dine In', 'kds-report-for-orderable'); ?></option>
            </select>
        </p>
        <p>
            <label for="kdsamref_table_number"><?php esc_html_e('Table Number:', 'kds-report-for-orderable'); ?></label>
            <input type="text" name="kdsamref_table_number" id="kdsamref_table_number" value="<?php echo esc_attr($table_number); ?>" style="width: 100%;" />
        </p>
        <p>
            <label for="kdsamref_pickup_time"><?php esc_html_e('Pickup Time:', 'kds-report-for-orderable'); ?></label>
            <input type="datetime-local" name="kdsamref_pickup_time" id="kdsamref_pickup_time" value="<?php echo esc_attr($pickup_time); ?>" style="width: 100%;" />
        </p>
        <p>
            <label for="kdsamref_special_instructions"><?php esc_html_e('Special Instructions:', 'kds-report-for-orderable'); ?></label>
            <textarea name="kdsamref_special_instructions" id="kdsamref_special_instructions" rows="3" style="width: 100%;"><?php echo esc_textarea($special_instructions); ?></textarea>
        </p>
        <?php
    }

    /**
     * Save order meta
     */
    public function save_order_meta($post_id) {
        if (!isset($_POST['kdsamref_meta_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['kdsamref_meta_nonce'])), 'kdsamref_save_meta')) {
            return;
        }

        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        $fields = array(
            '_kdsamref_delivery_type',
            '_kdsamref_table_number',
            '_kdsamref_pickup_time',
            '_kdsamref_special_instructions'
        );

        foreach ($fields as $field) {
            $key = str_replace('_kdsamref_', 'kdsamref_', $field);
            if (isset($_POST[$key])) {
                update_post_meta($post_id, $field, sanitize_text_field($_POST[$key]));
            }
        }
    }

    /**
     * AJAX: Get orders
     */
    public function ajax_get_orders() {
        check_ajax_referer('kdsamref_nonce', 'nonce');

        if (!$this->user_can_access_kdsamref_orders()) {
            wp_die(esc_html__('Permission denied', 'kds-report-for-orderable'));
        }

        $status = isset($_POST['status']) ? sanitize_text_field($_POST['status']) : 'any';
        $orders = $this->order_manager->get_orders($status);
        $stats = $this->order_manager->get_order_statistics();
        
        // Get license info for frontend
        $license_info = array(
            'is_premium' => false,
            'order_limit' => 4,
            'realtime_enabled' => false
        );
        
        if (isset($this->license_manager) && $this->license_manager) {
            $license_info = $this->license_manager->get_license_info();
        }

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

    /**
     * AJAX: Update order status
     */
    public function ajax_update_order_status() {
        check_ajax_referer('kdsamref_nonce', 'nonce');

        if (!$this->user_can_access_kdsamref_orders()) {
            wp_die(esc_html__('Permission denied', 'kds-report-for-orderable'));
        }

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

        if (!$order_id || !$new_status) {
            wp_send_json_error(esc_html__('Invalid parameters', 'kds-report-for-orderable'));
        }

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

        if ($result) {
            wp_send_json_success(esc_html__('Order status updated', 'kds-report-for-orderable'));
        } else {
            wp_send_json_error(esc_html__('Failed to update order status', 'kds-report-for-orderable'));
        }
    }



    /**
     * AJAX: Get order statistics
     */
    public function ajax_get_order_stats() {
        check_ajax_referer('kdsamref_nonce', 'nonce');

        if (!$this->user_can_access_kdsamref_orders()) {
            wp_die(esc_html__('Permission denied', 'kds-report-for-orderable'));
        }

        $stats = $this->order_manager->get_order_statistics();
        wp_send_json_success($stats);
    }

    /**
     * AJAX: Validate license
     */
    public function ajax_validate_license() {
        if (isset($this->license_manager) && method_exists($this->license_manager, 'ajax_validate_license')) {
            $this->license_manager->ajax_validate_license();
        } else {
            wp_send_json_error(array('message' => 'License manager not available'));
        }
    }

    /**
     * AJAX: Remove license
     */
    public function ajax_remove_license() {
        if (isset($this->license_manager) && method_exists($this->license_manager, 'ajax_remove_license')) {
            $this->license_manager->ajax_remove_license();
        } else {
            wp_send_json_error(array('message' => 'License manager not available'));
        }
    }

    

    /**
     * AJAX: Refresh license info
     */
    public function ajax_refresh_license_info() {
        check_ajax_referer('kdsamref_license_nonce', 'nonce');

        if (!$this->user_can_access_kdsamref_orders()) {
            wp_die(esc_html__('Permission denied', 'kds-report-for-orderable'));
        }

        if (isset($this->license_manager) && method_exists($this->license_manager, 'ajax_refresh_license_info')) {
            $this->license_manager->ajax_refresh_license_info();
        } else {
            wp_send_json_error(array('message' => 'License manager not available'));
        }
    }



    /**
     * AJAX: Get orders by date range - DEPRECATED: Now handled by KDSAMREF_Ajax_Handler
     */
    /*
    public function ajax_get_orders_by_date_range() {
        check_ajax_referer('kdsamref_nonce', 'nonce');

        if (!$this->user_can_access_kdsamref_orders()) {
            wp_die(esc_html__('Permission denied', 'kds-report-for-orderable'));
        }

        $start_date = isset($_POST['start_date']) ? sanitize_text_field($_POST['start_date']) : '';
        $end_date = isset($_POST['end_date']) ? sanitize_text_field($_POST['end_date']) : '';
        $limit = isset($_POST['limit']) ? intval($_POST['limit']) : 100;

        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
        );
        
        // Get orders using date range
        $args = array(
            'limit' => $limit,
            'orderby' => 'date',
            'order' => 'DESC',
            'return' => 'objects',
            'type' => 'shop_order',
            'status' => array('processing', 'preparing', 'ready-pickup', 'completed'),
            'date_created' => $date_range,
        );
        
        // Apply license restrictions
        if (isset($this->license_manager) && $this->license_manager) {
            $license_info = $this->license_manager->get_license_info();
            if (!$license_info['is_premium'] && $license_info['order_limit'] > 0) {
                $args['limit'] = min($limit, $license_info['order_limit']);
            }
        }
        
        $orders = wc_get_orders($args);
        $formatted_orders = array();
        
        foreach ($orders as $order) {
            $order_data = $this->order_manager->format_order_data($order);
            if ($order_data) {
                $formatted_orders[] = $order_data;
            }
        }
        
        // Filter out forbidden statuses (Orderable-focused)
        $forbidden_statuses = array('checkout-draft', 'wc-checkout-draft');
        
        $formatted_orders = array_filter($formatted_orders, function($order) use ($forbidden_statuses) {
            // Only filter truly problematic statuses
            return !in_array($order['status'], $forbidden_statuses);
        });
        
        $stats = $this->order_manager->get_order_statistics();
        
        // Get license info for frontend
        $license_info = array(
            'is_premium' => false,
            'order_limit' => 4,
            'realtime_enabled' => false
        );
        
        if (isset($this->license_manager) && $this->license_manager) {
            $license_info = $this->license_manager->get_license_info();
        }
        
        wp_send_json_success(array(
            'orders' => array_values($formatted_orders),
            'stats' => $stats,
            'license_info' => $license_info,
            'debug_24h' => $debug_24h
        ));
    }
    */

    /**
     * Enqueue admin styles for specific pages
     */
    public function admin_enqueue_styles() {
        global $hook_suffix;
        
        if (strpos($hook_suffix, 'kdsamref-order-statuses') !== false) {
            // Register and enqueue FontAwesome
            wp_register_style(
                'kdsamref-fontawesome',
                KDSAMREF_PLUGIN_URL . 'assets/fonts/fontawesome/css/all.min.css',
                array(),
                '6.4.0'
            );
            wp_enqueue_style('kdsamref-fontawesome');
            
            // Register and enqueue custom status page CSS
            wp_register_style(
                'kdsamref-custom-status-page',
                KDSAMREF_PLUGIN_URL . 'assets/css/custom-status-page.css',
                array('kdsamref-fontawesome'),
                KDSAMREF_VERSION
            );
            wp_enqueue_style('kdsamref-custom-status-page');
        } else if (strpos($hook_suffix, 'kdsamref-workflow') !== false) {
            // Register and enqueue FontAwesome
            wp_register_style(
                'kdsamref-fontawesome',
                KDSAMREF_PLUGIN_URL . 'assets/fonts/fontawesome/css/all.min.css',
                array(),
                '6.4.0'
            );
            wp_enqueue_style('kdsamref-fontawesome');
            
            // Register and enqueue workflow page CSS
            wp_register_style(
                'kdsamref-workflow-page',
                KDSAMREF_PLUGIN_URL . 'assets/css/workflow-page.css',
                array('kdsamref-fontawesome'),
                KDSAMREF_VERSION
            );
            wp_enqueue_style('kdsamref-workflow-page');
        }
    }
    


    /**
     * Enqueue admin scripts for specific pages
     */
    public function admin_enqueue_scripts() {
        global $hook_suffix;
        
        if (strpos($hook_suffix, 'kdsamref-order-statuses') !== false) {
            // Register and enqueue custom status page JS
            wp_register_script(
                'kdsamref-custom-status-page',
                KDSAMREF_PLUGIN_URL . 'assets/js/custom-status-page.js',
                array('jquery'),
                KDSAMREF_VERSION,
                true
            );
            wp_enqueue_script('kdsamref-custom-status-page');
            
            // Get custom statuses for localization
            if (class_exists('KDSAMREF_Admin')) {
                $admin = new KDSAMREF_Admin();
                $settings = $admin->get_all_settings();
                $custom_statuses = $settings['custom_statuses'] ?? array();
            } else {
                $custom_statuses = array();
            }
            
            // Localize script with data
            wp_localize_script('kdsamref-custom-status-page', 'kdsamrefData', array(
                'customStatuses' => $custom_statuses,
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'pluginUrl' => KDSAMREF_PLUGIN_URL,
                'nonce' => wp_create_nonce('kdsamref_custom_status')
            ));
        } else if (strpos($hook_suffix, 'kdsamref-workflow') !== false) {
            // Register and enqueue workflow page JS
            wp_register_script(
                'kdsamref-workflow-page',
                KDSAMREF_PLUGIN_URL . 'assets/js/workflow-page.js',
                array('jquery', 'jquery-ui-sortable'),
                KDSAMREF_VERSION,
                true
            );
            wp_enqueue_script('kdsamref-workflow-page');
            
            // Get custom statuses for localization
            if (class_exists('KDSAMREF_Admin')) {
                $admin = new KDSAMREF_Admin();
                $settings = $admin->get_all_settings();
                $custom_statuses = $settings['custom_statuses'] ?? array();
            } else {
                $custom_statuses = array();
            }
            
            // Localize script with data
            wp_localize_script('kdsamref-workflow-page', 'kdsamrefData', array(
                'customStatuses' => $custom_statuses,
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'pluginUrl' => KDSAMREF_PLUGIN_URL,
                'nonce' => wp_create_nonce('kdsamref_workflow')
            ));
        }
    }
}

/**
 * Initialize the plugin
 */
// Global for backwards compatibility
$GLOBALS['kdsamref_restaurant_orders'] = KDSAMREF_Main::instance();

/**
 * Pro detection helpers (Core → consumed by Pro via filters)
 */
if (!function_exists('kdsamref_is_pro_active')) {
    function kdsamref_is_pro_active() {
        return (bool) apply_filters('kdsamref/is_pro_active', false);
    }
}

if (!function_exists('kdsamref_has_feature')) {
    function kdsamref_has_feature($feature) {
        $features = (array) apply_filters('kdsamref/features', array());
        return !empty($features[$feature]);
    }
}
