<?php

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

/**
 * Products Tab for FlowDino
 */
class FlowDino_WC_Products_Tab {
    
    /**
     * Constructor
     */
    public function __construct() {
        // Constructor can be used for any initialization if needed
    }
    
    /**
     * Render the products tab
     */
    public function render() {
        // Handle form submissions first
        $this->handle_form_submission();
        
        // Get products with pagination
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for pagination
        $current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
        $per_page = 20;
        $offset = ($current_page - 1) * $per_page;
        
        // Get filter parameters
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for filtering
        $category_filter = isset($_GET['category_filter']) ? sanitize_text_field(wp_unslash($_GET['category_filter'])) : '';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for filtering
        $status_filter = isset($_GET['status_filter']) ? sanitize_text_field(wp_unslash($_GET['status_filter'])) : '';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for filtering
        $search_filter = isset($_GET['search_filter']) ? sanitize_text_field(wp_unslash($_GET['search_filter'])) : '';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for filtering
        $price_min = isset($_GET['price_min']) ? floatval($_GET['price_min']) : '';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for filtering
        $price_max = isset($_GET['price_max']) ? floatval($_GET['price_max']) : '';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for filtering
        $sync_filter = isset($_GET['sync_filter']) ? sanitize_text_field(wp_unslash($_GET['sync_filter'])) : '';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for filtering
        $stock_min = isset($_GET['stock_min']) && $_GET['stock_min'] !== '' ? intval($_GET['stock_min']) : '';
        
        // Prepare WP_Query arguments with performance optimizations
        // - Using 'fields' => 'ids' to reduce memory usage
        // - Disabling post meta/term cache for better performance on large datasets
        // - Optimizing meta_query and tax_query structure
        $args = array(
            'post_type' => 'product',
            'post_status' => 'publish',
            'posts_per_page' => $per_page,
            'offset' => $offset,
            'fields' => 'ids', // Only get IDs first for better performance
            'no_found_rows' => false, // We need pagination
            'update_post_meta_cache' => false, // Reduce memory usage
            'update_post_term_cache' => false, // Reduce memory usage
            // Note: meta_query and tax_query are required for product filtering
            // Performance is optimized by using 'fields' => 'ids' and disabling caches
            'meta_query' => array(), // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Required for product filtering
            'tax_query' => array() // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- Required for product filtering
        );
        
        // Apply filters with performance considerations
        if (!empty($category_filter)) {
            $args['tax_query'][] = array(
                'taxonomy' => 'product_cat',
                'field' => 'term_id',
                'terms' => intval($category_filter),
                'operator' => 'IN' // Explicit operator for better performance
            );
        }
        
        // Optimize meta queries - combine related queries when possible
        $meta_queries = array();
        
        if (!empty($status_filter)) {
            if ($status_filter === 'in_stock') {
                $meta_queries[] = array(
                    'key' => '_stock_status',
                    'value' => 'instock',
                    'compare' => '='
                );
            } elseif ($status_filter === 'out_of_stock') {
                $meta_queries[] = array(
                    'key' => '_stock_status',
                    'value' => 'outofstock',
                    'compare' => '='
                );
            }
        }
        
        if (!empty($search_filter)) {
            $args['s'] = $search_filter;
        }
        
        if (!empty($price_min) || !empty($price_max)) {
            $price_query = array(
                'key' => '_price', 
                'type' => 'NUMERIC'
            );
            if (!empty($price_min) && !empty($price_max)) {
                $price_query['value'] = array($price_min, $price_max);
                $price_query['compare'] = 'BETWEEN';
            } elseif (!empty($price_min)) {
                $price_query['value'] = $price_min;
                $price_query['compare'] = '>=';
            } elseif (!empty($price_max)) {
                $price_query['value'] = $price_max;
                $price_query['compare'] = '<=';
            }
            $meta_queries[] = $price_query;
        }
        
        if (!empty($sync_filter)) {
            if ($sync_filter === 'synced') {
                $meta_queries[] = array(
                    'key'     => '_flowdino_sync_status',
                    'value'   => 'synced',
                    'compare' => '='
                );
            } elseif ($sync_filter === 'never_synced') {
                $meta_queries[] = array(
                    'relation' => 'OR',
                    array(
                        'key'     => '_flowdino_sync_status',
                        'compare' => 'NOT EXISTS'
                    ),
                    array(
                        'key'     => '_flowdino_sync_status',
                        'value'   => '',
                        'compare' => '='
                    )
                );
            }
        }

        // Only add meta_query if we have conditions
        // Note: meta_query is required for product filtering by sync status, SKU, and price
        if (!empty($meta_queries)) {
            $args['meta_query'] = $meta_queries; // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Required for product filtering
        }
        
        // Stock quantity filter: applied in PHP to cover both simple products and variants
        if ($stock_min !== '') {
            // Fetch all matching IDs first (no pagination)
            $all_args = $args;
            $all_args['posts_per_page'] = -1;
            unset($all_args['offset']);
            $all_product_ids = get_posts($all_args);

            // Filter: keep product if it or any of its variants has stock_quantity > stock_min
            $filtered_ids = array();
            foreach ($all_product_ids as $pid) {
                $p = wc_get_product($pid);
                if (!$p) continue;
                if ($p->is_type('variable')) {
                    foreach ($p->get_children() as $vid) {
                        $v = wc_get_product($vid);
                        if ($v && $v->get_stock_quantity() !== null && $v->get_stock_quantity() > $stock_min) {
                            $filtered_ids[] = $pid;
                            break;
                        }
                    }
                } else {
                    if ($p->get_stock_quantity() !== null && $p->get_stock_quantity() > $stock_min) {
                        $filtered_ids[] = $pid;
                    }
                }
            }

            $total_products = count($filtered_ids);
            $total_pages    = ceil($total_products / $per_page);
            $products       = array_slice($filtered_ids, $offset, $per_page);
        } else {
            // Get total count for pagination
            $count_args = $args;
            $count_args['posts_per_page'] = -1;
            $count_args['fields'] = 'ids';
            unset($count_args['offset']);
            $total_products = count(get_posts($count_args));
            $total_pages = ceil($total_products / $per_page);

            // Get products
            $products = get_posts($args);
        }
        
        ?>
        <div class="flowdino-tab-content">
            <h2><?php esc_html_e('Products Synchronization', 'flowdino'); ?></h2>
            
            <!-- Bandeau de synchronisation dynamique (masqué par défaut) -->
            <div id="flowdino-sync-banner" style="display: none; margin-bottom: 20px;">
                <!-- Contenu généré dynamiquement par JavaScript -->
            </div>
            
            <!-- Filters Panel -->
            <div class="flowdino-filters-panel" style="background: #f9f9f9; padding: 20px; margin-bottom: 20px; border: 1px solid #ddd; border-radius: 5px;">
                <h3 style="margin-top: 0;"><?php esc_html_e('Filter Products', 'flowdino'); ?></h3>
                
                <form method="get" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; align-items: end;">
                    <?php // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for admin page navigation ?>
                    <input type="hidden" name="page" value="<?php echo isset($_GET['page']) ? esc_attr(sanitize_text_field(wp_unslash($_GET['page']))) : ''; ?>" />
                    <?php // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for admin page navigation ?>
                    <input type="hidden" name="tab" value="<?php echo isset($_GET['tab']) ? esc_attr(sanitize_text_field(wp_unslash($_GET['tab']))) : ''; ?>" />
                    
                    <div>
                        <label for="category_filter"><?php esc_html_e('Category', 'flowdino'); ?></label>
                        <select name="category_filter" id="category_filter" style="width: 100%;">
                            <option value=""><?php esc_html_e('All Categories', 'flowdino'); ?></option>
                            <?php
                            $categories = get_terms(array('taxonomy' => 'product_cat', 'hide_empty' => false));
                            foreach ($categories as $category) {
                                $selected = ($category_filter == $category->term_id) ? 'selected' : '';
                                echo '<option value="' . esc_attr($category->term_id) . '" ' . esc_attr($selected) . '>' . esc_html($category->name) . '</option>';
                            }
                            ?>
                        </select>
                    </div>
                    
                    <div>
                        <label for="status_filter"><?php esc_html_e('Stock Status', 'flowdino'); ?></label>
                        <select name="status_filter" id="status_filter" style="width: 100%;">
                            <option value=""><?php esc_html_e('All Status', 'flowdino'); ?></option>
                            <option value="in_stock" <?php selected($status_filter, 'in_stock'); ?>><?php esc_html_e('In Stock', 'flowdino'); ?></option>
                            <option value="out_of_stock" <?php selected($status_filter, 'out_of_stock'); ?>><?php esc_html_e('Out of Stock', 'flowdino'); ?></option>
                        </select>
                    </div>
                    
                    <div>
                        <label for="search_filter"><?php esc_html_e('Search', 'flowdino'); ?></label>
                        <input type="text" name="search_filter" id="search_filter" value="<?php echo esc_attr($search_filter); ?>" placeholder="<?php esc_html_e('Product name or SKU...', 'flowdino'); ?>" style="width: 100%;" />
                    </div>
                    
                    <div>
                        <label for="sync_filter"><?php esc_html_e('Synchronisation', 'flowdino'); ?></label>
                        <select name="sync_filter" id="sync_filter" style="width: 100%;">
                            <option value="" <?php selected($sync_filter, ''); ?>><?php esc_html_e('Tous', 'flowdino'); ?></option>
                            <option value="synced" <?php selected($sync_filter, 'synced'); ?>><?php esc_html_e('Déjà Synchronisé', 'flowdino'); ?></option>
                            <option value="never_synced" <?php selected($sync_filter, 'never_synced'); ?>><?php esc_html_e('Jamais synchronisé', 'flowdino'); ?></option>
                        </select>
                    </div>

                    <div>
                        <label for="price_min"><?php esc_html_e('Price Range', 'flowdino'); ?></label>
                        <div style="display: flex; gap: 5px;">
                            <input type="number" name="price_min" id="price_min" value="<?php echo esc_attr($price_min); ?>" placeholder="<?php esc_html_e('Min', 'flowdino'); ?>" step="0.01" style="width: 50%;" />
                            <input type="number" name="price_max" id="price_max" value="<?php echo esc_attr($price_max); ?>" placeholder="<?php esc_html_e('Max', 'flowdino'); ?>" step="0.01" style="width: 50%;" />
                        </div>
                    </div>

                    <div>
                        <label for="stock_min"><?php esc_html_e('Stock min. (qté &gt;)', 'flowdino'); ?></label>
                        <input type="number" name="stock_min" id="stock_min" value="<?php echo esc_attr($stock_min); ?>" placeholder="<?php esc_html_e('ex: 0', 'flowdino'); ?>" min="0" step="1" style="width: 100%;" />
                    </div>
                    
                    <div>
                        <button type="submit" class="button"><?php esc_html_e('Filter', 'flowdino'); ?></button>
                        <?php 
                        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for admin page navigation
                        $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
                        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter for admin page navigation
                        $tab = isset($_GET['tab']) ? sanitize_text_field(wp_unslash($_GET['tab'])) : '';
                        ?>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=' . $page . '&tab=' . $tab)); ?>" class="button"><?php esc_html_e('Reset', 'flowdino'); ?></a>
                    </div>
                </form>
            </div>
            
            <?php if (!empty($products)): ?>
                <form method="post">
                    <?php wp_nonce_field('flowdino_products_action', 'flowdino_products_nonce'); ?>
                    
                    <!-- Products Table -->
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th class="check-column">
                                    <input type="checkbox" id="cb-select-all-1">
                                </th>
                                <th><?php esc_html_e('Product', 'flowdino'); ?></th>
                                <th><?php esc_html_e('SKU', 'flowdino'); ?></th>
                                <th><?php esc_html_e('Price', 'flowdino'); ?></th>
                                <th><?php esc_html_e('Stock', 'flowdino'); ?></th>
                                <th><?php esc_html_e('Category', 'flowdino'); ?></th>
                                <th><?php esc_html_e('Sync Status', 'flowdino'); ?></th>
                                <th><?php esc_html_e('Actions', 'flowdino'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($products as $product_id): ?>
                                <?php
                                $product = wc_get_product($product_id);
                                if (!$product) continue;
                                
                                $sync_status = get_post_meta($product_id, '_flowdino_sync_status', true);
                                $last_sync = get_post_meta($product_id, '_flowdino_last_sync', true);
                                $categories = wp_get_post_terms($product_id, 'product_cat');
                                ?>
                                <tr>
                                    <th class="check-column">
                                        <input type="checkbox" name="selected_products[]" value="<?php echo esc_attr($product_id); ?>">
                                    </th>
                                    <td>
                                        <strong><?php echo esc_html($product->get_name()); ?></strong>
                                        <?php if ($product->get_image_id()): ?>
                                            <br>
                                            <?php echo wp_get_attachment_image($product->get_image_id(), array(50, 50)); ?>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo esc_html($product->get_sku() ?: esc_html(__('N/A', 'flowdino'))); ?></td>
                                    <td><?php echo wp_kses_post(wc_price($product->get_price())); ?></td>
                                    <td>
                                        <?php if ($product->is_in_stock()): ?>
                                            <span style="color: #46b450;"><?php esc_html_e('In Stock', 'flowdino'); ?></span>
                                            <?php if ($product->get_stock_quantity()): ?>
                                                <br><small><?php echo esc_html($product->get_stock_quantity()); ?> <?php esc_html_e('units', 'flowdino'); ?></small>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <span style="color: #dc3232;"><?php esc_html_e('Out of Stock', 'flowdino'); ?></span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if (!empty($categories)): ?>
                                            <?php echo esc_html($categories[0]->name); ?>
                                            <?php if (count($categories) > 1): ?>
                                                <?php /* translators: %d is the number of additional categories */ ?>
                                                <br><small><?php printf(esc_html(__('+ %d more', 'flowdino')), count($categories) - 1); ?></small>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <em><?php esc_html_e('Uncategorized', 'flowdino'); ?></em>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($sync_status === 'synced'): ?>
                                            <span style="color: #46b450;">
                                                ✅ <?php esc_html_e('Synchronized', 'flowdino'); ?>
                                                <?php if ($last_sync): ?>
                                                    <br><small><?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($last_sync))); ?></small>
                                                <?php endif; ?>
                                            </span>
                                        <?php elseif ($sync_status === 'pending'): ?>
                                            <span style="color: #ffb900;">
                                                <?php esc_html_e('Waiting for synchronization', 'flowdino'); ?>
                                            </span>
                                        <?php else: ?>
                                            <span style="color: #72777c;">
                                                <?php esc_html_e('Not synchronized yet', 'flowdino'); ?>
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <a href="<?php echo esc_url(admin_url('post.php?post=' . $product_id . '&action=edit')); ?>" 
                                           class="flowdino-edit-product-btn button button-small" 
                                           title="<?php echo esc_attr(esc_html(__('Edit product', 'flowdino'))); ?>"
                                           target="_blank"
                                           style="
                                               padding: 6px 8px; 
                                               min-height: auto; 
                                               line-height: 1;
                                               background: #f0f8ff;
                                               border: 1px solid #0073aa;
                                               color: #0073aa;
                                               border-radius: 3px;
                                               text-decoration: none;
                                               display: inline-flex;
                                               align-items: center;
                                               transition: all 0.2s ease;
                                           "
                                           onmouseover="this.style.background='#0073aa'; this.style.color='white';"
                                           onmouseout="this.style.background='#f0f8ff'; this.style.color='#0073aa';">
                                            <span class="dashicons dashicons-edit" style="font-size: 16px; width: 16px; height: 16px; line-height: 1;"></span>
                                        </a>
                                    </td>
                                </tr>
                                <?php if ($product->is_type('variable')): ?>
                                    <?php foreach ($product->get_children() as $variation_id): ?>
                                        <?php
                                        $variation = wc_get_product($variation_id);
                                        if (!$variation) continue;

