<?php

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

/**
 * Brands Tab for FlowDino
 */
class FlowDino_WC_Brands_Tab {
    
    /**
     * Render the brands tab
     */
    public function render() {
        $this->handle_form_submission();
        $this->render_content();
    }
    
    /**
     * Handle form submission
     */
    private function handle_form_submission() {
        // Check if required classes exist
        if (!class_exists('FlowDino_WC_API') || !class_exists('FlowDino_WC_Database')) {
            echo '<div class="notice notice-error"><p>' . esc_html(__('Required FlowDino classes not found. Please check plugin installation.', 'flowdino')) . '</p></div>';
            return;
        }
        
        $api = new FlowDino_WC_API();
        $database = new FlowDino_WC_Database();
        
        // Handle form submission
        if (isset($_POST['save_brand_mapping']) && isset($_POST['flowdino_brands_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['flowdino_brands_nonce'])), 'flowdino_brands')) {
            try {
                // Validate that database connection is available
                global $wpdb;
                if (!$wpdb) {
                    throw new Exception('Database connection not available');
                }
                
                // Save default brand
                if (isset($_POST['default_brand'])) {
                    update_option('flowdino_default_brand', sanitize_text_field(wp_unslash($_POST['default_brand'])));
                }
                
                // Save default brand name
                if (isset($_POST['default_brand_name'])) {
                    update_option('flowdino_default_brand_name', sanitize_text_field(wp_unslash($_POST['default_brand_name'])));
                }
                
                $brand_mappings = isset($_POST['brand_mapping']) ? map_deep(wp_unslash($_POST['brand_mapping']), 'sanitize_text_field') : array();
                $success_count = 0;
                $error_count = 0;
                
                // Validate brand_mappings is an array
                if (!is_array($brand_mappings)) {
                    throw new Exception('Invalid brand mapping data');
                }
                
                foreach ($brand_mappings as $wc_brand_id => $flowdino_brand_id) {
                    // Sanitize the values
                    $wc_brand_id = sanitize_text_field($wc_brand_id);
                    $flowdino_brand_id = sanitize_text_field($flowdino_brand_id);
                    
                    try {
                        // Validate inputs
                        if (!is_numeric($wc_brand_id)) {
                            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                            error_log('FlowDino: Invalid WC brand ID: ' . $wc_brand_id);
                            $error_count++;
                            continue;
                        }
                        
                        if (!empty($flowdino_brand_id) && is_numeric($flowdino_brand_id)) {
                            $result = $database->set_brand_mapping(intval($wc_brand_id), intval($flowdino_brand_id));
                            if ($result !== false) {
                                $success_count++;
                            } else {
                                $error_count++;
                                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                                error_log('FlowDino: Failed to set brand mapping for WC brand ' . $wc_brand_id . ' -> FlowDino brand ' . $flowdino_brand_id);
                                if ($wpdb->last_error) {
                                    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                                    error_log('FlowDino DB Error: ' . $wpdb->last_error);
                                }
                            }
                        } else {
                            $result = $database->delete_brand_mapping(intval($wc_brand_id));
                            if ($result !== false) {
                                $success_count++;
                            } else {
                                $error_count++;
                                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                                error_log('FlowDino: Failed to delete brand mapping for WC brand ' . $wc_brand_id);
                                if ($wpdb->last_error) {
                                    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                                    error_log('FlowDino DB Error: ' . $wpdb->last_error);
                                }
                            }
                        }
                    } catch (Exception $e) {
                        $error_count++;
                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                        error_log('FlowDino Brand Mapping Error for WC brand ' . $wc_brand_id . ': ' . $e->getMessage());
                    }
                }
                
                if ($error_count > 0) {
                    // translators: %d is the number of errors
                    echo '<div class="notice notice-warning"><p>' . sprintf(esc_html(__('Brand mappings saved with %d errors. Check error logs for details.', 'flowdino')), esc_html($error_count)) . '</p></div>';
                } else {
                    echo '<div class="notice notice-success"><p>' . esc_html(__('Brand mappings saved successfully!', 'flowdino')) . '</p></div>';
                }
            } catch (Exception $e) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                error_log('FlowDino Brand Mapping Critical Error: ' . $e->getMessage());
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                error_log('FlowDino Stack trace: ' . $e->getTraceAsString());
                // translators: %s is the error message
                echo '<div class="notice notice-error"><p>' . sprintf(esc_html(__('An error occurred while saving brand mappings: %s', 'flowdino')), esc_html($e->getMessage())) . '</p></div>';
            } catch (Error $e) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                error_log('FlowDino Brand Mapping Fatal Error: ' . $e->getMessage());
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                error_log('FlowDino Stack trace: ' . $e->getTraceAsString());
                // translators: %s is the error message
                echo '<div class="notice notice-error"><p>' . sprintf(esc_html(__('A fatal error occurred: %s', 'flowdino')), esc_html($e->getMessage())) . '</p></div>';
            }
        }
    }
    
