<?php

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

// Require tab classes
require_once FLOWDINO_PLUGIN_PATH . 'includes/tabs/class-flowdino-wc-settings-tab.php';
require_once FLOWDINO_PLUGIN_PATH . 'includes/tabs/class-flowdino-wc-products-tab.php';
require_once FLOWDINO_PLUGIN_PATH . 'includes/tabs/class-flowdino-wc-categories-tab.php';
require_once FLOWDINO_PLUGIN_PATH . 'includes/tabs/class-flowdino-wc-brands-tab.php';
require_once FLOWDINO_PLUGIN_PATH . 'includes/tabs/class-flowdino-wc-colors-tab.php';
require_once FLOWDINO_PLUGIN_PATH . 'includes/tabs/class-flowdino-wc-materials-tab.php';
require_once FLOWDINO_PLUGIN_PATH . 'includes/tabs/class-flowdino-wc-sizes-tab.php';
require_once FLOWDINO_PLUGIN_PATH . 'includes/tabs/class-flowdino-wc-videogameratings-tab.php';
require_once FLOWDINO_PLUGIN_PATH . 'includes/tabs/class-flowdino-wc-tags-tab.php';
require_once FLOWDINO_PLUGIN_PATH . 'includes/tabs/class-flowdino-wc-variation-tab.php';
require_once FLOWDINO_PLUGIN_PATH . 'includes/tabs/class-flowdino-wc-help-tab.php';
require_once FLOWDINO_PLUGIN_PATH . 'includes/tabs/class-flowdino-wc-sales-tab.php';

/**
 * Admin interface for FlowDino
 */
class FlowDino_WC_Admin {
    