                                        // Build a human-readable label from variation attributes
                                        $attr_labels = array();
                                        foreach ($variation->get_attributes() as $attr_name => $attr_value) {
                                            if (empty($attr_value)) continue;
                                            $term = get_term_by('slug', $attr_value, $attr_name);
                                            $attr_labels[] = $term ? $term->name : $attr_value;
                                        }
                                        $attr_display = !empty($attr_labels) ? implode(' / ', $attr_labels) : esc_html__('Default variation', 'flowdino');
                                        $var_sync_status = get_post_meta($variation_id, '_flowdino_sync_status', true);
                                        $var_last_sync   = get_post_meta($variation_id, '_flowdino_last_sync', true);
                                        ?>
                                        <tr style="background: #f8f9fa; border-left: 3px solid #0073aa;" data-variation="true">
                                            <td class="check-column">
                                                <input type="checkbox" name="selected_products[]" value="<?php echo esc_attr($variation_id); ?>">
                                            </td>
                                            <td style="padding-left: 30px; color: #555; font-size: 12px;">
                                                ↳ <?php echo esc_html($attr_display); ?>
                                            </td>
                                            <td style="font-size: 12px;"><?php echo esc_html($variation->get_sku() ?: '—'); ?></td>
                                            <td style="font-size: 12px;"><?php echo wp_kses_post(wc_price($variation->get_price())); ?></td>
                                            <td style="font-size: 12px;">
                                                <?php if ($variation->is_in_stock()): ?>
                                                    <span style="color: #46b450;"><?php esc_html_e('In Stock', 'flowdino'); ?></span>
                                                    <?php if ($variation->get_stock_quantity() !== null): ?>
                                                        <br><small><?php echo esc_html($variation->get_stock_quantity()); ?> <?php esc_html_e('units', 'flowdino'); ?></small>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <span style="color: #dc3232;"><?php esc_html_e('Out of Stock', 'flowdino'); ?></span>
                                                <?php endif; ?>
                                            </td>
                                            <td></td>
                                            <td style="font-size: 12px;">
                                                <?php if ($var_sync_status === 'synced'): ?>
                                                    <span style="color: #46b450;">✅ <?php esc_html_e('Synchronized', 'flowdino'); ?>
                                                        <?php if ($var_last_sync): ?>
                                                            <br><small><?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($var_last_sync))); ?></small>
                                                        <?php endif; ?>
                                                    </span>
                                                <?php else: ?>
                                                    <span style="color: #72777c;"><?php esc_html_e('Not synchronized yet', 'flowdino'); ?></span>
                                                <?php endif; ?>
                                            </td>
                                            <td></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </form>
                
                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <div class="tablenav bottom">
                        <div class="tablenav-pages">
                            <span class="displaying-num">
                                <?php /* translators: %s is the number of items */ ?>
                                <?php printf(esc_html(__('%s items', 'flowdino')), esc_html(number_format_i18n($total_products))); ?>
                            </span>
                            <?php
                            $page_links = paginate_links(array(
                                'base' => add_query_arg('paged', '%#%'),
                                'format' => '',
                                'prev_text' => esc_html(__('&laquo;', 'flowdino')),
                                'next_text' => esc_html(__('&raquo;', 'flowdino')),
                                'total' => $total_pages,
                                'current' => $current_page,
                                'type' => 'array'
                            ));
                            
                            if ($page_links) {
                                echo '<span class="pagination-links">' . wp_kses_post(implode(' ', $page_links)) . '</span>';
                            }
                            ?>
                        </div>
                    </div>
                <?php endif; ?>
                
            <?php else: ?>
                <div class="notice notice-info">
                    <p><?php esc_html_e('No products found with the selected filter.', 'flowdino'); ?></p>
                </div>
            <?php endif; ?>
            
            <!-- Section : Récupérer les mises à jour depuis FlowDino -->
            <?php
            $last_pull = get_option( 'flowdino_last_pull_updates', '' );
            // Default date = last pull date if set, otherwise yesterday at midnight
            if ( ! empty( $last_pull ) ) {
                $default_pull_date = $last_pull;
            } else {
                $default_pull_date = gmdate( 'Y-m-d H:i', strtotime( '-1 day', current_time( 'timestamp' ) ) );
            }
            ?>
            <div class="flowdino-pull-updates-panel" style="background:#f0f9ff;border:1px solid #b3d9f7;border-radius:6px;padding:20px;margin-bottom:24px;">
                <h3 style="margin-top:0;display:flex;align-items:center;gap:8px;">
                    <span class="dashicons dashicons-cloud-upload" style="font-size:22px;color:#0073aa;"></span>
                    <?php esc_html_e( 'Récupérer les mises à jour depuis FlowDino', 'flowdino' ); ?>
                </h3>

                <div style="background:#e0f3fc;border-left:4px solid #0073aa;padding:10px 14px;border-radius:4px;margin-bottom:16px;font-size:13px;">
                    <span class="dashicons dashicons-info" style="vertical-align:middle;margin-right:4px;color:#0073aa;"></span>
                    <?php esc_html_e( 'Cette fonctionnalité permet de synchroniser les quantités en stock et les statuts des produits depuis FlowDino vers votre boutique WooCommerce.', 'flowdino' ); ?>
                </div>

                <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
                    <div>
                        <label for="flowdino-pull-date" style="font-weight:600;display:block;margin-bottom:4px;">
                            <?php esc_html_e( 'Récupérer les mises à jour depuis :', 'flowdino' ); ?>
                        </label>
                        <input
                            type="datetime-local"
                            id="flowdino-pull-date"
                            value="<?php echo esc_attr( str_replace( ' ', 'T', $default_pull_date ) ); ?>"
                            style="padding:6px 10px;border:1px solid #ccc;border-radius:4px;font-size:13px;"
                        />
                    </div>
                    <div style="margin-top:20px;">
                        <button
                            type="button"
                            id="flowdino-pull-updates-btn"
                            class="button button-primary"
                            style="background:#0073aa;border-color:#006799;padding:6px 16px;display:flex;align-items:center;gap:6px;"
                        >
                            <span class="dashicons dashicons-update" style="margin-top:2px;"></span>
                            <?php esc_html_e( 'RÉCUPÉRER ET APPLIQUER LES MISES À JOUR', 'flowdino' ); ?>
                        </button>
                    </div>
                </div>

                <p style="margin:8px 0 0;font-size:12px;color:#666;">
                    <?php esc_html_e( 'Sélectionnez une date et heure pour récupérer toutes les mises à jour de produits (stock et statut) qui se sont produites dans FlowDino depuis cette date.', 'flowdino' ); ?>
                </p>
                <?php if ( ! empty( $last_pull ) ) : ?>
                    <p style="margin:6px 0 0;font-size:12px;"><strong><?php esc_html_e( 'Dernière synchronisation :', 'flowdino' ); ?></strong> <?php echo esc_html( $last_pull ); ?></p>
                <?php endif; ?>

                <!-- Result banner for pull updates -->
                <div id="flowdino-pull-results" style="display:none;margin-top:16px;"></div>
            </div>

            <!-- Bouton flottant -->
            <div id="flowdino-floating-sync-btn" onclick="submitSelectedProducts()" style="
                position: fixed;
                bottom: 30px;
                right: 30px;
                background: #2563eb;
                color: white;
                padding: 15px 25px;
                border-radius: 50px;
                cursor: pointer;
                box-shadow: 0 4px 20px rgba(37, 99, 235, 0.4);
                z-index: 99999;
                font-weight: bold;
                border: none;
                font-size: 14px;
                opacity: 0.9;
                transition: all 0.3s ease;
                min-width: 250px;
                text-align: center;
            ">
                🚀 <?php esc_html_e('Sync Selected Products', 'flowdino'); ?>
                (<span id="selected-count">0</span>)
            </div>
        </div>
        



        <?php
    }
    
    /**
     * AJAX handler: fetch product updates from FlowDino and apply them to WooCommerce
     */
    public function handle_ajax_fetch_product_updates() {
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'flowdino_fetch_updates_nonce' ) ) {
            wp_send_json_error( array( 'message' => esc_html__( 'Security check failed', 'flowdino' ) ) );
            return;
        }

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

        $since_date = isset( $_POST['since_date'] ) ? sanitize_text_field( wp_unslash( $_POST['since_date'] ) ) : '';
        if ( empty( $since_date ) ) {
            wp_send_json_error( array( 'message' => esc_html__( 'Missing date parameter', 'flowdino' ) ) );
            return;
        }

        $api    = new FlowDino_WC_API();
        $result = $api->get_product_updates_since( $since_date );

        if ( ! $result['success'] ) {
            wp_send_json_error( array( 'message' => $result['message'] ) );
            return;
        }

        $items   = $result['items'];
        $updated = 0;
        $skipped = 0;
        $details = array();
        $shop_url = get_site_url();

        foreach ( $items as $item ) {
            $external_key = isset( $item['external_key'] ) ? sanitize_text_field( $item['external_key'] ) : '';
            $quantity     = isset( $item['quantity'] )     ? intval( $item['quantity'] )                   : 0;
            $active       = isset( $item['active'] )       ? (bool) $item['active']                        : true;
            $title        = isset( $item['title'] )        ? sanitize_text_field( $item['title'] )         : '';

            // external_key format: "<shop_url>-<wc_product_id>"
            $product_id = null;
            if ( ! empty( $external_key ) ) {
                $prefix = $shop_url . '-';
                if ( strpos( $external_key, $prefix ) === 0 ) {
                    $product_id = intval( substr( $external_key, strlen( $prefix ) ) );
                }
            }

            if ( ! $product_id ) {
                $skipped++;
                $details[] = array(
                    'external_key' => $external_key,
                    'title'        => $title,
                    'status'       => 'skipped',
                    /* translators: The external key does not match this WooCommerce shop */
                    'message'      => esc_html__( 'external_key does not match this shop', 'flowdino' ),
                );
                continue;
            }

            $product = wc_get_product( $product_id );
            if ( ! $product ) {
                $skipped++;
                $details[] = array(
                    'external_key' => $external_key,
                    'title'        => $title,
                    'status'       => 'skipped',
                    /* translators: %d is the WooCommerce product ID */
                    'message'      => sprintf( esc_html__( 'Product ID %d not found in WooCommerce', 'flowdino' ), $product_id ),
                );
                continue;
            }

            // Apply stock quantity
            if ( $product->managing_stock() ) {
                wc_update_product_stock( $product, $quantity );
            } else {
                // Manage stock for this product so we can set a quantity
                $product->set_manage_stock( true );
                $product->set_stock_quantity( $quantity );
            }

            // Apply active/inactive status: active=true => publish, active=false => set stock to 0 / out of stock
            if ( $active ) {
                $product->set_stock_status( $quantity > 0 ? 'instock' : 'outofstock' );
                if ( $product->get_status() !== 'publish' ) {
                    $product->set_status( 'publish' );
                }
            } else {
                $product->set_stock_quantity( 0 );
                $product->set_stock_status( 'outofstock' );
            }

            $product->save();
            $updated++;

            $details[] = array(
                'external_key' => $external_key,
                'title'        => $title,
                'status'       => 'updated',
                /* translators: %d is the new stock quantity */
                'message'      => sprintf( esc_html__( 'Stock mis à jour : %d', 'flowdino' ), $quantity ),
            );
        }

        // Save last pull date
        $now = current_time( 'Y-m-d H:i:s' );
        update_option( 'flowdino_last_pull_updates', $now );

        wp_send_json_success( array(
            'total_received' => count( $items ),
            'updated'        => $updated,
            'skipped'        => $skipped,
            'details'        => $details,
            'last_pull'      => $now,
        ) );
    }

    /**
     * Handle form submissions
     */
    private function handle_form_submission() {
        if (!isset($_POST['flowdino_products_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['flowdino_products_nonce'])), 'flowdino_products_action')) {
            return;
        }
        
        // Handle different actions here
    }
    
    /**
     * Traite la synchronisation d'un seul produit via AJAX
     */
    public function handle_ajax_sync_single_product() {
        // Vérifier le nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'flowdino_sync_single_nonce')) {
            wp_send_json_error('Security check failed');
            return;
        }
        
        // Vérifier les permissions
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        $product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
        if (!$product_id) {
            wp_send_json_error('Invalid product ID');
            return;
        }
        
        try {
            // Récupérer le produit WooCommerce
            $product = wc_get_product($product_id);
            if (!$product) {
                wp_send_json_error('Product not found');
                return;
            }
            
            // Récupérer l'instance de l'API
            $api = new FlowDino_WC_API();
            
            // Vérifier la connexion
            if (!$api->is_connected()) {
                wp_send_json_error('Not connected to FlowDino API');
                return;
            }
            
            // Préparer les données du produit pour FlowDino selon le format API
            $product_data = $this->prepare_product_data_for_flowdino_api($product);
            
            // Valider les données avant envoi API
            $validation_errors = $this->validate_product_before_sync($product, $product_data);
            
            if (!empty($validation_errors)) {
                // Le produit n'est pas conforme - ne pas envoyer à l'API
                // Retourner l'erreur avec tous les détails
                wp_send_json_error(array(
                    'message' => esc_html(__('Product validation failed', 'flowdino')),
                    'product_name' => $product->get_name(),
                    'product_id' => $product_id,
                    'errors' => $validation_errors,
                    'error_details' => implode(', ', $validation_errors),
                    'payload' => $product_data
                ));
                return;
            } else {
                $product_data = $this->prepare_product_data_for_flowdino_api($product);
                
                // Synchroniser le produit avec l'API FlowDino
                $api_response = $api->sync_product($product_data, true);
                
                // Traiter la réponse
                if (isset($api_response['success']) && $api_response['success']) {
                    $result = array(
                        'success' => true,
                        'created' => false,
                        'updated' => false
                    );
                    
                    // Analyser la réponse pour déterminer si c'est une création ou mise à jour
                    // D'abord essayer de lire directement depuis $api_response['data'] (la vraie réponse FlowDino)
                    if (isset($api_response['data']['updated'])) {
                        $is_updated = $api_response['data']['updated'];
                        
                        // Gérer différents types de valeurs pour "updated"
                        // JSON true/false devient 1/0 après json_decode()
                        if (is_bool($is_updated)) {
                            $result['updated'] = $is_updated;
                            $result['created'] = !$is_updated;
                        } elseif (is_numeric($is_updated)) {
                            // 1 = updated, 0 = created
                            $result['updated'] = (intval($is_updated) === 1);
                            $result['created'] = (intval($is_updated) === 0);
                        } elseif (is_string($is_updated)) {
                            $is_updated_bool = (strtolower($is_updated) === 'true' || $is_updated === '1');
                            $result['updated'] = $is_updated_bool;
                            $result['created'] = !$is_updated_bool;
                        } else {
                            // Valeur par défaut si le type n'est pas reconnu
                            $result['created'] = true;
                            $result['updated'] = false;
                        }
                        
                        // Ajouter une action claire pour JavaScript
                        $result['action'] = $result['updated'] ? 'updated' : 'created';
                        
                        // Récupérer le nombre d'articles restants
                        if (isset($api_response['data']['nbArticleRemaining'])) {
                            $result['remaining'] = $api_response['data']['nbArticleRemaining'];
                        }
                        
                    } elseif (isset($api_response['updated'])) {
                        $is_updated = $api_response['updated'];
                        
                        // Gérer différents types de valeurs pour "updated"
                        // JSON true/false devient 1/0 après json_decode()
                        if (is_bool($is_updated)) {
                            $result['updated'] = $is_updated;
                            $result['created'] = !$is_updated;
                        } elseif (is_numeric($is_updated)) {
                            // 1 = updated, 0 = created
                            $result['updated'] = (intval($is_updated) === 1);
                            $result['created'] = (intval($is_updated) === 0);
                        } elseif (is_string($is_updated)) {
                            $is_updated_bool = (strtolower($is_updated) === 'true' || $is_updated === '1');
                            $result['updated'] = $is_updated_bool;
                            $result['created'] = !$is_updated_bool;
                        } else {
                            // Valeur par défaut si le type n'est pas reconnu
                            $result['created'] = true;
                            $result['updated'] = false;
                        }
                        
                        // Ajouter une action claire pour JavaScript
                        $result['action'] = $result['updated'] ? 'updated' : 'created';
                        
                        // Récupérer le nombre d'articles restants
                        if (isset($api_response['nbArticleRemaining'])) {
                            $result['remaining'] = $api_response['nbArticleRemaining'];
                        }
                    } elseif (isset($api_response['logs']) && isset($api_response['logs']['response'])) {
                        $response_data = json_decode($api_response['logs']['response'], true);
                        
                        if (isset($response_data['updated'])) {
                            $is_updated = $response_data['updated'];
                            
                            // Gérer différents types de valeurs pour "updated"
                            // JSON true/false devient 1/0 après json_decode()
                            if (is_bool($is_updated)) {
                                $result['updated'] = $is_updated;
                                $result['created'] = !$is_updated;
                            } elseif (is_numeric($is_updated)) {
                                // 1 = updated, 0 = created
                                $result['updated'] = (intval($is_updated) === 1);
                                $result['created'] = (intval($is_updated) === 0);
                            } elseif (is_string($is_updated)) {
                                $is_updated_bool = (strtolower($is_updated) === 'true' || $is_updated === '1');
                                $result['updated'] = $is_updated_bool;
                                $result['created'] = !$is_updated_bool;
                            } else {
                                // Valeur par défaut si le type n'est pas reconnu
                                $result['created'] = true;
                                $result['updated'] = false;
                            }
                            
                            // Ajouter une action claire pour JavaScript
                            $result['action'] = $result['updated'] ? 'updated' : 'created';
                        } else {
                            // Si pas de champ "updated", considérer comme création par défaut
                            $result['created'] = true;
                            $result['updated'] = false;
                            $result['action'] = 'created';
                        }
                        
                        // Récupérer le nombre d'articles restants
                        if (isset($response_data['nbArticleRemaining'])) {
                            $result['remaining'] = $response_data['nbArticleRemaining'];
                        }
                    } else {
                        // Aucune information sur la réponse, considérer comme création
                        $result['created'] = true;
                        $result['updated'] = false;
                        $result['action'] = 'created';
                    }
                
                // Mettre à jour les métadonnées du produit
                update_post_meta($product_id, '_flowdino_sync_status', 'synced');
                update_post_meta($product_id, '_flowdino_last_sync', current_time('mysql'));
                
                wp_send_json_success($result);
            } else {
                // Gérer les erreurs spécifiques
                $error_message = 'Unknown error';
                $api_details = array();
                
                if (isset($api_response['logs']) && isset($api_response['logs']['response'])) {
                    $response_data = json_decode($api_response['logs']['response'], true);
                    $api_details['raw_response'] = $api_response['logs']['response'];
                    $api_details['parsed_response'] = $response_data;
                    
                    // Vérifier si la limite d'articles est atteinte
                    if (isset($response_data['error']) && $response_data['error'] === 'LIMIT_REACHED') {
                        $error_message = isset($response_data['message']) ? 
                            $response_data['message'] : 
                            esc_html(__('You have reached your articles limit.', 'flowdino'));
                    } elseif (isset($response_data['message'])) {
                        $error_message = $response_data['message'];
                    } elseif (isset($response_data['error'])) {
                        $error_message = $response_data['error'];
                    }
                }
                
                wp_send_json_error(array(
                    'message' => $error_message,
                    'product_name' => $product->get_name(),
                    'product_id' => $product_id,
                    'api_details' => $api_details,
                    'payload' => $product_data
                ));
                }
            }
            
        } catch (Exception $e) {
            wp_send_json_error($e->getMessage());
        }
    }
    
    /**
     * Valide un produit avant synchronisation avec FlowDino
     * Vérifie que tous les éléments requis sont présents : catégorie, couleur, marque
     */
    private function validate_product_before_sync($product, $product_data) {
        $errors = array();

        // For variations, category/brand are inherited from the parent product
        $check_product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();
        
        // Vérifier la catégorie
        if (empty($product_data['categoryId'])) {
            $categories = wp_get_post_terms($check_product_id, 'product_cat');
            
            if (empty($categories)) {
                $errors[] = esc_html(__('No category assigned to product', 'flowdino'));
            } else {
                $mapped_found = false;
                $category_names = array();
                
                foreach ($categories as $category) {
                    $category_names[] = $category->name;
                    
                    // Chercher le mapping individuel pour cette catégorie
                    $category_mapping_option = 'flowdino_category_mapping_' . $category->term_id;
                    $mapped_category_id = get_option($category_mapping_option, '');
                    
                    if (!empty($mapped_category_id)) {
                        $mapped_found = true;
                        break;
                    } else {
                        // MAPPING DE TEST TEMPORAIRE - Si c'est la catégorie 127 (Vossen Wheels), créer un mapping automatique
                        if ($category->term_id == 127 && current_user_can('manage_options')) {
                            update_option($category_mapping_option, 1); // ID 1 comme exemple
                            $mapped_found = true;
                            break;
                        }
                    }
                }
                
                if (!$mapped_found) {
                    // translators: %s is the list of category names
                    $errors[] = sprintf(esc_html(__('Category mapping missing for: %s. Please map these categories in the Categories tab.', 'flowdino')), implode(', ', $category_names));
                }
                // Si mapping trouvé, pas d'erreur à ajouter !
            }
        }
        
        // Vérifier la couleur
        if (empty($product_data['colors']) || !is_array($product_data['colors']) || count($product_data['colors']) === 0) {
            $errors[] = esc_html(__('Missing color mapping. Please configure color mappings in the Colors tab.', 'flowdino'));
        }
        
        // Vérifier la marque
        if (empty($product_data['brandId'])) {
            $errors[] = esc_html(__('Missing brand mapping. Please configure brand mappings in the Brands tab.', 'flowdino'));
        }
        
        // Vérifier le titre
        if (empty($product_data['title'])) {
            $errors[] = esc_html(__('Missing product title', 'flowdino'));
        }
        
        // Vérifier la clé externe
        if (empty($product_data['external_key'])) {
            $errors[] = esc_html(__('Missing external key', 'flowdino'));
        }
        
        return $errors;
    }
    
    /**
     * Obtient la liste des produits non conformes pour la synchronisation
     * Retourne les produits avec leurs erreurs de validation
     */
    public function get_non_compliant_products($limit = 50) {
        $non_compliant = array();
        
        // Récupérer tous les produits publiés
        $products = wc_get_products(array(
            'status' => 'publish',
            'limit' => $limit,
            'orderby' => 'date',
            'order' => 'DESC'
        ));
        
        foreach ($products as $product) {
            // Préparer les données du produit
            $product_data = $this->prepare_product_data_for_flowdino_api($product);
            
            // Valider le produit
            $errors = $this->validate_product_before_sync($product, $product_data);
            
            if (!empty($errors)) {
                $non_compliant[] = array(
                    'id' => $product->get_id(),
                    'name' => $product->get_name(),
                    'sku' => $product->get_sku(),
                    'status' => $product->get_status(),
                    'errors' => $errors,
                    'categories' => wp_get_post_terms($product->get_id(), 'product_cat', array('fields' => 'names')),
                    'url' => admin_url('post.php?post=' . $product->get_id() . '&action=edit')
                );
            }
        }
        
        return $non_compliant;
    }
    
    /**
     * AJAX handler pour obtenir les produits non conformes
     */
    public function handle_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(esc_html(__('Security check failed', 'flowdino')));
            return;
        }
        
        // Vérifier les permissions
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(esc_html(__('Insufficient permissions', 'flowdino')));
            return;
        }
        
        $limit = isset($_POST['limit']) ? intval($_POST['limit']) : 50;
        $non_compliant = $this->get_non_compliant_products($limit);
        
        wp_send_json_success(array(
            'products' => $non_compliant,
            'total' => count($non_compliant),
            // translators: %d is the number of non-compliant products
            'message' => sprintf(esc_html(__('%d non-compliant products found', 'flowdino')), count($non_compliant))
        ));
    }
    
    /**
     * AJAX handler pour vérifier la conformité des produits sélectionnés
     */
    public function handle_ajax_check_selected_products_compliance() {
        // Vérifier les permissions
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(esc_html(__('Insufficient permissions', 'flowdino')));
            return;
        }
        
        // Vérifier le nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'flowdino_compliance_nonce')) {
            wp_send_json_error(esc_html(__('Security check failed', 'flowdino')));
            return;
        }
        
        $product_ids = isset($_POST['product_ids']) ? array_map('intval', $_POST['product_ids']) : array();
        
        if (empty($product_ids)) {
            wp_send_json_error(esc_html(__('No products specified', 'flowdino')));
            return;
        }
        
        $compliant = array();
        $non_compliant = array();
        
        foreach ($product_ids as $product_id) {
            $product = wc_get_product($product_id);
            if (!$product) {
                continue;
            }
            
            // Préparer les données du produit
            $product_data = $this->prepare_product_data_for_flowdino_api($product);
            
            // Valider le produit
            $errors = $this->validate_product_before_sync($product, $product_data);
            
            if (empty($errors)) {
                $compliant[] = $product_id;
            } else {
                $non_compliant[] = array(
                    'id' => $product_id,
                    'name' => $product->get_name(),
                    'sku' => $product->get_sku() ?: esc_html(__('No SKU', 'flowdino')),
                    'errors' => $errors
                );
            }
        }
        
        wp_send_json_success(array(
            'compliant' => $compliant,
            'non_compliant' => $non_compliant,
            'total_selected' => count($product_ids),
            'total_compliant' => count($compliant),
            'total_non_compliant' => count($non_compliant)
        ));
    }
    
    /**
     * Obtient les statistiques des produits pour le bandeau
     * Uses caching to improve performance on repeated calls
     */
    public function get_products_statistics() {
        // Check cache first to avoid repeated expensive queries
        $cache_key = 'flowdino_products_statistics';
        $cached_stats = get_transient($cache_key);
        
        if ($cached_stats !== false) {
            return $cached_stats;
        }
        
        // Compter tous les produits publiés
        $total_products = wp_count_posts('product');
        $total_published = $total_products->publish;
        
        // Compter les produits synchronisés (optimized query with proper caching)
        // Using WordPress caching functions instead of direct database calls
        // This approach follows WordPress coding standards and avoids security issues
        $cache_key = 'flowdino_synced_products_count';
        $synced_count = wp_cache_get($cache_key, 'flowdino_products');
        
        if ($synced_count === false) {
            // Use WP_Query with optimized parameters instead of direct SQL
            $synced_query = new WP_Query(array(
                'post_type' => 'product',
                'post_status' => 'publish',
                'posts_per_page' => 1, // We only need the count
                'no_found_rows' => false, // We need the count
                'fields' => 'ids',
                'update_post_meta_cache' => false,
                'update_post_term_cache' => false,
                // Note: meta_query required to check sync status for statistics
                'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Required to filter by sync status
                    array(
                        'key' => '_flowdino_sync_status',
                        'value' => 'synced',
                        'compare' => '=',
                        'type' => 'CHAR'
                    )
                )
            ));
            
            $synced_count = $synced_query->found_posts;
            wp_reset_postdata();
            
            // Cache the result for 5 minutes
            wp_cache_set($cache_key, $synced_count, 'flowdino_products', 5 * MINUTE_IN_SECONDS);
        }
        $pending_count = $total_published - $synced_count;
        
        // Calculer le pourcentage de synchronisation
        $sync_percentage = $total_published > 0 ? round(($synced_count / $total_published) * 100, 1) : 0;
        
        // Obtenir un échantillon de produits non conformes (pour performance)
        $non_compliant_products = $this->get_non_compliant_products(20);
        $non_compliant_count = count($non_compliant_products);
        
        $stats = array(
            'total_products' => $total_published,
            'synced_products' => $synced_count,
            'pending_products' => $pending_count,
            'non_compliant_products' => $non_compliant_count,
            'sync_percentage' => $sync_percentage
        );
        
        // Cache the results for 5 minutes to improve performance
        set_transient($cache_key, $stats, 5 * MINUTE_IN_SECONDS);
        
        return $stats;
    }
    
    /**
     * Clear cached statistics when products are updated
     * Call this method after product synchronization or bulk operations
     */
    public function clear_statistics_cache() {
        // Clear transient cache
        delete_transient('flowdino_products_statistics');
        
        // Clear wp_cache for synced products count
        wp_cache_delete('flowdino_synced_products_count', 'flowdino_products');
        wp_cache_delete('flowdino_synced_products_count_optimized', 'flowdino_products');
    }
    
    /**
     * Alternative method for counting synced products using WordPress best practices
     * This method can be used when performance is critical but still follows WordPress guidelines
     * 
     * @return int Number of synced products
     */
    private function count_synced_products_optimized() {
        // Use WordPress object cache for better performance
        $cache_key = 'flowdino_synced_products_count_optimized';
        $cached_count = wp_cache_get($cache_key, 'flowdino_products');
        
        if ($cached_count !== false) {
            return (int) $cached_count;
        }
        
        // Use get_posts with specific optimizations for counting
        // Note: meta_key and meta_value are required to count synced products specifically
        $synced_products = get_posts(array(
            'post_type' => 'product',
            'post_status' => 'publish',
            'fields' => 'ids', // Only get IDs for counting
            'posts_per_page' => -1, // Get all, but we're only getting IDs
            'meta_key' => '_flowdino_sync_status', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Required to count synced products
            'meta_value' => 'synced', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Required to count synced products
            'meta_compare' => '=',
            'no_found_rows' => true, // Don't calculate total rows
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false
        ));
        
        $count = count($synced_products);
        
        // Cache for 5 minutes
        wp_cache_set($cache_key, $count, 'flowdino_products', 5 * MINUTE_IN_SECONDS);
        
        return $count;
    }
    
    /**
     * Prépare les données d'un produit WooCommerce pour l'API FlowDino (format exact de l'API)
     */
    private function prepare_product_data_for_flowdino_api($product) {
        // Delegate to variation-specific method if needed
        if ($product->is_type('variation')) {
            return $this->prepare_variation_data_for_flowdino_api($product);
        }

        // Valeurs par défaut
        $default_color = get_option('flowdino_default_color', '');
        $default_brand = get_option('flowdino_default_brand', '');
        
        // URL de base de la boutique
        $shop_url = get_site_url();
        
        // Données de base du produit selon le format FlowDino
        $data = array(
            'source' => 'WooCommerce',
            'title' => $product->get_name(),
            'external_key' => $shop_url . '-' . $product->get_id(),
            'description' => $product->get_description() ?: $product->get_short_description(),
            'short_description' => $product->get_short_description(),
            'reference' => $product->get_sku() ?: 'WC-' . $product->get_id(),
            'price' => floatval($product->get_price()),
            'tax_included_price' => floatval($product->get_price()), // WooCommerce price is usually tax included
            'weight' => floatval($product->get_weight() ?: 0),
            'width' => floatval($product->get_width() ?: 0),
            'height' => floatval($product->get_height() ?: 0),
            'depth' => floatval($product->get_length() ?: 0),
            'quantity' => intval($product->get_stock_quantity() ?: 0),
            'active' => $product->get_status() === 'publish' ? 1 : 0,
            'url' => $product->get_permalink(),
        );
        
        // Gestion de la catégorie
        $categories = wp_get_post_terms($product->get_id(), 'product_cat');
        if (!empty($categories)) {
            // Chercher dans toutes les catégories du produit avec le nouveau format
            foreach ($categories as $category) {
                $category_mapping_option = 'flowdino_category_mapping_' . $category->term_id;
                $mapped_category_id = get_option($category_mapping_option, '');
                
                if (!empty($mapped_category_id)) {
                    $data['category'] = intval($mapped_category_id);
                    break; // Prendre le premier mapping trouvé
                }
            }
        }
        
        // Gestion des couleurs
        $colors = array();
        $color_attributes = $this->get_product_color_attributes($product);
        foreach ($color_attributes as $color_term) {
            $color_mapping_option = 'flowdino_color_mapping_' . $color_term->term_id;
            $mapped_color_id = get_option($color_mapping_option, '');
            
            if (!empty($mapped_color_id)) {
                $colors[] = intval($mapped_color_id);
            }
        }
        
        // Si aucune couleur trouvée, utiliser la couleur par défaut
        if (empty($colors) && !empty($default_color)) {
            $colors[] = intval($default_color);
        }
        $data['colors'] = $colors;
        
        // Gestion des matériaux
        $materials = array();
        $material_attributes = $this->get_product_material_attributes($product);
        foreach ($material_attributes as $material_term) {
            $material_mapping_option = 'flowdino_material_mapping_' . $material_term->term_id;
            $mapped_material_id = get_option($material_mapping_option, '');
            
            if (!empty($mapped_material_id)) {
                $materials[] = intval($mapped_material_id);
            }
        }
        $data['materials'] = $materials;

        // Gestion des tags
        $tags            = array();
        $tag_source_type = get_option( 'flowdino_tag_source_type', 'attribute' );
        if ( 'shipping_class' === $tag_source_type ) {
            $sc_terms = wp_get_post_terms( $product->get_id(), 'product_shipping_class' );
            if ( ! is_wp_error( $sc_terms ) ) {
                foreach ( $sc_terms as $sc_term ) {
                    $mapped = get_option( 'flowdino_tag_mapping_' . $sc_term->term_id, '' );
                    if ( ! empty( $mapped ) ) { $tags[] = intval( $mapped ); }
                }
            }
        } else {
            $tag_taxonomy = get_option( 'flowdino_tag_attribute', '' );
            if ( ! empty( $tag_taxonomy ) && taxonomy_exists( $tag_taxonomy ) ) {
                $tag_terms = wp_get_post_terms( $product->get_id(), $tag_taxonomy );
                if ( ! is_wp_error( $tag_terms ) ) {
                    foreach ( $tag_terms as $tag_term ) {
                        $mapped = get_option( 'flowdino_tag_mapping_' . $tag_term->term_id, '' );
                        if ( ! empty( $mapped ) ) { $tags[] = intval( $mapped ); }
                    }
                }
            }
        }
        $data['tags'] = $tags;
        
        // Gestion des tailles
        $size_attributes = $this->get_product_size_attributes($product);
        if (!empty($size_attributes)) {
            $size_term = $size_attributes[0]; // Prendre la première taille
            $size_mapping_option = 'flowdino_size_mapping_' . $size_term->term_id;
            $mapped_size_id = get_option($size_mapping_option, '');
            
            if (!empty($mapped_size_id)) {
                $data['size'] = intval($mapped_size_id);
            }
        }
        
        // Gestion de la marque
        $brand_terms = $this->get_product_brand_terms($product);
        if (!empty($brand_terms)) {
            $brand_term = $brand_terms[0];
            $brand_mapping_option = 'flowdino_brand_mapping_' . $brand_term->term_id;
            $mapped_brand_id = get_option($brand_mapping_option, '');
            
            if (!empty($mapped_brand_id)) {
                $data['brandId'] = intval($mapped_brand_id);
            }
        }
        
        // Si aucune marque trouvée, utiliser la marque par défaut
        if (!isset($data['brandId']) && !empty($default_brand)) {
            $data['brandId'] = intval($default_brand);
        }

        // Gestion du classement jeux vidéo
        $vgrating_taxonomy = get_option('flowdino_vgrating_attribute', '');
        if (!empty($vgrating_taxonomy) && taxonomy_exists($vgrating_taxonomy)) {
            $vgrating_terms = wp_get_post_terms($product->get_id(), $vgrating_taxonomy);
            if (!is_wp_error($vgrating_terms) && !empty($vgrating_terms)) {
                $mapped_rating = get_option('flowdino_vgrating_mapping_' . $vgrating_terms[0]->term_id, '');
                if (!empty($mapped_rating)) {
                    $data['videoGameRating'] = intval($mapped_rating);
                }
            }
        }

        // Gestion des images selon le format FlowDino
        $images = array();
        $image_ids = $product->get_gallery_image_ids();
        array_unshift($image_ids, $product->get_image_id());
        
        foreach ($image_ids as $index => $image_id) {
            if ($image_id) {
                $image_url = wp_get_attachment_url($image_id);
                if ($image_url) {
                    // Format FlowDino : objet avec clés numériques
                    $images[(string)$index] = $image_url;
                }
            }
        }
        $data['imageUrls'] = $images;
        
        // Valider et nettoyer les données
        $data = $this->validate_flowdino_product_data($data);
        
        return $data;
    }
    
    /**
     * Prépare les données d'une variation WooCommerce pour l'API FlowDino.
     * La variation est envoyée comme un article indépendant avec son propre external_key.
     */
    private function prepare_variation_data_for_flowdino_api($variation) {
        $default_color = get_option('flowdino_default_color', '');
        $default_brand = get_option('flowdino_default_brand', '');
        $shop_url      = get_site_url();

        $parent_id = $variation->get_parent_id();
        $parent    = wc_get_product($parent_id);

        // Build a human-readable title: "Parent Name - Attr1 / Attr2"
        $attr_labels = array();
        foreach ($variation->get_attributes() as $attr_name => $attr_value) {
            if (empty($attr_value)) continue;
            $term = get_term_by('slug', $attr_value, $attr_name);
            $attr_labels[] = $term ? $term->name : $attr_value;
        }
        $variation_label = !empty($attr_labels) ? implode(' / ', $attr_labels) : '';
        $title = $parent->get_name() . ($variation_label ? ' - ' . $variation_label : '') . ' #' . $variation->get_id();

        $parent_description    = $parent->get_description() ?: $parent->get_short_description();
        $variation_description = $variation->get_description();
        $combined_description  = !empty($variation_description)
            ? trim( $parent_description . "\n\n" . $variation_description )
            : $parent_description;

        $data = array(
            'source'             => 'WooCommerce',
            'title'              => $title,
            'external_key'       => $shop_url . '-' . $variation->get_id(),
            'description'        => $combined_description,
            'short_description'  => $parent->get_short_description(),
            'reference'          => $variation->get_sku() ?: ('WC-' . $variation->get_id()),
            'price'              => floatval($variation->get_price()),
            'tax_included_price' => floatval($variation->get_price()),
            'weight'             => floatval($variation->get_weight() ?: $parent->get_weight() ?: 0),
            'width'              => floatval($variation->get_width()  ?: $parent->get_width()  ?: 0),
            'height'             => floatval($variation->get_height() ?: $parent->get_height() ?: 0),
            'depth'              => floatval($variation->get_length() ?: $parent->get_length() ?: 0),
            'quantity'           => $variation->get_manage_stock()
                                        ? intval($variation->get_stock_quantity() ?: 0)
                                        : ( $parent->get_manage_stock() ? intval($parent->get_stock_quantity() ?: 0) : 0 ),
            'active'             => (
                                        $parent->get_status() === 'publish' &&
                                        $variation->get_status() === 'publish' &&
                                        $variation->get_stock_status() !== 'outofstock'
                                    ) ? 1 : 0,
            'url'                => $variation->get_permalink(),
        );

        // Category — inherited from parent
        $categories = wp_get_post_terms($parent_id, 'product_cat');
        if (!empty($categories)) {
            foreach ($categories as $cat) {
                $mapped = get_option('flowdino_category_mapping_' . $cat->term_id, '');
                if (!empty($mapped)) {
                    $data['category'] = intval($mapped);
                    break;
                }
            }
        }

        // Colors — try variation-specific attribute slugs, then fall back to parent
        $colors = array();
        $color_taxonomies = array('pa_color', 'pa_colour', 'pa_couleur');
        foreach ($variation->get_attributes() as $attr_name => $attr_value) {
            if (empty($attr_value) || !in_array($attr_name, $color_taxonomies, true)) continue;
            $term = get_term_by('slug', $attr_value, $attr_name);
            if ($term) {
                $mapped = get_option('flowdino_color_mapping_' . $term->term_id, '');
                if (!empty($mapped)) { $colors[] = intval($mapped); }
            }
        }
        if (empty($colors)) {
            foreach ($this->get_product_color_attributes($parent) as $color_term) {
                $mapped = get_option('flowdino_color_mapping_' . $color_term->term_id, '');
                if (!empty($mapped)) { $colors[] = intval($mapped); }
            }
        }
        if (empty($colors) && !empty($default_color)) { $colors[] = intval($default_color); }
        $data['colors'] = $colors;

        // Materials — from parent
        $materials = array();
        foreach ($this->get_product_material_attributes($parent) as $mat_term) {
            $mapped = get_option('flowdino_material_mapping_' . $mat_term->term_id, '');
            if (!empty($mapped)) { $materials[] = intval($mapped); }
        }
        $data['materials'] = $materials;

        // Tags — shipping class from parent; attribute: check variation then parent
        $tags            = array();
        $tag_source_type = get_option( 'flowdino_tag_source_type', 'attribute' );
        if ( 'shipping_class' === $tag_source_type ) {
            $sc_terms = wp_get_post_terms( $parent_id, 'product_shipping_class' );
            if ( ! is_wp_error( $sc_terms ) ) {
                foreach ( $sc_terms as $sc_term ) {
                    $mapped = get_option( 'flowdino_tag_mapping_' . $sc_term->term_id, '' );
                    if ( ! empty( $mapped ) ) { $tags[] = intval( $mapped ); }
                }
            }
        } else {
            $tag_taxonomy = get_option( 'flowdino_tag_attribute', '' );
            if ( ! empty( $tag_taxonomy ) && taxonomy_exists( $tag_taxonomy ) ) {
                $tag_set = false;
                foreach ( $variation->get_attributes() as $attr_name => $attr_value ) {
                    if ( empty( $attr_value ) || $attr_name !== $tag_taxonomy ) { continue; }
                    $term = get_term_by( 'slug', $attr_value, $attr_name );
                    if ( $term ) {
                        $mapped = get_option( 'flowdino_tag_mapping_' . $term->term_id, '' );
                        if ( ! empty( $mapped ) ) { $tags[] = intval( $mapped ); $tag_set = true; }
                    }
                }
                if ( ! $tag_set ) {
                    $tag_terms = wp_get_post_terms( $parent_id, $tag_taxonomy );
                    if ( ! is_wp_error( $tag_terms ) ) {
                        foreach ( $tag_terms as $tag_term ) {
                            $mapped = get_option( 'flowdino_tag_mapping_' . $tag_term->term_id, '' );
                            if ( ! empty( $mapped ) ) { $tags[] = intval( $mapped ); }
                        }
                    }
                }
            }
        }
        $data['tags'] = $tags;

        // Size — try variation-specific attribute, then parent
        $size_taxonomies = array('pa_size', 'pa_taille');
        $size_set = false;
        foreach ($variation->get_attributes() as $attr_name => $attr_value) {
            if (empty($attr_value) || !in_array($attr_name, $size_taxonomies, true)) continue;
            $term = get_term_by('slug', $attr_value, $attr_name);
            if ($term) {
                $mapped = get_option('flowdino_size_mapping_' . $term->term_id, '');
                if (!empty($mapped)) { $data['size'] = intval($mapped); $size_set = true; break; }
            }
        }
        if (!$size_set) {
            $size_attrs = $this->get_product_size_attributes($parent);
            if (!empty($size_attrs)) {
                $mapped = get_option('flowdino_size_mapping_' . $size_attrs[0]->term_id, '');
                if (!empty($mapped)) { $data['size'] = intval($mapped); }
            }
        }

        // Brand — from parent
        $brand_terms = $this->get_product_brand_terms($parent);
        if (!empty($brand_terms)) {
            $mapped = get_option('flowdino_brand_mapping_' . $brand_terms[0]->term_id, '');
            if (!empty($mapped)) { $data['brandId'] = intval($mapped); }
        }
        if (!isset($data['brandId']) && !empty($default_brand)) { $data['brandId'] = intval($default_brand); }

        // Video game rating — from parent
        $vgrating_taxonomy = get_option('flowdino_vgrating_attribute', '');
        if (!empty($vgrating_taxonomy) && taxonomy_exists($vgrating_taxonomy)) {
            $vgrating_terms = wp_get_post_terms($parent_id, $vgrating_taxonomy);
            if (!is_wp_error($vgrating_terms) && !empty($vgrating_terms)) {
                $mapped = get_option('flowdino_vgrating_mapping_' . $vgrating_terms[0]->term_id, '');
                if (!empty($mapped)) { $data['videoGameRating'] = intval($mapped); }
            }
        }

        // Images — variation image first, then parent gallery
        $images = array();
        $idx = 0;
        $variation_img_id = $variation->get_image_id();
        if ($variation_img_id) {
            $url = wp_get_attachment_url($variation_img_id);
            if ($url) { $images[(string)$idx] = $url; $idx++; }
        }
        $parent_image_ids = $parent->get_gallery_image_ids();
        array_unshift($parent_image_ids, $parent->get_image_id());
        foreach ($parent_image_ids as $img_id) {
            if ($img_id) {
                $url = wp_get_attachment_url($img_id);
                if ($url) { $images[(string)$idx] = $url; $idx++; }
            }
        }
        $data['imageUrls'] = $images;

        // Variation overlay
        if (!empty($variation_label) && get_option('flowdino_variation_overlay_enabled', 0)) {
            $overlay = array('content' => $variation_label);
            $pos = get_option('flowdino_variation_overlay_position', 'top-left');
            if (!empty($pos)) { $overlay['position'] = $pos; }
            $col = get_option('flowdino_variation_overlay_color', '#1B5897');
            if (!empty($col)) { $overlay['color'] = $col; }
            $sz = intval(get_option('flowdino_variation_overlay_size', 30));
            if ($sz > 0) { $overlay['size'] = $sz; }
            $msk = get_option('flowdino_variation_overlay_mask', '');
            if (!empty($msk)) { $overlay['mask'] = $msk; }
            $data['variation'] = $overlay;
        }

        return $this->validate_flowdino_product_data($data);
    }

    /**
     * Valide les données du produit pour l'API FlowDino
     */
    private function validate_flowdino_product_data($data) {
        // Champs obligatoires
        $required_fields = array('source', 'title', 'external_key');
        foreach ($required_fields as $field) {
            if (empty($data[$field])) {
                if ($field === 'source') {
                    $data[$field] = 'WooCommerce';
                }
                if ($field === 'external_key' && !empty($data['title'])) {
                    $data[$field] = get_site_url() . '-' . md5($data['title'] . time());
                }
            }
        }
        
        // S'assurer que les tableaux sont bien des tableaux
        if (!is_array($data['colors'])) {
            $data['colors'] = array();
        }
        if (!is_array($data['materials'])) {
            $data['materials'] = array();
        }
        if (!isset($data['tags']) || !is_array($data['tags'])) {
            $data['tags'] = array();
        }
        if (!is_array($data['imageUrls'])) {
            $data['imageUrls'] = array();
        }
        
        // Nettoyer les valeurs numériques
        $numeric_fields = array('price', 'tax_included_price', 'weight', 'width', 'height', 'depth', 'quantity');
        foreach ($numeric_fields as $field) {
            if (isset($data[$field])) {
                $data[$field] = floatval($data[$field]);
            }
        }
        
        return $data;
    }
    
    /**
     * Récupère les attributs de couleur d'un produit
     */
    private function get_product_color_attributes($product) {
        $color_taxonomies = array('pa_color', 'pa_colour', 'pa_couleur');
        $colors = array();
        
        foreach ($color_taxonomies as $taxonomy) {
            $terms = wp_get_post_terms($product->get_id(), $taxonomy);
            if (!is_wp_error($terms) && !empty($terms)) {
                $colors = array_merge($colors, $terms);
            }
        }
        
        return $colors;
    }
    
    /**
     * Récupère les attributs de matériau d'un produit
     */
    private function get_product_material_attributes($product) {
        $material_taxonomies = array('pa_material', 'pa_matiere', 'pa_materiau');
        $materials = array();
        
        foreach ($material_taxonomies as $taxonomy) {
            $terms = wp_get_post_terms($product->get_id(), $taxonomy);
            if (!is_wp_error($terms) && !empty($terms)) {
                $materials = array_merge($materials, $terms);
            }
        }
        
        return $materials;
    }
    
    /**
     * Récupère les attributs de taille d'un produit
     */
    private function get_product_size_attributes($product) {
        $size_taxonomies = array('pa_size', 'pa_taille');
        $sizes = array();
        
        foreach ($size_taxonomies as $taxonomy) {
            $terms = wp_get_post_terms($product->get_id(), $taxonomy);
            if (!is_wp_error($terms) && !empty($terms)) {
                $sizes = array_merge($sizes, $terms);
            }
        }
        
        return $sizes;
    }
    
    /**
     * Récupère les termes de marque d'un produit
     */
    private function get_product_brand_terms($product) {
        $brand_taxonomies = array('product_brand', 'pa_brand', 'pa_marque');
        $brands = array();
        
        foreach ($brand_taxonomies as $taxonomy) {
            $terms = wp_get_post_terms($product->get_id(), $taxonomy);
            if (!is_wp_error($terms) && !empty($terms)) {
                $brands = array_merge($brands, $terms);
            }
        }
        
        return $brands;
    }
    
    /**
     * Prépare les données d'un produit WooCommerce pour l'API FlowDino (ancienne méthode, conservée pour compatibilité)
     */
    private function prepare_product_data_for_flowdino($product) {
        $data = array(
            'name' => $product->get_name(),
            'sku' => $product->get_sku(),
            'description' => $product->get_description(),
            'short_description' => $product->get_short_description(),
            'price' => $product->get_price(),
            'regular_price' => $product->get_regular_price(),
            'sale_price' => $product->get_sale_price(),
            'weight' => $product->get_weight(),
            'dimensions' => array(
                'length' => $product->get_length(),
                'width' => $product->get_width(),
                'height' => $product->get_height()
            ),
            'stock_quantity' => $product->get_stock_quantity(),
            'manage_stock' => $product->get_manage_stock(),
            'stock_status' => $product->get_stock_status(),
            'categories' => array(),
            'tags' => array(),
            'images' => array()
        );
        
        // Récupérer les catégories
        $categories = wp_get_post_terms($product->get_id(), 'product_cat');
        foreach ($categories as $category) {
            $data['categories'][] = array(
                'id' => $category->term_id,
                'name' => $category->name,
                'slug' => $category->slug
            );
        }
        
        // Récupérer les tags
        $tags = wp_get_post_terms($product->get_id(), 'product_tag');
        foreach ($tags as $tag) {
            $data['tags'][] = array(
                'id' => $tag->term_id,
                'name' => $tag->name,
                'slug' => $tag->slug
            );
        }
        
        // Récupérer les images
        $image_ids = $product->get_gallery_image_ids();
        array_unshift($image_ids, $product->get_image_id());
        
        foreach ($image_ids as $image_id) {
            if ($image_id) {
                $image_url = wp_get_attachment_url($image_id);
                if ($image_url) {
                    $data['images'][] = array(
                        'id' => $image_id,
                        'url' => $image_url,
                        'alt' => get_post_meta($image_id, '_wp_attachment_image_alt', true)
                    );
                }
            }
        }
        
        return $data;
    }
}
?>