    /**
     * Render the main content
     */
    private function render_content() {
        if (!class_exists('FlowDino_WC_API') || !class_exists('FlowDino_WC_Database')) {
            return;
        }
        
        $api = new FlowDino_WC_API();
        $database = new FlowDino_WC_Database();
        
        // Get WooCommerce brands (product attributes or custom taxonomy)
        try {
            $wc_brands = $this->get_wc_brands();
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: Error getting WC brands: ' . $e->getMessage());
            $wc_brands = array();
        }
        
        // Get FlowDino brands
        $flowdino_brands = array();
        $brands_error_message = '';
        try {
            if (!empty($api->get_token())) {
                $brands_response = $api->get_brands();
                if (is_array($brands_response) && isset($brands_response['success'])) {
                    if ($brands_response['success']) {
                        $flowdino_brands = $brands_response;
                    } else {
                        $brands_error_message = isset($brands_response['message']) ? $brands_response['message'] : esc_html(__('Unknown error occurred', 'flowdino'));
                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                        error_log('FlowDino: Brands API error - ' . $brands_error_message);
                    }
                } else {
                    // Compatibility with old API response format
                    if (is_array($brands_response) && !empty($brands_response)) {
                        $flowdino_brands = array(
                            'success' => true,
                            'data' => $brands_response
                        );
                    } else {
                        $brands_error_message = esc_html(__('Invalid response format from FlowDino brands API', 'flowdino'));
                    }
                }
            } else {
                $brands_error_message = esc_html(__('Please configure your FlowDino credentials in the Settings tab first.', 'flowdino'));
            }
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: Exception getting FlowDino brands: ' . $e->getMessage());
            $brands_error_message = $e->getMessage();
        }
        
        // Get current default brand
        $default_brand = get_option('flowdino_default_brand', '');
        $default_brand_name = get_option('flowdino_default_brand_name', '');
        
        // Auto-set default brand if none is configured and FlowDino brands are available
        $auto_brand_name = '';
        if (empty($default_brand) && is_array($flowdino_brands) && isset($flowdino_brands['data']) && !empty($flowdino_brands['data'])) {
            try {
                $auto_default_result = $api->auto_set_default_brand();
                if ($auto_default_result['success']) {
                    $default_brand = $auto_default_result['data']['brand_id'];
                    $default_brand_name = isset($auto_default_result['data']['brand_name']) ? $auto_default_result['data']['brand_name'] : '';
                    $auto_brand_name = $default_brand_name;
                    echo '<div class="notice notice-success"><p>' . esc_html($auto_default_result['message']) . '</p></div>';
                } else {
                    echo '<div class="notice notice-warning"><p>' . esc_html($auto_default_result['message']) . '</p></div>';
                }
            } catch (Exception $e) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                error_log('FlowDino: Error auto-setting default brand: ' . $e->getMessage());
            }
        }
        
        // Get current brand mappings and their names
        $brand_mappings = array();
        $mapped_brand_ids = array();
        
        // Collect all mapped brand IDs
        if (!empty($wc_brands)) {
            foreach ($wc_brands as $wc_brand) {
                $brand_id = isset($wc_brand['id']) ? $wc_brand['id'] : 0;
                if ($brand_id) {
                    $mapping = $database->get_brand_mapping($brand_id);
                    if ($mapping) {
                        $brand_mappings[$brand_id] = $mapping;
                        $mapped_brand_ids[] = $mapping;
                    }
                }
            }
        }
        
        // Add default brand ID if exists
        if (!empty($default_brand)) {
            $mapped_brand_ids[] = $default_brand;
        }
        