    /**
     * Constructor
     */
    public function __construct() {
        add_action('admin_init', array($this, 'init_settings'));
        
        // AJAX hooks for brand search
        add_action('wp_ajax_flowdino_search_brands', array($this, 'ajax_search_brands'));
        add_action('wp_ajax_nopriv_flowdino_search_brands', array($this, 'ajax_search_brands'));

        // AJAX hook for brand creation
        add_action('wp_ajax_flowdino_create_brand', array($this, 'ajax_create_brand'));
        
        // AJAX hooks for colors search
        add_action('wp_ajax_flowdino_search_colors', array($this, 'ajax_search_colors'));
        add_action('wp_ajax_nopriv_flowdino_search_colors', array($this, 'ajax_search_colors'));
        
        // AJAX hooks for connection test
        add_action('wp_ajax_flowdino_test_connection', array($this, 'ajax_test_connection'));
        
        // AJAX hooks for advanced debug
        add_action('wp_ajax_flowdino_debug_advanced', array($this, 'ajax_debug_advanced'));
        
        // AJAX hooks for force reconnect
        add_action('wp_ajax_flowdino_force_reconnect', array($this, 'ajax_force_reconnect'));
        
        // AJAX hook for product synchronization
        add_action('wp_ajax_flowdino_sync_single_product', array($this, 'ajax_sync_single_product'));
        
        // AJAX hook for non-compliant products check
        add_action('wp_ajax_flowdino_get_non_compliant_products', array($this, 'ajax_get_non_compliant_products'));
        
        // AJAX hook for checking selected products compliance
        add_action('wp_ajax_flowdino_check_selected_products_compliance', array($this, 'ajax_check_selected_products_compliance'));
        
        // AJAX hook for refreshing product statistics in banner
        add_action('wp_ajax_flowdino_refresh_product_stats', array($this, 'ajax_refresh_product_stats'));

        // AJAX hook for fetching product updates from FlowDino (pull stock/status)
        add_action('wp_ajax_flowdino_fetch_product_updates', array($this, 'ajax_fetch_product_updates'));

        // AJAX hook for sales synchronisation
        add_action('wp_ajax_flowdino_sync_sales', array($this, 'ajax_sync_sales'));
    }
    
    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_submenu_page(
            'woocommerce',
            __('FlowDino', 'flowdino'),
            __('FlowDino', 'flowdino'),
            'manage_woocommerce',
            'flowdino-sync',
            array($this, 'admin_page')
        );
    }
    
    /**
     * Initialize settings
     */
    public function init_settings() {
        register_setting('flowdino_settings', 'flowdino_email', array(
            'sanitize_callback' => 'sanitize_email'
        ));
        register_setting('flowdino_settings', 'flowdino_password', array(
            'sanitize_callback' => 'sanitize_text_field'
        ));
        register_setting('flowdino_settings', 'flowdino_api_url', array(
            'sanitize_callback' => 'esc_url_raw'
        ));
        register_setting('flowdino_settings', 'flowdino_auto_sync', array(
            'sanitize_callback' => array($this, 'sanitize_checkbox')
        ));
        register_setting('flowdino_settings', 'flowdino_default_color', array(
            'sanitize_callback' => 'absint'
        ));
        register_setting('flowdino_settings', 'flowdino_default_brand', array(
            'sanitize_callback' => 'absint'
        ));
    }
    
    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_scripts($hook) {
        if (strpos($hook, 'flowdino-sync') === false) {
            return;
        }

        wp_enqueue_script(
            'flowdino-admin',
            FLOWDINO_PLUGIN_URL . 'assets/admin.js',
            array('jquery'),
            FLOWDINO_VERSION,
            true
        );

        wp_enqueue_style(
            'flowdino-admin',
            FLOWDINO_PLUGIN_URL . 'assets/admin.css',
            array(),
            FLOWDINO_VERSION
        );

        // Determine the active tab for conditional asset loading.
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter used only for asset routing
        $active_tab = isset($_GET['tab']) ? sanitize_text_field(wp_unslash($_GET['tab'])) : 'products';

        if ($active_tab === 'variation') {
            wp_enqueue_media();
        }

        // Consolidated Ajax nonces (single wp_localize_script call to avoid duplicate variable declarations).
        wp_localize_script('flowdino-admin', 'flowdino_ajax', array(
            'ajax_url'            => admin_url('admin-ajax.php'),
            'sync_nonce'          => wp_create_nonce('flowdino_sync_nonce'),
            'test_nonce'          => wp_create_nonce('flowdino_test_connection'),
            'force_nonce'         => wp_create_nonce('flowdino_force_nonce'),
            'search_nonce'        => wp_create_nonce('flowdino_search_brands'),
            'create_brand_nonce'  => wp_create_nonce('flowdino_create_brand'),
            'sync_sales_nonce'    => wp_create_nonce('flowdino_sync_sales_nonce'),
            'fetch_updates_nonce' => wp_create_nonce('flowdino_fetch_updates_nonce'),
            'compliance_nonce'    => wp_create_nonce('flowdino_compliance_nonce'),
            'sync_single_nonce'   => wp_create_nonce('flowdino_sync_single_nonce'),
        ));

        // Internationalised strings used by tab-specific JS files.
        wp_localize_script('flowdino-admin', 'flowdino_data', array(
            'i18n' => array(
                // Shared
                'cancel'                 => __('Cancel', 'flowdino'),
                'confirm'                => __('Confirm', 'flowdino'),
                'error_colon'            => __('Error:', 'flowdino'),
                'searching'              => __('Searching...', 'flowdino'),
                // Settings tab
                'disconnect'             => __('Disconnect', 'flowdino'),
                'disconnect_confirm'     => __('Are you sure you want to disconnect from FlowDino?', 'flowdino'),
                'connecting'             => __('Connexion...', 'flowdino'),
                'connect_btn'            => __('Connexion', 'flowdino'),
                'connection_success'     => __('Connection successful!', 'flowdino'),
                'connection_failed'      => __('Connection failed:', 'flowdino'),
                'unable_test'            => __('Unable to test connection. Please try again.', 'flowdino'),
                // Products tab
                'select_one_product'     => __('Please select at least one product to sync.', 'flowdino'),
                'sync_in_progress'       => __('Synchronisation en cours', 'flowdino'),
                'products_selected'      => __('produits sélectionnés', 'flowdino'),
                'checking_compliance'    => __('Vérification de la conformité des produits...', 'flowdino'),
                'progression'            => __('Progression', 'flowdino'),
                'products_in_error'      => __('Produits en erreur', 'flowdino'),
                'synced'                 => __('Synchronisés', 'flowdino'),
                'created'                => __('Créés', 'flowdino'),
                'updated'                => __('Mis à jour', 'flowdino'),
                'in_error'               => __('En erreur', 'flowdino'),
                'non_compliant'          => __('Non conformes', 'flowdino'),
                'error_details'          => __('Détails des erreurs', 'flowdino'),
                'close'                  => __('Fermer', 'flowdino'),
                'select_date'            => __('Veuillez sélectionner une date.', 'flowdino'),
                'fetching_updates'       => __('Récupération des mises à jour en cours…', 'flowdino'),
                'updates_applied'        => __('Mises à jour appliquées avec succès !', 'flowdino'),
                'products_received'      => __('Produits reçus de FlowDino :', 'flowdino'),
                'wc_updated'             => __('Produits mis à jour dans WooCommerce :', 'flowdino'),
                'not_found'              => __('Non trouvés (ignorés) :', 'flowdino'),
                'view_detail'            => __('Voir le détail', 'flowdino'),
                'unknown_error'          => __('Erreur inconnue.', 'flowdino'),
                'network_error_fetch'    => __('Erreur réseau lors de la récupération.', 'flowdino'),
                'verifying_compliance'   => __('Vérification de la conformité...', 'flowdino'),
                'compliance_verified'    => __('Conformité vérifiée', 'flowdino'),
                'partial_sync_confirm'   => __('Certains produits ne sont pas conformes. Voulez-vous synchroniser uniquement les produits conformes ?', 'flowdino'),
                'sync_cancelled'         => __('Synchronisation annulée', 'flowdino'),
                'no_compliant'           => __('Aucun produit conforme à synchroniser', 'flowdino'),
                'error_checking'         => __('Erreur lors de la vérification', 'flowdino'),
                'network_error_check'    => __('Erreur réseau lors de la vérification', 'flowdino'),
                'starting_sync'          => __('Démarrage de la synchronisation...', 'flowdino'),
                'sync_complete'          => __('Synchronisation terminée !', 'flowdino'),
                'syncing_product'        => __('Synchronisation du produit', 'flowdino'),
                'unknown_error_en'       => __('Unknown error', 'flowdino'),
                'network_error_sync'     => __('Network error during synchronization', 'flowdino'),
                // Mapping tabs — Select2 placeholders
                'select_default_color'   => __('-- Select a default FlowDino color --', 'flowdino'),
                'select_color'           => __('-- Select a FlowDino color --', 'flowdino'),
                'select_default_size'    => __('-- Select a default FlowDino size --', 'flowdino'),
                'select_size'            => __('-- Select a FlowDino size --', 'flowdino'),
                'select_default_material'=> __('-- Select a default FlowDino material --', 'flowdino'),
                'select_material'        => __('-- Select a FlowDino material --', 'flowdino'),
                'select_vg_rating'       => __('-- Select a FlowDino rating --', 'flowdino'),
                'select_tag'             => __('-- Select a FlowDino tag --', 'flowdino'),
                // Categories tab
                'no_categories_found'    => __('No categories found', 'flowdino'),
                // Brands tab
                'no_brands_found'        => __('No brands found', 'flowdino'),
                'error_searching_brands' => __('Error searching brands', 'flowdino'),
                'default_brand_label'    => __('Default brand:', 'flowdino'),
                'currently_mapped_to'    => __('Currently mapped to:', 'flowdino'),
                'clear_default_brand'    => __('Clear default brand', 'flowdino'),
                'clear_mapping'          => __('Clear mapping', 'flowdino'),
                'no_default_brand'       => __('No default brand selected', 'flowdino'),
                'no_brand_selected'      => __('No brand selected', 'flowdino'),
                'brand_name_required'    => __('Please enter a brand name.', 'flowdino'),
                'creating_brand'         => __('Creating...', 'flowdino'),
                'create_brand'           => __('Create Brand', 'flowdino'),
                'brand_created'          => __('Brand created successfully:', 'flowdino'),
                'error_creating_brand'   => __('Error creating brand:', 'flowdino'),
            ),
        ));

        // Tab-specific static JS files.
        if ('products' === $active_tab) {
            wp_enqueue_script(
                'flowdino-products',
                FLOWDINO_PLUGIN_URL . 'assets/admin-products.js',
                array('jquery', 'flowdino-admin'),
                FLOWDINO_VERSION,
                true
            );
        }

        if ('settings' === $active_tab) {
            wp_enqueue_script(
                'flowdino-settings',
                FLOWDINO_PLUGIN_URL . 'assets/admin-settings.js',
                array('jquery', 'flowdino-admin'),
                FLOWDINO_VERSION,
                true
            );
        }

        if ('brands' === $active_tab) {
            wp_enqueue_script(
                'flowdino-brands',
                FLOWDINO_PLUGIN_URL . 'assets/admin-brands.js',
                array('jquery', 'flowdino-admin'),
                FLOWDINO_VERSION,
                true
            );
        }

        // Enqueue SelectWoo / Select2 for attribute-mapping tabs.
        $mapping_tabs = array('colors', 'sizes', 'materials', 'categories', 'videogameratings', 'tags');
        if (in_array($active_tab, $mapping_tabs, true)) {
            if (class_exists('WooCommerce')) {
                wp_enqueue_script('selectWoo');
                wp_enqueue_style('select2');
            }
        }

        // Inline initialisation scripts for each mapping tab.
        // For tabs that use SelectWoo we register a dependency-aware dummy handle so the
        // init code is guaranteed to run AFTER both flowdino-admin AND selectWoo are loaded.
        if ('colors' === $active_tab) {
            wp_add_inline_script('flowdino-admin', $this->get_select2_init_js('color'), 'after');
        } elseif ('sizes' === $active_tab) {
            wp_add_inline_script('flowdino-admin', $this->get_select2_init_js('size'), 'after');
        } elseif ('materials' === $active_tab) {
            wp_add_inline_script('flowdino-admin', $this->get_select2_init_js('material'), 'after');
        } elseif ('categories' === $active_tab) {
            // Init script is embedded directly in the tab template.
        } elseif ('videogameratings' === $active_tab) {
            wp_add_inline_script('flowdino-admin', $this->get_videogameratings_init_js(), 'after');
        } elseif ('tags' === $active_tab) {
            wp_add_inline_script('flowdino-admin', $this->get_tags_init_js(), 'after');
        }
    }

    /**
     * Return the Select2/SelectWoo initialisation JS for the colors, sizes or materials tab.
     *
     * @param string $type  One of 'colors', 'sizes', 'materials'.
     * @return string
     */
    private function get_select2_init_js($type) {
        return "jQuery(document).ready(function(\$) {
    var selectFn = typeof \$.fn.selectWoo !== 'undefined' ? 'selectWoo' : (typeof \$.fn.select2 !== 'undefined' ? 'select2' : null);
    if (!selectFn) { return; }
    \$('select.flowdino-select2')[selectFn]({
        placeholder: flowdino_data.i18n.select_default_{$type},
        allowClear: true, width: '400px', dropdownAutoWidth: true,
        escapeMarkup: function(m) { return m; }
    });
    \$('select.flowdino-select2-mapping')[selectFn]({
        placeholder: flowdino_data.i18n.select_{$type},
        allowClear: true, width: '100%', dropdownAutoWidth: true,
        escapeMarkup: function(m) { return m; }
    });
    \$('select.flowdino-select2').on('select2:select selectWoo:select', function(e) {
        var data = e.params.data;
        var opt  = \$(this).find('option[value=\"' + data.id + '\"]');
        \$('input[name=\"default_{$type}_name\"]').val(opt.data('name') || opt.text());
    });
    \$('select.flowdino-select2').on('select2:clear selectWoo:clear', function() {
        \$('input[name=\"default_{$type}_name\"]').val('');
    });
});";
    }

    /**
     * Return the Select2/SelectWoo initialisation JS for the categories tab.
     *
     * @return string
     */
    private function get_categories_init_js() {
        // Note: this code runs inline after selectWoo.js — DOM is ready, selectWoo is defined.
        return "jQuery(function(\$) {
    var selectFn = typeof \$.fn.selectWoo !== 'undefined' ? 'selectWoo' : (typeof \$.fn.select2 !== 'undefined' ? 'select2' : null);
    if (!selectFn) { return; }
    \$('.flowdino-category-select').each(function() {
        if (\$(this).data(selectFn)) { return; }
        \$(this)[selectFn]({
            width: '100%',
            placeholder: \$(this).data('placeholder') || '-- Select --',
            allowClear: true,
            dropdownParent: \$(this).parent(),
            language: {
                noResults: function() { return (typeof flowdino_data !== 'undefined') ? flowdino_data.i18n.no_categories_found : 'No results'; },
                searching: function() { return (typeof flowdino_data !== 'undefined') ? flowdino_data.i18n.searching : 'Searching...'; }
            },
            matcher: function(params, data) {
                if (\$.trim(params.term) === '') { return data; }
                if (data.text.toLowerCase().indexOf(params.term.toLowerCase()) > -1) { return data; }
                return null;
            }
        });
    });
});";
    }

    /**
     * Return the Select2 initialisation JS for the video-game ratings tab.
     *
     * @return string
     */
    private function get_videogameratings_init_js() {
        return "jQuery(document).ready(function(\$) {
    var selectFn = typeof \$.fn.selectWoo !== 'undefined' ? 'selectWoo' : (typeof \$.fn.select2 !== 'undefined' ? 'select2' : null);
    if (!selectFn) { return; }
    \$('select.flowdino-vgrating-select2')[selectFn]({
        placeholder: flowdino_data.i18n.select_vg_rating,
        allowClear: true, width: '100%', dropdownAutoWidth: true,
        escapeMarkup: function(markup) { return markup; }
    });
});";
    }

    /**
     * Return the Select2 initialisation JS for the tags tab.
     *
     * @return string
     */
    private function get_tags_init_js() {
        return "jQuery(document).ready(function(\$) {
    var selectFn = typeof \$.fn.selectWoo !== 'undefined' ? 'selectWoo' : (typeof \$.fn.select2 !== 'undefined' ? 'select2' : null);
    if (!selectFn) { return; }
    \$('select.flowdino-tag-select2')[selectFn]({
        placeholder: flowdino_data.i18n.select_tag,
        allowClear: true, width: '100%', dropdownAutoWidth: true,
        escapeMarkup: function(markup) { return markup; }
    });
});";
    }
    
    /**
     * Get FlowDino logo HTML
     */
    private function get_flowdino_logo() {
        $logo_url = FLOWDINO_PLUGIN_URL . 'flowdino/logo.png';
        return '<img src="' . esc_url($logo_url) . '" alt="FlowDino" style="height: 32px; width: 32px;" />';
    }
    
    /**
     * Admin page callback
     */
    public function admin_page() {
        // Déterminer l'onglet par défaut selon l'état de connexion
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for tab navigation
        if (!isset($_GET['tab'])) {
            // Vérifier si on est connecté à l'API
            require_once FLOWDINO_PLUGIN_PATH . 'includes/class-flowdino-wc-api.php';
            $api = new FlowDino_WC_API();
            
            // Si connecté -> onglet Produits, sinon -> onglet Paramètres
            $default_tab = $api->is_connected() ? 'products' : 'settings';
        } else {
            $default_tab = 'settings'; // fallback
        }
        
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for tab navigation
        $active_tab = isset($_GET['tab']) ? sanitize_text_field(wp_unslash($_GET['tab'])) : $default_tab;
        
        ?>
        <div class="wrap">
            <h1 class="flowdino-title-with-logo">
                <?php echo wp_kses_post($this->get_flowdino_logo()); ?>
                <span style="color: #2563eb;"><?php /* translators: FlowDino admin title */ esc_html_e('FlowDino', 'flowdino'); ?></span>
            </h1>
            
            <nav class="nav-tab-wrapper">
                <a href="?page=flowdino-sync&tab=settings" class="nav-tab <?php echo esc_attr($active_tab == 'settings' ? 'nav-tab-active' : ''); ?>">
                    <?php /* translators: Tab title for settings */ esc_html_e('Settings', 'flowdino'); ?>
                </a>
                <a href="?page=flowdino-sync&tab=products" class="nav-tab <?php echo esc_attr($active_tab == 'products' ? 'nav-tab-active' : ''); ?>">
                    <?php /* translators: Tab title for products */ esc_html_e('Products', 'flowdino'); ?>
                </a>
                <a href="?page=flowdino-sync&tab=categories" class="nav-tab <?php echo esc_attr($active_tab == 'categories' ? 'nav-tab-active' : ''); ?>">
                    <?php /* translators: Tab title for categories */ esc_html_e('Categories', 'flowdino'); ?>
                </a>
                <a href="?page=flowdino-sync&tab=brands" class="nav-tab <?php echo esc_attr($active_tab == 'brands' ? 'nav-tab-active' : ''); ?>">
                    <?php /* translators: Tab title for brands */ esc_html_e('Brands', 'flowdino'); ?>
                </a>
                <a href="?page=flowdino-sync&tab=colors" class="nav-tab <?php echo esc_attr($active_tab == 'colors' ? 'nav-tab-active' : ''); ?>">
                    <?php /* translators: Tab title for colors */ esc_html_e('Colors', 'flowdino'); ?>
                </a>
                <a href="?page=flowdino-sync&tab=materials" class="nav-tab <?php echo esc_attr($active_tab == 'materials' ? 'nav-tab-active' : ''); ?>">
                    <?php /* translators: Tab title for materials */ esc_html_e('Materials', 'flowdino'); ?>
                </a>
                <a href="?page=flowdino-sync&tab=sizes" class="nav-tab <?php echo esc_attr($active_tab == 'sizes' ? 'nav-tab-active' : ''); ?>">
                    <?php /* translators: Tab title for sizes */ esc_html_e('Sizes', 'flowdino'); ?>
                </a>
                <a href="?page=flowdino-sync&tab=videogameratings" class="nav-tab <?php echo esc_attr($active_tab == 'videogameratings' ? 'nav-tab-active' : ''); ?>">
                    <?php /* translators: Tab title for video game ratings */ esc_html_e('Video Game Ratings', 'flowdino'); ?>
                </a>
                <a href="?page=flowdino-sync&tab=tags" class="nav-tab <?php echo esc_attr($active_tab == 'tags' ? 'nav-tab-active' : ''); ?>">
                    <?php /* translators: Tab title for tags */ esc_html_e('Tags', 'flowdino'); ?>
                </a>
                <a href="?page=flowdino-sync&tab=variation" class="nav-tab <?php echo esc_attr($active_tab == 'variation' ? 'nav-tab-active' : ''); ?>">
                    <?php /* translators: Tab title for variation overlay */ esc_html_e('Variation', 'flowdino'); ?>
                </a>
                <a href="?page=flowdino-sync&tab=help" class="nav-tab <?php echo esc_attr($active_tab == 'help' ? 'nav-tab-active' : ''); ?>">
                    <?php /* translators: Tab title for help */ esc_html_e('Help', 'flowdino'); ?>
                </a>
                <a href="?page=flowdino-sync&tab=sales" class="nav-tab <?php echo esc_attr($active_tab == 'sales' ? 'nav-tab-active' : ''); ?>" style="color:#00acc1;font-weight:600;">
                    <span class="dashicons dashicons-cart" style="vertical-align:middle;margin-right:4px;"></span>
                    <?php /* translators: Tab title for sales */ esc_html_e('Ventes', 'flowdino'); ?>
                </a>
            </nav>
            
            <div class="tab-content">
                <?php
                switch ($active_tab) {
                    case 'settings':
                        $settings_tab = new FlowDino_WC_Settings_Tab();
                        $settings_tab->render();
                        break;
                    case 'products':
                        $products_tab = new FlowDino_WC_Products_Tab();
                        $products_tab->render();
                        break;
                    case 'categories':
                        $categories_tab = new FlowDino_WC_Categories_Tab();
                        $categories_tab->render();
                        break;
                    case 'brands':
                        $brands_tab = new FlowDino_WC_Brands_Tab();
                        $brands_tab->render();
                        break;
                    case 'colors':
                        $colors_tab = new FlowDino_WC_Colors_Tab();
                        $colors_tab->render();
                        break;
                    case 'materials':
                        $materials_tab = new FlowDino_WC_Materials_Tab();
                        $materials_tab->render();
                        break;
                    case 'sizes':
                        $sizes_tab = new FlowDino_WC_Sizes_Tab();
                        $sizes_tab->render();
                        break;
                    case 'videogameratings':
                        $vgratings_tab = new FlowDino_WC_VideoGameRatings_Tab();
                        $vgratings_tab->render();
                        break;
                    case 'tags':
                        $tags_tab = new FlowDino_WC_Tags_Tab();
                        $tags_tab->render();
                        break;
                    case 'variation':
                        $variation_tab = new FlowDino_WC_Variation_Tab();
                        $variation_tab->render();
                        break;
                    case 'help':
                        $help_tab = new FlowDino_WC_Help_Tab();
                        $help_tab->render();
                        break;
                    case 'sales':
                        $sales_tab = new FlowDino_WC_Sales_Tab();
                        $sales_tab->render();
                        break;
                    default:
                        $settings_tab = new FlowDino_WC_Settings_Tab();
                        $settings_tab->render();
                        break;
                }
                ?>
            </div>
        </div>
        <?php
    }
    
    /**
     * AJAX handler for brand search
     */
    public function ajax_search_brands() {
        // Vérifier le nonce pour la sécurité
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'flowdino_search_brands')) {
            wp_die('Unauthorized');
        }
        
        // Vérifier les permissions
        if (!current_user_can('manage_woocommerce')) {
            wp_die('Insufficient permissions');
        }
        
        $search_term = isset($_POST['search_term']) ? sanitize_text_field(wp_unslash($_POST['search_term'])) : '';
        
        if (empty($search_term)) {
            wp_send_json_error(array(
                'message' => __('Search term is required', 'flowdino')
            ));
            return;
        }
        
        // Minimum 2 caractères pour éviter trop de résultats
        if (strlen($search_term) < 2) {
            wp_send_json_error(array(
                'message' => __('Please enter at least 2 characters', 'flowdino')
            ));
            return;
        }
        
        try {
            $api = new FlowDino_WC_API();
            $result = $api->search_brands($search_term);
            
            if ($result['success']) {
                wp_send_json_success(array(
                    'brands' => $result['data'],
                    'message' => $result['message']
                ));
            } else {
                wp_send_json_error(array(
                    'message' => $result['message']
                ));
            }
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: AJAX brand search error - ' . $e->getMessage());
            wp_send_json_error(array(
                'message' => esc_html(__('An error occurred while searching brands', 'flowdino'))
            ));
        }
    }

    /**
     * AJAX handler for brand creation
     */
    public function ajax_create_brand() {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'flowdino_create_brand')) {
            wp_die('Unauthorized');
        }

        if (!current_user_can('manage_woocommerce')) {
            wp_die('Insufficient permissions');
        }

        $name = isset($_POST['brand_name']) ? sanitize_text_field(wp_unslash($_POST['brand_name'])) : '';

        if (empty($name)) {
            wp_send_json_error(array(
                'message' => __('Brand name is required', 'flowdino')
            ));
            return;
        }

        try {
            $api    = new FlowDino_WC_API();
            $result = $api->create_brand($name);

            if ($result['success']) {
                wp_send_json_success(array(
                    'brand'   => $result['data'],
                    'message' => $result['message'],
                ));
            } else {
                wp_send_json_error(array(
                    'message' => $result['message']
                ));
            }
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: AJAX create brand error - ' . $e->getMessage());
            wp_send_json_error(array(
                'message' => esc_html(__('An error occurred while creating the brand', 'flowdino'))
            ));
        }
    }

    /**
     * AJAX handler for colors search
     */
    public function ajax_search_colors() {
        // Vérifier les permissions
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(array(
                'message' => esc_html(__('Permission denied', 'flowdino'))
            ));
            return;
        }
        
        // Vérifier le nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'flowdino_colors')) {
            wp_send_json_error(array(
                'message' => esc_html(__('Security check failed', 'flowdino'))
            ));
            return;
        }
        
        $search_term = isset($_POST['search_term']) ? sanitize_text_field(wp_unslash($_POST['search_term'])) : '';
        
        if (empty($search_term)) {
            wp_send_json_error(array(
                'message' => esc_html(__('Search term is required', 'flowdino'))
            ));
            return;
        }
        
        // Minimum 2 caractères pour éviter trop de résultats
        if (strlen($search_term) < 2) {
            wp_send_json_error(array(
                'message' => esc_html(__('Please enter at least 2 characters', 'flowdino'))
            ));
            return;
        }
        
        try {
            $api = new FlowDino_WC_API();
            $result = $api->search_colors($search_term);
            
            if ($result['success']) {
                wp_send_json_success(array(
                    'colors' => $result['member'],
                    'message' => $result['message']
                ));
            } else {
                wp_send_json_error(array(
                    'message' => $result['message']
                ));
            }
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: AJAX color search error - ' . $e->getMessage());
            wp_send_json_error(array(
                'message' => esc_html(__('An error occurred while searching colors', 'flowdino'))
            ));
        }
    }

    /**
     * AJAX handler for connection test
     */
    public function ajax_test_connection() {
        // Vérifier les permissions
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(array(
                'message' => __('Permission denied', 'flowdino')
            ));
            return;
        }
        
        // Vérifier le nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'flowdino_test_connection')) {
            wp_send_json_error(array(
                'message' => __('Security check failed', 'flowdino')
            ));
            return;
        }
        
        try {
            $api = new FlowDino_WC_API();
            $result = $api->test_connection();
            
            if ($result['success']) {
                wp_send_json_success(array(
                    'message' => __('Connection successful!', 'flowdino'),
                    'data' => $result['data']
                ));
            } else {
                wp_send_json_error(array(
                    'message' => $result['message']
                ));
            }
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: AJAX connection test error - ' . $e->getMessage());
            wp_send_json_error(array(
                'message' => __('Connection test failed: ', 'flowdino') . $e->getMessage()
            ));
        }
    }

    /**
     * AJAX handler for advanced debug
     */
    public function ajax_debug_advanced() {
        // Vérifier les permissions
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(array(
                'message' => __('Permission denied', 'flowdino')
            ));
            return;
        }
        
        // Vérifier le nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'flowdino_debug_nonce')) {
            wp_send_json_error(array(
                'message' => __('Security check failed', 'flowdino')
            ));
            return;
        }
        
        try {
            ob_start();
            $this->run_advanced_debug();
            $output = ob_get_clean();
            
            wp_send_json_success(array(
                'output' => $output
            ));
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: AJAX advanced debug error - ' . $e->getMessage());
            wp_send_json_error(array(
                'message' => __('Advanced debug failed: ', 'flowdino') . $e->getMessage()
            ));
        }
    }
    
    /**
     * Exécute le diagnostic avancé
     */
    private function run_advanced_debug() {
    echo esc_html("RAPPORT TECHNIQUE FLOWDINO\n");
    echo esc_html("==========================\n\n");
        
        // 1. Environnement système
        // 1. Environnement système
        echo esc_html("ENVIRONNEMENT:\n");
        echo esc_html("PHP: " . PHP_VERSION . " | WP: " . esc_html(get_bloginfo('version')) . " | WC: " . (class_exists('WooCommerce') ? 'OK' : 'MANQUANT') . "\n");
        echo esc_html("CURL: " . (function_exists('curl_init') ? 'OK' : 'NON') . " | SSL: " . (extension_loaded('openssl') ? 'OK' : 'NON') . "\n");
        echo esc_html("Serveur: " . (isset($_SERVER['SERVER_SOFTWARE']) ? esc_html(sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE']))) : '') . "\n");
        echo esc_html("Timezone: " . esc_html(wp_timezone_string()) . " | " . esc_html(current_time('mysql')) . "\n\n");
        // 2. Configuration FlowDino
        echo "CONFIGURATION FLOWDINO:\n";
    $api_url = get_option('flowdino_api_url', 'https://www.flowdino.com');
    $email = get_option('flowdino_email', '');
    $password = get_option('flowdino_password', '');
    $token = get_option('flowdino_token', '');
    echo esc_html("API URL: " . $api_url . "\n");
    echo esc_html("Email: " . (!empty($email) ? $email : 'NON CONFIGURÉ') . "\n");
    echo esc_html("Password: " . (!empty($password) ? 'CONFIGURÉ (' . strlen($password) . ' chars)' : 'NON CONFIGURÉ') . "\n");
    echo esc_html("Token: " . (!empty($token) ? 'PRÉSENT (' . substr($token, 0, 20) . '...)' : 'ABSENT') . "\n\n");
        
        // 3. Test de connectivité
        echo "CONNECTIVITÉ:\n";
        $host = wp_parse_url($api_url, PHP_URL_HOST);
    $ip = gethostbyname($host);
    echo esc_html("DNS " . $host . ": " . ($ip !== $host ? 'OK → ' . $ip : 'ÉCHEC') . "\n");
        
        $response = wp_remote_get($api_url, array('timeout' => 10, 'sslverify' => false));
        if (!is_wp_error($response)) {
            echo esc_html("HTTP: OK (Code: " . wp_remote_retrieve_response_code($response) . ")\n");
        } else {
            echo esc_html("HTTP: ÉCHEC - " . $response->get_error_message() . "\n");
        }
        echo "\n";
        
        // 4. Test API
        if (empty($email) || empty($password)) {
            echo "TEST API: IMPOSSIBLE - Identifiants manquants\n\n";
            echo "SOLUTION: Configurez votre email et mot de passe FlowDino\n";
            return;
        }
        
        echo "TEST API:\n";
        $login_response = wp_remote_post($api_url . '/api/login_check', array(
            'headers' => array('Content-Type' => 'application/json'),
            'body' => json_encode(array('email' => $email, 'password' => $password)),
            'timeout' => 30,
            'sslverify' => false
        ));
        
        if (is_wp_error($login_response)) {
            echo esc_html("LOGIN: ÉCHEC RÉSEAU - " . $login_response->get_error_message() . "\n");
        } else {
            $code = wp_remote_retrieve_response_code($login_response);
            $body = wp_remote_retrieve_body($login_response);
            $data = json_decode($body, true);
            echo esc_html("LOGIN: Code " . $code);
            if ($code === 200 && isset($data['token'])) {
                echo esc_html(" - SUCCÈS\n");
                echo esc_html("Token reçu: " . substr($data['token'], 0, 30) . "...\n");
                // Test categories
                $cat_response = wp_remote_get($api_url . '/api/categories/tree', array(
                    'headers' => array(
                        'Authorization' => 'Bearer ' . $data['token'],
                        'Content-Type' => 'application/json'
                    ),
                    'timeout' => 30,
                    'sslverify' => false
                ));
                if (!is_wp_error($cat_response)) {
                    $cat_code = wp_remote_retrieve_response_code($cat_response);
                    echo esc_html("CATEGORIES: Code " . $cat_code);
                    if ($cat_code === 200) {
                        $cat_data = json_decode(wp_remote_retrieve_body($cat_response), true);
                        echo esc_html(" - OK (" . (is_array($cat_data) ? count($cat_data) : 0) . " catégories)\n");
                    } else {
                        echo esc_html(" - ÉCHEC\n");
                    }
                }
            } else {
                echo esc_html(" - ÉCHEC\n");
                if (isset($data['message'])) {
                    echo esc_html("Message: " . $data['message'] . "\n");
                }
                // Suggestions
                echo esc_html("\nDIAGNOSTIC:\n");
                if ($code === 401) {
                    echo esc_html("- Vérifiez vos identifiants FlowDino\n");
                    echo esc_html("- Email: " . $email . "\n");
                } elseif ($code === 403) {
                    echo esc_html("- Compte suspendu ou accès API désactivé\n");
                } elseif ($code === 404) {
                    echo esc_html("- URL API incorrecte: " . $api_url . "\n");
                } else {
                    echo esc_html("- Erreur serveur FlowDino\n");
                }
            }
        }
        
        echo "\n==========================\n";
    echo esc_html("\n==========================\n");
    echo esc_html("Fin du rapport technique\n");
    }

    /**
     * AJAX handler for force reconnect
     */
    public function ajax_force_reconnect() {
        // Vérifier les permissions
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(array(
                'message' => __('Permission denied', 'flowdino')
            ));
            return;
        }
        
        // Vérifier le nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'flowdino_force_nonce')) {
            wp_send_json_error(array(
                'message' => __('Security check failed', 'flowdino')
            ));
            return;
        }
        
        try {
            // Nettoyer l'ancien token
            delete_option('flowdino_token');
            delete_option('flowdino_token_last_refresh');
            
            // Forcer une nouvelle connexion
            $api = new FlowDino_WC_API();
            $email = get_option('flowdino_email');
            $password = get_option('flowdino_password');
            
            if (empty($email) || empty($password)) {
                wp_send_json_error(array(
                    'message' => 'Identifiants manquants. Veuillez configurer votre email et mot de passe.'
                ));
                return;
            }
            
            $result = $api->login($email, $password);
            
            if ($result['success']) {
                wp_send_json_success(array(
                    'message' => 'Token sauvegardé avec succès!'
                ));
            } else {
                wp_send_json_error(array(
                    'message' => $result['message']
                ));
            }
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: AJAX force reconnect error - ' . $e->getMessage());
            wp_send_json_error(array(
                'message' => 'Erreur lors de la reconnexion: ' . $e->getMessage()
            ));
        }
    }
    
    /**
     * Handle AJAX product synchronization
     */
    public function ajax_sync_single_product() {
        // Déléguer à l'instance de la classe Products Tab
        $products_tab = new FlowDino_WC_Products_Tab();
        $products_tab->handle_ajax_sync_single_product();
    }
    
    /**
     * Handle AJAX non-compliant products check
     */
    public function ajax_get_non_compliant_products() {
        // Vérifier le nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'flowdino_non_compliant_nonce')) {
            wp_send_json_error(__('Security check failed', 'flowdino'));
            return;
        }
        
        // Vérifier les permissions
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(__('Insufficient permissions', 'flowdino'));
            return;
        }
        
        // Déléguer à l'instance de la classe Products Tab
        $products_tab = new FlowDino_WC_Products_Tab();
        $products_tab->handle_ajax_get_non_compliant_products();
    }
    
    /**
     * Handle AJAX selected products compliance check
     */
    public function ajax_check_selected_products_compliance() {
        // Déléguer à l'instance de la classe Products Tab
        $products_tab = new FlowDino_WC_Products_Tab();
        $products_tab->handle_ajax_check_selected_products_compliance();
    }
    
    /**
     * Handle AJAX refresh product statistics
     */
    public function ajax_refresh_product_stats() {
        // Vérifier le nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'flowdino_refresh_stats_nonce')) {
            wp_die('Security check failed');
        }
        
        // Déléguer à l'instance de la classe Products Tab pour obtenir les statistiques
        $products_tab = new FlowDino_WC_Products_Tab();
        $stats = $products_tab->get_products_statistics();
        
        wp_send_json_success($stats);
    }

    /**
     * Handle AJAX: fetch product updates from FlowDino and apply them to WooCommerce
     */
    public function ajax_fetch_product_updates() {
        $products_tab = new FlowDino_WC_Products_Tab();
        $products_tab->handle_ajax_fetch_product_updates();
    }

    /**
     * AJAX handler — synchronise sales from FlowDino platforms.
     */
    public function ajax_sync_sales() {
        // Security check
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'flowdino_sync_sales_nonce')) {
            wp_send_json_error(array('message' => __('Security check failed', 'flowdino')));
            return;
        }

        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(array('message' => __('Insufficient permissions', 'flowdino')));
            return;
        }

        try {
            $sales_tab = new FlowDino_WC_Sales_Tab();
            $result    = $sales_tab->process_sync_sales();

            if ($result['success']) {
                wp_send_json_success(array(
                    'total'   => $result['total'],
                    'message' => $result['message'],
                    'sites'   => $result['sites'],
                ));
            } else {
                wp_send_json_error(array('message' => $result['message']));
            }
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            error_log('FlowDino: ajax_sync_sales exception — ' . $e->getMessage());
            wp_send_json_error(array('message' => $e->getMessage()));
        }
    }

    /**
     * Sanitize checkbox value
     * @param mixed $value
     * @return int
     */
    public function sanitize_checkbox($value) {
        return !empty($value) ? 1 : 0;
    }
}