        // Get brand names for all mapped IDs
        $flowdino_brand_names = array();
        if (!empty($mapped_brand_ids)) {
            try {
                $flowdino_brand_names = $api->get_brand_names_by_ids(array_unique($mapped_brand_ids));
            } catch (Exception $e) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                error_log('FlowDino: Error getting brand names: ' . $e->getMessage());
            }
        }

        ?>
        <div class="flowdino-tab-content">
            <h2><?php esc_html_e('Brands Mapping', 'flowdino'); ?></h2>
            <p><?php esc_html_e('Map your WooCommerce brands to FlowDino brands to enable product synchronization.', 'flowdino'); ?></p>
            
            <?php if (!empty($brands_error_message)): ?>
                <div class="notice notice-error">
                    <p><?php echo esc_html($brands_error_message); ?></p>
                    <?php if (strpos($brands_error_message, 'credentials') !== false || strpos($brands_error_message, 'token') !== false): ?>
                        <p><a href="?page=flowdino-sync&tab=settings" class="button"><?php esc_html_e('Go to Settings', 'flowdino'); ?></a></p>
                    <?php endif; ?>
                </div>
            <?php elseif (empty($flowdino_brands) || !isset($flowdino_brands['data']) || empty($flowdino_brands['data'])): ?>
                <div class="notice notice-error">
                    <p><?php esc_html_e('Unable to load FlowDino brands. Please check your connection.', 'flowdino'); ?></p>
                    <p><?php esc_html_e('Please verify:', 'flowdino'); ?></p>
                    <ul>
                        <li><?php esc_html_e('Your FlowDino credentials are correctly configured', 'flowdino'); ?></li>
                        <li><?php esc_html_e('Your internet connection is working', 'flowdino'); ?></li>
                        <li><?php esc_html_e('FlowDino API is accessible', 'flowdino'); ?></li>
                    </ul>
                    <p><a href="?page=flowdino-sync&tab=settings" class="button"><?php esc_html_e('Check Settings', 'flowdino'); ?></a></p>
                </div>
            <?php else: ?>
                <!-- Success: brands loaded -->
                <div class="notice notice-success" id="flowdino-brands-count-notice">
                    <?php /* translators: %d is the number of brands loaded */ ?>
                    <p><?php printf(esc_html(__('Successfully loaded %d brands from FlowDino.', 'flowdino')), count($flowdino_brands['data'])); ?></p>
                </div>

                <form method="post" action="">
                    <?php wp_nonce_field('flowdino_brands', 'flowdino_brands_nonce'); ?>
                    
                    <!-- Default Brand Section -->
                    <div class="card" style="margin-bottom: 20px;">
                        <h3 style="margin: 15px;"><?php esc_html_e('Default Brand Selection', 'flowdino'); ?></h3>
                        <div style="padding: 15px;">
                            <table class="form-table">
                                <tr>
                                    <th scope="row"><?php esc_html_e('Default Brand', 'flowdino'); ?></th>
                                    <td>
                                        <div class="flowdino-brand-search-container" data-wc-brand="default">
                                            <!-- Champs cachés pour stocker la valeur et le nom sélectionnés -->
                                            <input type="hidden" 
                                                   name="default_brand" 
                                                   class="flowdino-brand-value"
                                                   value="<?php echo esc_attr($default_brand); ?>" />
                                            <input type="hidden" 
                                                   name="default_brand_name" 
                                                   class="flowdino-brand-name"
                                                   value="<?php echo esc_attr($default_brand_name); ?>" />
                                            
                                            <!-- Champ de recherche -->
                                            <input type="text" 
                                                   class="flowdino-brand-search" 
                                                   placeholder="<?php esc_html_e('Search for a default FlowDino brand...', 'flowdino'); ?>"
                                                   autocomplete="off"
                                                   style="width: 400px; margin-bottom: 5px;" />
                                            
                                            <!-- Résultats de recherche -->
                                            <div class="flowdino-brand-results" style="display: none; max-height: 200px; overflow-y: auto; border: 1px solid #ddd; background: white; position: absolute; z-index: 1000; width: 400px;">
                                            </div>
                                            
                                            <!-- Affichage de la sélection actuelle -->
                                            <div class="flowdino-brand-current" style="font-style: italic; color: #666; font-size: 0.9em;">
                                                <?php if ($default_brand): ?>
                                                    <?php 
                                                    // Utiliser le nom récupéré en priorité
                                                    $display_brand_name = '';
                                                    
                                                    // D'abord, utiliser le nom récupéré par get_brand_names_by_ids
                                                    if (isset($flowdino_brand_names[$default_brand])) {
                                                        $display_brand_name = $flowdino_brand_names[$default_brand];
                                                    }
                                                    // Sinon, utiliser le nom stocké
                                                    elseif (!empty($default_brand_name)) {
                                                        $display_brand_name = $default_brand_name;
                                                    }
                                                    // Sinon, utiliser le nom de l'auto-configuration
                                                    elseif (!empty($auto_brand_name)) {
                                                        $display_brand_name = $auto_brand_name;
                                                    }
                                                    ?>
                                                    <?php if ($display_brand_name): ?>
                                                        <?php esc_html_e('Default brand:', 'flowdino'); ?> <strong><?php echo esc_html($display_brand_name); ?></strong>
                                                        <button type="button" class="flowdino-brand-clear" style="margin-left: 10px; font-size: 0.8em;" title="<?php esc_html_e('Clear default brand', 'flowdino'); ?>">✕</button>
                                                    <?php else: ?>
                                                        <?php esc_html_e('A FlowDino brand is selected as default', 'flowdino'); ?> (ID: <?php echo esc_html($default_brand); ?>)
                                                        <button type="button" class="flowdino-brand-clear" style="margin-left: 10px; font-size: 0.8em;" title="<?php esc_html_e('Clear default brand', 'flowdino'); ?>">✕</button>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <?php esc_html_e('No default brand selected', 'flowdino'); ?>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <p class="description"><?php esc_html_e('This brand will be used when no specific mapping is found for a product.', 'flowdino'); ?></p>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>

                    <?php if (!empty($wc_brands)): ?>
                        <!-- Brands Mapping Section -->
                        <div class="card">
                            <h3 style="margin: 15px;"><?php esc_html_e('Brands Mapping', 'flowdino'); ?></h3>
                            <div style="padding: 15px;">
                                <div class="table-responsive">
                                    <table class="wp-list-table widefat fixed striped">
                                        <thead>
                                            <tr>
                                                <th style="width: 40%;"><?php esc_html_e('WooCommerce Brand', 'flowdino'); ?></th>
                                                <th style="width: 60%;"><?php esc_html_e('FlowDino Brand', 'flowdino'); ?></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($wc_brands as $wc_brand): ?>
                                                <?php 
                                                // La méthode get_wc_brands() retourne un tableau d'arrays standardisés
                                                $brand_id = isset($wc_brand['id']) ? $wc_brand['id'] : 0;
                                                $brand_name = isset($wc_brand['name']) ? $wc_brand['name'] : '';
                                                $brand_count = isset($wc_brand['count']) ? $wc_brand['count'] : 0;
                                                $current_mapping = isset($brand_mappings[$brand_id]) ? $brand_mappings[$brand_id] : '';
                                                ?>
                                                <tr>
                                                    <td>
                                                        <strong><?php echo esc_html($brand_name); ?></strong>
                                                        <?php if ($brand_count > 0): ?>
                                                            <span style="color: #666; font-size: 0.9em;">
                                                                (<?php echo esc_html($brand_count); ?> <?php esc_html_e('products', 'flowdino'); ?>)
                                                            </span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div class="flowdino-brand-search-container" data-wc-brand="<?php echo esc_html($brand_id); ?>">
                                                            <!-- Champs cachés pour stocker la valeur et le nom sélectionnés -->
                                                            <input type="hidden" 
                                                                   name="brand_mapping[<?php echo esc_html($brand_id); ?>]" 
                                                                   class="flowdino-brand-value"
                                                                   value="<?php echo esc_attr($current_mapping ? $current_mapping : ''); ?>" />
                                                            <input type="hidden" 
                                                                   name="brand_mapping_name[<?php echo esc_html($brand_id); ?>]" 
                                                                   class="flowdino-brand-name"
                                                                   value="" />
                                                            
                                                            <!-- Champ de recherche -->
                                                            <input type="text" 
                                                                   class="flowdino-brand-search" 
                                                                   placeholder="<?php esc_html_e('Search for a FlowDino brand...', 'flowdino'); ?>"
                                                                   autocomplete="off"
                                                                   style="width: 100%; max-width: 500px; margin-bottom: 5px;" />
                                                            
                                                            <!-- Résultats de recherche -->
                                                            <div class="flowdino-brand-results" style="display: none; max-height: 200px; overflow-y: auto; border: 1px solid #ddd; background: white; position: absolute; z-index: 1000; width: 100%; max-width: 500px;">
                                                            </div>
                                                            
                                                            <!-- Affichage de la sélection actuelle -->
                                                            <div class="flowdino-brand-current" style="font-style: italic; color: #666; font-size: 0.9em;">
                                                                <?php if ($current_mapping): ?>
                                                                    <?php 
                                                                    // Utiliser le nom récupéré par get_brand_names_by_ids
                                                                    $current_brand_name = '';
                                                                    if (isset($flowdino_brand_names[$current_mapping])) {
                                                                        $current_brand_name = $flowdino_brand_names[$current_mapping];
                                                                    }
                                                                    ?>
                                                                    <?php if ($current_brand_name): ?>
                                                                        <?php esc_html_e('Currently mapped to:', 'flowdino'); ?> <strong><?php echo esc_html($current_brand_name); ?></strong>
                                                                        <button type="button" class="flowdino-brand-clear" style="margin-left: 10px; font-size: 0.8em;" title="<?php esc_html_e('Clear mapping', 'flowdino'); ?>">✕</button>
                                                                    <?php else: ?>
                                                                        <?php esc_html_e('Mapped to a FlowDino brand', 'flowdino'); ?> (ID: <?php echo esc_html($current_mapping); ?>)
                                                                        <button type="button" class="flowdino-brand-clear" style="margin-left: 10px; font-size: 0.8em;" title="<?php esc_html_e('Clear mapping', 'flowdino'); ?>">✕</button>
                                                                    <?php endif; ?>
                                                                <?php else: ?>
                                                                    <?php esc_html_e('No brand selected', 'flowdino'); ?>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="notice notice-info">
                            <p><?php esc_html_e('No WooCommerce brands found.', 'flowdino'); ?></p>
                            <p><?php esc_html_e('Brands can come from:', 'flowdino'); ?></p>
                            <ul>
                                <li><?php esc_html_e('Product attribute "brand" or "Brand"', 'flowdino'); ?></li>
                                <li><?php esc_html_e('Custom taxonomy "product_brand"', 'flowdino'); ?></li>
                                <li><?php esc_html_e('Third-party brand plugins', 'flowdino'); ?></li>
                            </ul>
                        </div>
                    <?php endif; ?>
                    
                    <p class="submit">
                        <input type="submit" name="save_brand_mapping" class="button-primary" 
                               value="<?php esc_html_e('Save Brand Mappings', 'flowdino'); ?>" />
                    </p>
                </form>

                <!-- Create Brand Section -->
                <div class="card" style="margin-top: 20px;">
                    <h3 style="margin: 15px;"><?php esc_html_e('Create a New Brand', 'flowdino'); ?></h3>
                    <div style="padding: 15px;">
                        <div id="flowdino-create-brand-notice" style="display:none;"></div>
                        <table class="form-table">
                            <tr>
                                <th scope="row">
                                    <label for="flowdino-new-brand-name"><?php esc_html_e('Brand Name', 'flowdino'); ?></label>
                                </th>
                                <td>
                                    <input type="text"
                                           id="flowdino-new-brand-name"
                                           style="width: 300px;"
                                           placeholder="<?php esc_attr_e('e.g. Nike Adissa', 'flowdino'); ?>"
                                           autocomplete="off" />
                                    <button type="button"
                                            id="flowdino-create-brand-btn"
                                            class="button button-primary"
                                            style="margin-left: 8px;">
                                        <?php esc_html_e('Create Brand', 'flowdino'); ?>
                                    </button>
                                    <p class="description"><?php esc_html_e('Create a new brand directly in FlowDino. It will immediately be available in the search fields above.', 'flowdino'); ?></p>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>

            <?php endif; ?>
        </div>
        
        <?php
    }
    
    /**
     * Get WooCommerce brands from various sources
     * Returns standardized array format for consistent interface
     */
    private function get_wc_brands() {
        $brands = array();
        $found_taxonomy = '';
        $brand_terms = array();
        
        // Method 1: Try product_brand taxonomy (most common brand plugin taxonomy)
        if (taxonomy_exists('product_brand')) {
            $brand_terms = get_terms(array(
                'taxonomy' => 'product_brand',
                'hide_empty' => false,
                'orderby' => 'name',
                'order' => 'ASC'
            ));
            
            if (!is_wp_error($brand_terms) && !empty($brand_terms)) {
                $found_taxonomy = 'product_brand';
            }
        }
        
        // Method 2: Try pwb-brand taxonomy (Perfect WooCommerce Brands)
        if (empty($brand_terms) && taxonomy_exists('pwb-brand')) {
            $brand_terms = get_terms(array(
                'taxonomy' => 'pwb-brand',
                'hide_empty' => false,
                'orderby' => 'name',
                'order' => 'ASC'
            ));
            
            if (!is_wp_error($brand_terms) && !empty($brand_terms)) {
                $found_taxonomy = 'pwb-brand';
            }
        }
        
        // Method 3: Try yith_product_brand taxonomy (YITH WooCommerce Brands)
        if (empty($brand_terms) && taxonomy_exists('yith_product_brand')) {
            $brand_terms = get_terms(array(
                'taxonomy' => 'yith_product_brand',
                'hide_empty' => false,
                'orderby' => 'name',
                'order' => 'ASC'
            ));
            
            if (!is_wp_error($brand_terms) && !empty($brand_terms)) {
                $found_taxonomy = 'yith_product_brand';
            }
        }
        
        // Method 4: Try brand attribute (pa_brand)
        if (empty($brand_terms) && taxonomy_exists('pa_brand')) {
            $brand_terms = get_terms(array(
                'taxonomy' => 'pa_brand',
                'hide_empty' => false,
                'orderby' => 'name',
                'order' => 'ASC'
            ));
            
            if (!is_wp_error($brand_terms) && !empty($brand_terms)) {
                $found_taxonomy = 'pa_brand';
            }
        }
        
        // Method 5: Try other common brand attribute names
        if (empty($brand_terms)) {
            $brand_attributes = array('pa_brand', 'pa_marque', 'pa_marca', 'pa_manufacturer');
            foreach ($brand_attributes as $attribute) {
                if (taxonomy_exists($attribute)) {
                    $brand_terms = get_terms(array(
                        'taxonomy' => $attribute,
                        'hide_empty' => false,
                        'orderby' => 'name',
                        'order' => 'ASC'
                    ));
                    
                    if (!is_wp_error($brand_terms) && !empty($brand_terms)) {
                        $found_taxonomy = $attribute;
                        break;
                    }
                }
            }
        }
        
        // Method 6: Search for brand attributes in WooCommerce attributes
        if (empty($brand_terms)) {
            global $wpdb;
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct query to WooCommerce attribute taxonomies table for brand attribute detection
            $attribute_taxonomies = $wpdb->get_results(
                "SELECT * FROM {$wpdb->prefix}woocommerce_attribute_taxonomies WHERE attribute_name LIKE '%brand%' OR attribute_name LIKE '%marque%'"
            );
            
            if ($attribute_taxonomies) {
                foreach ($attribute_taxonomies as $tax) {
                    $taxonomy = 'pa_' . $tax->attribute_name;
                    if (taxonomy_exists($taxonomy)) {
                        $brand_terms = get_terms(array(
                            'taxonomy' => $taxonomy,
                            'hide_empty' => false,
                            'orderby' => 'name',
                            'order' => 'ASC'
                        ));
                        
                        if (!is_wp_error($brand_terms) && !empty($brand_terms)) {
                            $found_taxonomy = $taxonomy;
                            break;
                        }
                    }
                }
            }
        }
        
        // Convert WP_Term objects to standardized array format
        if (!empty($brand_terms) && !is_wp_error($brand_terms)) {
            foreach ($brand_terms as $term) {
                $brands[] = array(
                    'id' => $term->term_id,
                    'name' => $term->name,
                    'slug' => $term->slug,
                    'description' => $term->description,
                    'count' => $term->count,
                    'taxonomy' => $found_taxonomy,
                    'source' => $this->get_brand_source_name($found_taxonomy)
                );
            }
        }
        
        return $brands;
    }
    
    /**
     * Get friendly name for brand source taxonomy
     */
    private function get_brand_source_name($taxonomy) {
        switch ($taxonomy) {
            case 'product_brand':
                return 'WooCommerce Brands Plugin';
            case 'pwb-brand':
                return 'Perfect WooCommerce Brands';
            case 'yith_product_brand':
                return 'YITH WooCommerce Brands';
            case 'pa_brand':
                return 'WooCommerce Brand Attribute';
            default:
                if (strpos($taxonomy, 'pa_') === 0) {
                    return 'WooCommerce Attribute (' . str_replace('pa_', '', $taxonomy) . ')';
                }
                return 'Custom Brand Taxonomy';
        }
    }
}
