<?php

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

/**
 * FlowDino API Handler for WooCommerce
 */
class FlowDino_WC_API {
    
    /**
     * API URL
     */
    private $api_url;
    
    /**
     * User credentials
     */
    private $email;
    private $password;
    private $token;
    
    /**
     * Constructor
     */
    public function __construct() {
        $this->api_url = get_option('flowdino_api_url', 'https://www.flowdino.com');
        $this->email = get_option('flowdino_email', '');
        $this->password = get_option('flowdino_password', '');
        $this->token = get_option('flowdino_token', '');
        
        // Si on n'a pas de token mais qu'on a les identifiants, essayer de se connecter
        if (empty($this->token) && !empty($this->email) && !empty($this->password)) {
            $this->auto_login();
        }
    }
    
    /**
     * Tentative de connexion automatique
     */
    private function auto_login() {
        try {
            $login_result = $this->login();
            if ($login_result['success']) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                error_log('FlowDino: Auto-login successful for ' . $this->email);
            } else {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                error_log('FlowDino: Auto-login failed for ' . $this->email . ' - ' . $login_result['message']);
            }
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: Auto-login exception - ' . $e->getMessage());
        }
    }
    
    /**
     * Login to FlowDino API
     */
    public function login($email = null, $password = null) {
        if ($email) $this->email = $email;
        if ($password) $this->password = $password;
        
        $response = wp_remote_post($this->api_url . '/api/login_check', array(
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode(array(
                'email' => $this->email,
                'password' => $this->password
            )),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => $response->get_error_message()
            );
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (wp_remote_retrieve_response_code($response) === 200 && isset($data['token'])) {
            $this->token = $data['token'];
            update_option('flowdino_email', $this->email);
            update_option('flowdino_password', $this->password);
            update_option('flowdino_token', $this->token);
            
            return array(
                'success' => true,
                'token' => $this->token
            );
        }
        
        return array(
            'success' => false,
            'message' => isset($data['message']) ? esc_html($data['message']) : esc_html(
                /* translators: Message when login fails */
                __('Login failed', 'flowdino'))
        );
    }
      /**
     * Refresh token
     */
    public function refresh_token() {
        if (empty($this->token)) {
            return false;
        }
        
        $response = wp_remote_post($this->api_url . '/api/token/refresh', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type' => 'application/json',
            ),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            return false;
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (wp_remote_retrieve_response_code($response) === 200 && isset($data['token'])) {
            $this->token = $data['token'];
            update_option('flowdino_token', $this->token);
            update_option('flowdino_token_last_refresh', time());
            return true;
        }
        
        return false;
    }
    
    /**
     * Test API connection
     */
    public function test_connection() {
        if (empty($this->token)) {
            return array(
                'success' => false,
                'message' => __('No token available', 'flowdino')
            );
        }
        
        // Utiliser l'endpoint categories/tree pour tester la connexion
        $response = wp_remote_get($this->api_url . '/api/categories/tree', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type' => 'application/json',
            ),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => $response->get_error_message()
            );
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        
        // Si le token est invalide (401), nettoyer les credentials
        if ($response_code === 401) {
            update_option('flowdino_token', '');
            update_option('flowdino_email', '');
            update_option('flowdino_password', '');
            $this->token = '';
        }
        
        return array(
            'success' => $response_code === 200,
            'message' => $response_code === 200 
                ? __('Connection successful', 'flowdino')
                : __('Connection failed', 'flowdino') . ' (HTTP ' . $response_code . ')'
        );
    }
    
    /**
     * Get categories from FlowDino
     */
    public function get_categories() {
        if (empty($this->token)) {
            return false;
        }
        
        $response = wp_remote_get($this->api_url . '/api/categories/tree', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type' => 'application/json',
            ),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            return false;
        }
        
        // Si le token est invalide, nettoyer les credentials
        if (wp_remote_retrieve_response_code($response) === 401) {
            update_option('flowdino_token', '');
            update_option('flowdino_email', '');
            update_option('flowdino_password', '');
            $this->token = '';
            return false;
        }
        
        $body = wp_remote_retrieve_body($response);
        return json_decode($body, true);
    }
    
    /**
     * Get brands from FlowDino
     */
    public function get_brands() {
        if (empty($this->token)) {
            return array(
                'success' => false,
                'message' => __('No authentication token available', 'flowdino'),
                'data' => array()
            );
        }
        
        $response = wp_remote_get($this->api_url . '/api/brands', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type' => 'application/json',
            ),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: API error for brands - ' . $response->get_error_message());
            return array(
                'success' => false,
                'message' => $response->get_error_message(),
                'data' => array()
            );
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        
        // Si le token est invalide, nettoyer les credentials
        if ($response_code === 401) {
            update_option('flowdino_token', '');
            update_option('flowdino_email', '');
            update_option('flowdino_password', '');
            $this->token = '';
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: Token expired for brands API');
            return array(
                'success' => false,
                'message' => __('Authentication token expired. Please reconnect.', 'flowdino'),
                'data' => array()
            );
        }
        
        if ($response_code !== 200) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: HTTP error ' . $response_code . ' for brands API');
            return array(
                'success' => false,
                'message' => __('Failed to retrieve brands from FlowDino', 'flowdino') . ' (HTTP ' . $response_code . ')',
                'data' => array()
            );
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: JSON decode error for brands - ' . json_last_error_msg());
            return array(
                'success' => false,
                'message' => __('Invalid response format from FlowDino brands API', 'flowdino'),
                'data' => array()
            );
        }
        
        // Log the response structure for debugging
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log,WordPress.PHP.DevelopmentFunctions.error_log_print_r -- Logging for debugging purposes
            error_log('FlowDino: Brands API response structure: ' . print_r($data, true));
        }
        
        // Adapter la structure de réponse selon ce que l'API retourne
        if (is_array($data)) {
            // Si l'API retourne directement un tableau de marques
            if (isset($data[0]) && is_array($data[0]) && isset($data[0]['id'])) {
                return array(
                    'success' => true,
                    'message' => __('Brands loaded successfully', 'flowdino'),
                    'data' => $data
                );
            }
            // Si l'API retourne un objet avec les marques dans une propriété
            elseif (isset($data['data']) && is_array($data['data'])) {
                return array(
                    'success' => true,
                    'message' => __('Brands loaded successfully', 'flowdino'),
                    'data' => $data['data']
                );
            }
            // Si l'API retourne un objet avec les marques dans une autre propriété
            elseif (isset($data['brands']) && is_array($data['brands'])) {
                return array(
                    'success' => true,
                    'message' => __('Brands loaded successfully', 'flowdino'),
                    'data' => $data['brands']
                );
            }
            // Si l'API retourne un objet avec une propriété member (comme pour les couleurs)
            elseif (isset($data['member']) && is_array($data['member'])) {
                return array(
                    'success' => true,
                    'message' => __('Brands loaded successfully', 'flowdino'),
                    'data' => $data['member']
                );
            }
        }
        
        // Si aucune structure connue n'est trouvée
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
        error_log('FlowDino: Unknown brands API response structure');
        return array(
            'success' => false,
            'message' => __('Unexpected response format from FlowDino brands API', 'flowdino'),
            'data' => array()
        );
    }
    
    /**
     * Create a new brand in FlowDino
     */
    public function create_brand($name) {
        if (empty($this->token)) {
            return array(
                'success' => false,
                'message' => __('No authentication token available', 'flowdino'),
            );
        }

        $response = wp_remote_post($this->api_url . '/api/brands', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type'  => 'application/json',
            ),
            'body'    => wp_json_encode(array('name' => $name)),
            'timeout' => 30,
        ));

        if (is_wp_error($response)) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: API error creating brand - ' . $response->get_error_message());
            return array(
                'success' => false,
                'message' => $response->get_error_message(),
            );
        }

        $response_code = wp_remote_retrieve_response_code($response);
        $body          = wp_remote_retrieve_body($response);
        $data          = json_decode($body, true);

        if ($response_code === 201) {
            return array(
                'success' => true,
                'message' => __('Brand created successfully', 'flowdino'),
                'data'    => array(
                    'id'   => isset($data['id']) ? intval($data['id']) : 0,
                    'name' => isset($data['name']) ? $data['name'] : $name,
                ),
            );
        }

        $error_message = isset($data['message']) ? $data['message'] : __('Failed to create brand', 'flowdino');
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
        error_log('FlowDino: HTTP error ' . $response_code . ' creating brand: ' . $body);
        return array(
            'success' => false,
            'message' => $error_message,
        );
    }

    /**
     * Search brands from FlowDino by name
     */
    public function search_brands($search_term) {
        if (empty($this->token)) {
            return array(
                'success' => false,
                'message' => __('No authentication token available', 'flowdino'),
                'data' => array()
            );
        }
        
        if (empty($search_term)) {
            return array(
                'success' => false,
                'message' => __('Search term is required', 'flowdino'),
                'data' => array()
            );
        }
        
        $search_url = $this->api_url . '/api/brands?name=' . urlencode($search_term);
        
        $response = wp_remote_get($search_url, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type' => 'application/json',
            ),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: API error for brand search - ' . $response->get_error_message());
            return array(
                'success' => false,
                'message' => $response->get_error_message(),
                'data' => array()
            );
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        
        // Si le token est invalide, nettoyer les credentials
        if ($response_code === 401) {
            update_option('flowdino_token', '');
            update_option('flowdino_email', '');
            update_option('flowdino_password', '');
            $this->token = '';
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: Token expired for brand search API');
            return array(
                'success' => false,
                'message' => __('Authentication token expired. Please reconnect.', 'flowdino'),
                'data' => array()
            );
        }
        
        if ($response_code !== 200) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: HTTP error ' . $response_code . ' for brand search API');
            return array(
                'success' => false,
                'message' => __('Failed to search brands in FlowDino', 'flowdino') . ' (HTTP ' . $response_code . ')',
                'data' => array()
            );
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: JSON decode error for brand search - ' . json_last_error_msg());
            return array(
                'success' => false,
                'message' => __('Invalid response format from FlowDino brand search API', 'flowdino'),
                'data' => array()
            );
        }
        
        // Log the response structure for debugging
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log,WordPress.PHP.DevelopmentFunctions.error_log_print_r -- Logging for debugging purposes
            error_log('FlowDino: Brand search API response structure: ' . print_r($data, true));
        }
        
        // Adapter la structure de réponse selon ce que l'API retourne
        if (is_array($data)) {
            // Si l'API retourne directement un tableau de marques
            if (isset($data[0]) && is_array($data[0]) && isset($data[0]['id'])) {
                return array(
                    'success' => true,
                    /* translators: %d is the number of brands found */
                    'message' => sprintf(__('%d brands found', 'flowdino'), count($data)),
                    'data' => $data
                );
            }
            // Si l'API retourne un objet avec les marques dans une propriété
            elseif (isset($data['data']) && is_array($data['data'])) {
                return array(
                    'success' => true,
                    /* translators: %d is the number of brands found */
                    'message' => sprintf(__('%d brands found', 'flowdino'), count($data['data'])),
                    'data' => $data['data']
                );
            }
            // Si l'API retourne un objet avec les marques dans une autre propriété
            elseif (isset($data['brands']) && is_array($data['brands'])) {
                return array(
                    'success' => true,
                    /* translators: %d is the number of brands found */
                    'message' => sprintf(__('%d brands found', 'flowdino'), count($data['brands'])),
                    'data' => $data['brands']
                );
            }
            // Si l'API retourne un objet avec une propriété member (comme pour les couleurs)
            elseif (isset($data['member']) && is_array($data['member'])) {
                return array(
                    'success' => true,
                    /* translators: %d is the number of brands found */
                    'message' => sprintf(__('%d brands found', 'flowdino'), count($data['member'])),
                    'data' => $data['member']
                );
            }
        }
        
        // Si aucune structure connue n'est trouvée
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
        error_log('FlowDino: Unknown brand search API response structure');
        return array(
            'success' => false,
            'message' => __('Unexpected response format from FlowDino brand search API', 'flowdino'),
            'data' => array()
        );
    }
    
    /**
     * Get a single brand by ID from FlowDino
     */
    public function get_brand_by_id($brand_id) {
        if (empty($this->token)) {
            return array(
                'success' => false,
                'message' => __('No authentication token available', 'flowdino'),
                'data' => null
            );
        }
        
        if (empty($brand_id)) {
            return array(
                'success' => false,
                'message' => __('Brand ID is required', 'flowdino'),
                'data' => null
            );
        }
        
        $response = wp_remote_get($this->api_url . '/api/brands/' . $brand_id, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type' => 'application/json',
            ),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: API error for brand by ID - ' . $response->get_error_message());
            return array(
                'success' => false,
                'message' => $response->get_error_message(),
                'data' => null
            );
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        
        // Si le token est invalide, nettoyer les credentials
        if ($response_code === 401) {
            update_option('flowdino_token', '');
            update_option('flowdino_email', '');
            update_option('flowdino_password', '');
            $this->token = '';
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: Token expired for brand by ID API');
            return array(
                'success' => false,
                'message' => __('Authentication token expired. Please reconnect.', 'flowdino'),
                'data' => null
            );
        }
        
        if ($response_code === 404) {
            return array(
                'success' => false,
                'message' => __('Brand not found', 'flowdino'),
                'data' => null
            );
        }
        
        if ($response_code !== 200) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: HTTP error ' . $response_code . ' for brand by ID API');
            return array(
                'success' => false,
                'message' => __('Failed to retrieve brand from FlowDino', 'flowdino') . ' (HTTP ' . $response_code . ')',
                'data' => null
            );
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: JSON decode error for brand by ID - ' . json_last_error_msg());
            return array(
                'success' => false,
                'message' => __('Invalid response format from FlowDino brand API', 'flowdino'),
                'data' => null
            );
        }
        
        // Log the response structure for debugging
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log,WordPress.PHP.DevelopmentFunctions.error_log_print_r -- Logging for debugging purposes
            error_log('FlowDino: Brand by ID API response structure: ' . print_r($data, true));
        }
        
        return array(
            'success' => true,
            'message' => __('Brand retrieved successfully', 'flowdino'),
            'data' => $data
        );
    }

    /**
     * Get or create default "no brand" option from FlowDino
     */
    public function get_default_no_brand() {
        if (empty($this->token)) {
            return array(
                'success' => false,
                'message' => __('No authentication token available', 'flowdino'),
                'data' => null
            );
        }
        
        // Rechercher une marque avec le nom "pas de marque" ou équivalents
        $search_terms = array(
            'pas de marque',
            'no brand',
            'sans marque',
            'default',
            'aucune marque'
        );
        
        foreach ($search_terms as $search_term) {
            $result = $this->search_brands($search_term);
            
            if ($result['success'] && !empty($result['data'])) {
                // Chercher une correspondance exacte ou partielle
                foreach ($result['data'] as $brand) {
                    $brand_name_lower = strtolower($brand['name']);
                    $search_term_lower = strtolower($search_term);
                    
                    // Correspondance exacte
                    if ($brand_name_lower === $search_term_lower) {
                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                        error_log('FlowDino: Found exact default brand match: ' . $brand['name'] . ' (ID: ' . $brand['id'] . ')');
                        return array(
                            'success' => true,
                            /* translators: %s is the brand name */
                            'message' => sprintf(__('Default brand found: %s', 'flowdino'), $brand['name']),
                            'data' => $brand
                        );
                    }
                    
                    // Correspondance partielle (contient le terme)
                    if (strpos($brand_name_lower, $search_term_lower) !== false) {
                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                        error_log('FlowDino: Found partial default brand match: ' . $brand['name'] . ' (ID: ' . $brand['id'] . ')');
                        return array(
                            'success' => true,
                            /* translators: %s is the brand name */
                            'message' => sprintf(__('Default brand found: %s', 'flowdino'), $brand['name']),
                            'data' => $brand
                        );
                    }
                }
            }
        }
        
        // Si aucune marque "pas de marque" trouvée, prendre la première marque disponible
        $all_brands = $this->get_brands();
        if ($all_brands['success'] && !empty($all_brands['data'])) {
            $first_brand = $all_brands['data'][0];
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: No "no brand" found, using first available brand: ' . $first_brand['name'] . ' (ID: ' . $first_brand['id'] . ')');
            return array(
                'success' => true,
                /* translators: %s is the brand name */
                'message' => sprintf(__('Using first available brand as default: %s', 'flowdino'), $first_brand['name']),
                'data' => $first_brand
            );
        }
        
        return array(
            'success' => false,
            'message' => __('No brands available in FlowDino', 'flowdino'),
            'data' => null
        );
    }
    
    /**
     * Get brand names for a list of brand IDs
     * Returns an associative array [brand_id => brand_name]
     */
    public function get_brand_names_by_ids($brand_ids) {
        if (empty($brand_ids) || !is_array($brand_ids)) {
            return array();
        }
        
        $brand_names = array();
        
        // D'abord, essayer de récupérer toutes les marques et les filtrer
        $all_brands = $this->get_brands();
        if ($all_brands['success'] && !empty($all_brands['data'])) {
            foreach ($all_brands['data'] as $brand) {
                if (isset($brand['id'], $brand['name']) && in_array($brand['id'], $brand_ids)) {
                    $brand_names[$brand['id']] = $brand['name'];
                }
            }
        }
        
        // Pour les IDs non trouvés, faire des requêtes individuelles
        foreach ($brand_ids as $brand_id) {
            if (!isset($brand_names[$brand_id])) {
                $brand_result = $this->get_brand_by_id($brand_id);
                if ($brand_result['success'] && $brand_result['data'] && isset($brand_result['data']['name'])) {
                    $brand_names[$brand_id] = $brand_result['data']['name'];
                }
            }
        }
        
        return $brand_names;
    }

    /**
     * Auto-set default brand if none is configured
     */
    public function auto_set_default_brand() {
        $current_default = get_option('flowdino_default_brand', '');
        
        // Si une marque par défaut est déjà configurée, ne rien faire
        if (!empty($current_default)) {
            $current_default_name = get_option('flowdino_default_brand_name', '');
            return array(
                'success' => true,
                'message' => __('Default brand already configured', 'flowdino'),
                'data' => array(
                    'brand_id' => $current_default,
                    'brand_name' => $current_default_name
                )
            );
        }
        
        // Rechercher et définir une marque par défaut
        $result = $this->get_default_no_brand();
        
        if ($result['success'] && $result['data']) {
            $brand_id = $result['data']['id'];
            $brand_name = $result['data']['name'];
            
            // Sauvegarder à la fois l'ID et le nom
            update_option('flowdino_default_brand', $brand_id);
            update_option('flowdino_default_brand_name', $brand_name);
            
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: Auto-set default brand: ' . $brand_name . ' (ID: ' . $brand_id . ')');
            
            return array(
                'success' => true,
                /* translators: %s is the brand name */
                'message' => sprintf(__('Default brand automatically set to: %s', 'flowdino'), $brand_name),
                'data' => array(
                    'brand_id' => $brand_id,
                    'brand_name' => $brand_name
                )
            );
        }
        
        return array(
            'success' => false,
            'message' => $result['message'],
            'data' => null
        );
    }
    
    /**
     * Search colors from FlowDino by name
     */
    public function search_colors($search_term) {
        if (empty($this->token)) {
            return array(
                'success' => false,
                'message' => __('No authentication token available', 'flowdino'),
                'data' => array()
            );
        }
        
        if (empty($search_term)) {
            return array(
                'success' => false,
                'message' => __('Search term is required', 'flowdino'),
                'data' => array()
            );
        }
        
        // Get default country ISO (use WooCommerce base country)
        $country_iso = WC()->countries->get_base_country();
        
        $search_url = $this->api_url . '/api/colors?country.isoCode=' . $country_iso . '&name=' . urlencode($search_term);
        
        $response = wp_remote_get($search_url, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: API error for color search - ' . $response->get_error_message());
            return array(
                'success' => false,
                'message' => $response->get_error_message(),
                'data' => array()
            );
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        
        // Si le token est invalide, nettoyer les credentials
        if ($response_code === 401) {
            update_option('flowdino_token', '');
            update_option('flowdino_email', '');
            update_option('flowdino_password', '');
            $this->token = '';
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: Token expired for color search API');
            return array(
                'success' => false,
                'message' => __('Authentication token expired. Please reconnect.', 'flowdino'),
                'data' => array()
            );
        }
        
        if ($response_code !== 200) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: HTTP error ' . $response_code . ' for color search API');
            return array(
                'success' => false,
                'message' => __('Failed to search colors in FlowDino', 'flowdino') . ' (HTTP ' . $response_code . ')',
                'data' => array()
            );
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: JSON decode error for color search - ' . json_last_error_msg());
            return array(
                'success' => false,
                'message' => __('Invalid response format from FlowDino color search API', 'flowdino'),
                'data' => array()
            );
        }
        
        // Log the response structure for debugging
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log,WordPress.PHP.DevelopmentFunctions.error_log_print_r -- Logging for debugging purposes
            error_log('FlowDino: Color search API response structure: ' . print_r($data, true));
        }
        
        // Retourner dans le même format que get_colors
        return array(
            'success' => true,
            /* translators: %d is the number of colors found */
            'message' => sprintf(__('%d colors found', 'flowdino'), is_array($data) ? count($data) : 0),
            'member' => isset($data) ? $data : array()
        );
    }

    /**
     * Get colors from FlowDino
     */
    public function get_colors() {
        if (empty($this->token)) {
            return false;
        }
        
        // Get default country ISO (use WooCommerce base country)
        $country_iso = WC()->countries->get_base_country();
        
        $response = wp_remote_get($this->api_url . '/api/colors?country.isoCode=' . $country_iso, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            return false;
        }
        
        // Si le token est invalide, nettoyer les credentials
        if (wp_remote_retrieve_response_code($response) === 401) {
            update_option('flowdino_token', '');
            update_option('flowdino_email', '');
            update_option('flowdino_password', '');
            $this->token = '';
            return false;
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        // Retourner dans le même format que le module PrestaShop
        return array(
            'member' => isset($data) ? $data : array()
        );
    }
    
    /**
     * Get color names for a list of color IDs
     * Returns an associative array [color_id => color_name]
     */
    public function get_color_names_by_ids($color_ids) {
        if (empty($color_ids) || !is_array($color_ids)) {
            return array();
        }
        
        $color_names = array();
        
        // Récupérer toutes les couleurs et les filtrer
        $all_colors = $this->get_colors();
        if ($all_colors && isset($all_colors['member']) && is_array($all_colors['member'])) {
            foreach ($all_colors['member'] as $color) {
                if (isset($color['id'], $color['name']) && in_array($color['id'], $color_ids)) {
                    $color_names[$color['id']] = $color['name'];
                }
            }
        }
        
        return $color_names;
    }

    /**
     * Get materials from FlowDino
     */
    public function get_materials() {
        if (empty($this->token)) {
            return false;
        }
        
        // Get default country ISO (use WooCommerce base country)
        $country_iso = WC()->countries->get_base_country();
        
        $response = wp_remote_get($this->api_url . '/api/materials?country.isoCode=' . $country_iso, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            return false;
        }
        
        // Si le token est invalide, nettoyer les credentials
        if (wp_remote_retrieve_response_code($response) === 401) {
            update_option('flowdino_token', '');
            update_option('flowdino_email', '');
            update_option('flowdino_password', '');
            $this->token = '';
            return false;
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        // Retourner dans le même format que le module PrestaShop
        return array(
            'member' => isset($data) ? $data : array()
        );
    }
    
    /**
     * Get sizes from FlowDino
     */
    public function get_sizes() {
        if (empty($this->token)) {
            return false;
        }
        
        $response = wp_remote_get($this->api_url . '/api/sizes', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type' => 'application/json',
            ),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            return false;
        }
        
        // Si le token est invalide, nettoyer les credentials
        if (wp_remote_retrieve_response_code($response) === 401) {
            update_option('flowdino_token', '');
            update_option('flowdino_email', '');
            update_option('flowdino_password', '');
            $this->token = '';
            return false;
        }
        
        $body = wp_remote_retrieve_body($response);
        return json_decode($body, true);
    }

    /**
     * Get video game ratings from FlowDino
     */
    public function get_video_game_ratings() {
        if (empty($this->token)) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: get_video_game_ratings - no token available');
            return false;
        }

        $response = wp_remote_get($this->api_url . '/api/video_game_ratings', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type'  => 'application/json',
                'Accept'        => 'application/json',
            ),
            'timeout' => 30
        ));

        if (is_wp_error($response)) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: get_video_game_ratings WP_Error - ' . $response->get_error_message());
            return false;
        }

        $http_code = wp_remote_retrieve_response_code($response);

        // Si le token est invalide, nettoyer les credentials
        if ($http_code === 401) {
            update_option('flowdino_token', '');
            update_option('flowdino_email', '');
            update_option('flowdino_password', '');
            $this->token = '';
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: get_video_game_ratings - 401 Unauthorized, token cleared');
            return false;
        }

        if ($http_code !== 200) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: get_video_game_ratings - HTTP ' . $http_code);
            return false;
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (!$data) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: get_video_game_ratings - failed to decode JSON: ' . substr($body, 0, 200));
            return false;
        }

        // Supporter les deux formats : collection JSON-LD (member / hydra:member) et tableau plat
        $members = array();
        if (isset($data['member']) && is_array($data['member'])) {
            $members = $data['member'];
        } elseif (isset($data['hydra:member']) && is_array($data['hydra:member'])) {
            $members = $data['hydra:member'];
        } elseif (is_array($data) && isset($data[0])) {
            // Tableau plat directement
            $members = $data;
        }

        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
        error_log('FlowDino: get_video_game_ratings - found ' . count($members) . ' ratings');

        return array(
            'member' => $members
        );
    }

    /**
     * Get tags from FlowDino
     */
    public function get_tags() {
        if ( empty( $this->token ) ) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log( 'FlowDino: get_tags - no token available' );
            return false;
        }

        $response = wp_remote_get( $this->api_url . '/api/tags', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type'  => 'application/json',
                'Accept'        => 'application/json',
            ),
            'timeout' => 30,
        ) );

        if ( is_wp_error( $response ) ) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log( 'FlowDino: get_tags WP_Error - ' . $response->get_error_message() );
            return false;
        }

        $http_code = wp_remote_retrieve_response_code( $response );

        if ( $http_code === 401 ) {
            update_option( 'flowdino_token', '' );
            update_option( 'flowdino_email', '' );
            update_option( 'flowdino_password', '' );
            $this->token = '';
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log( 'FlowDino: get_tags - 401 Unauthorized, token cleared' );
            return false;
        }

        if ( $http_code !== 200 ) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log( 'FlowDino: get_tags - HTTP ' . $http_code );
            return false;
        }

        $body = wp_remote_retrieve_body( $response );
        $data = json_decode( $body, true );

        if ( ! $data ) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log( 'FlowDino: get_tags - failed to decode JSON: ' . substr( $body, 0, 200 ) );
            return false;
        }

        // Support flat array or hydra:member / member collections
        if ( isset( $data['member'] ) && is_array( $data['member'] ) ) {
            $tags = $data['member'];
        } elseif ( isset( $data['hydra:member'] ) && is_array( $data['hydra:member'] ) ) {
            $tags = $data['hydra:member'];
        } elseif ( is_array( $data ) && isset( $data[0] ) ) {
            $tags = $data;
        } else {
            $tags = array();
        }

        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
        error_log( 'FlowDino: get_tags - found ' . count( $tags ) . ' tags' );

        return $tags;
    }

    /**
     * Sync product to FlowDino
     */
    /**
     * Synchronise un produit avec l'API FlowDino (méthode compatible PrestaShop)
     */
    public function sync_product($product_data) {
        if (empty($this->token)) {
            $login_result = $this->login();
            if (!$login_result['success']) {
                return array(
                    'success' => false,
                    'message' => __('Connection failed: ', 'flowdino') . $login_result['message'],
                    'error_code' => 'AUTH_FAILED'
                );
            }
        }
        
        // Préparer les headers selon le format FlowDino
        $headers = array(
            'Authorization' => 'Bearer ' . $this->token,
            'Content-Type' => 'application/json',
            'Accept' => 'application/json'
        );
        
        $json_payload = json_encode($product_data);

        // Envoyer la requête POST à l'endpoint /api/products
        $response = wp_remote_post($this->api_url . '/api/products', array(
            'headers' => $headers,
            'body' => $json_payload,
            'timeout' => 60,
            'sslverify' => false // Pour éviter les problèmes SSL en dev
        ));
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => __('Network error: ', 'flowdino') . $response->get_error_message(),
                'error_code' => 'NETWORK_ERROR'
            );
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        switch ($response_code) {
            case 200:
            case 201:
                // Succès - produit créé ou mis à jour
                $is_created = ($response_code === 201);
                $status = $is_created ? 'created' : 'updated';
                
                return array(
                    'success' => true,
                    'message' => $is_created ? 
                        __('Product successfully created on FlowDino', 'flowdino') : 
                        __('Product successfully updated on FlowDino', 'flowdino'),
                    'status' => $status,
                    'data' => $data,
                    'product_id' => isset($data['id']) ? $data['id'] : null
                );
                
            case 400:
                // Erreur de validation ou limite atteinte
                if (isset($data['message']) && strpos($data['message'], 'LIMIT_REACHED') !== false) {
                    return array(
                        'success' => false,
                        'message' => __('Product limit reached on your FlowDino subscription', 'flowdino'),
                        'error_code' => 'LIMIT_REACHED',
                        'data' => $data
                    );
                }
                
                return array(
                    'success' => false,
                    'message' => isset($data['message']) ? $data['message'] : __('Validation error', 'flowdino'),
                    'error_code' => 'VALIDATION_ERROR',
                    'data' => $data
                );
                
            case 401:
                // Token invalide - nettoyer les credentials et forcer une nouvelle connexion
                update_option('flowdino_token', '');
                $this->token = '';
                
                return array(
                    'success' => false,
                    'message' => __('Authentication failed. Please check your credentials.', 'flowdino'),
                    'error_code' => 'AUTH_EXPIRED'
                );
                
            case 403:
                return array(
                    'success' => false,
                    'message' => __('Access forbidden. Check your FlowDino permissions.', 'flowdino'),
                    'error_code' => 'ACCESS_FORBIDDEN'
                );
                
            case 404:
                return array(
                    'success' => false,
                    'message' => __('FlowDino API endpoint not found', 'flowdino'),
                    'error_code' => 'ENDPOINT_NOT_FOUND'
                );
                
            case 500:
                return array(
                    'success' => false,
                    'message' => __('FlowDino server error. Please try again later.', 'flowdino'),
                    'error_code' => 'SERVER_ERROR',
                    'data' => $data
                );
                
            default:
                return array(
                    'success' => false,
                    /* translators: %d is the HTTP response code */
                    'message' => sprintf(__('Unexpected response code: %d', 'flowdino'), $response_code),
                    'error_code' => 'UNEXPECTED_RESPONSE',
                    'data' => $data
                );
        }
    }
    
    /**
     * Get product from FlowDino by SKU
     */
    public function get_product($sku) {
        if (empty($this->token) || empty($sku)) {
            return false;
        }
        
        $response = wp_remote_get($this->api_url . '/api/products/' . urlencode($sku), array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type' => 'application/json',
            ),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            return false;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code === 404) {
            return false; // Product not found
        }
        
        if ($response_code !== 200) {
            return false;
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        return $data;
    }
    
    /**
     * Create product in FlowDino
     */
    public function create_product($product_data) {
        if (empty($this->token)) {
            return false;
        }
        
        $response = wp_remote_post($this->api_url . '/api/products', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode($product_data),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            return false;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        return $response_code === 201 ? $data : false;
    }
    
    /**
     * Update product in FlowDino
     */
    public function update_product($sku, $product_data) {
        if (empty($this->token) || empty($sku)) {
            return false;
        }
        
        $response = wp_remote_request($this->api_url . '/api/products/' . urlencode($sku), array(
            'method' => 'PUT',
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode($product_data),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            return false;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        return $response_code === 200 ? $data : false;
    }
    
    /**
     * Get subscription info including remaining articles
     */
    public function get_subscription_info() {
        if (empty($this->token)) {
            return false;
        }
        
        $response = wp_remote_get($this->api_url . '/api/subscription/info', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type' => 'application/json',
            ),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            return false;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            return false;
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        return $data;
    }
    
    /**
     * Get products updated since a given date from FlowDino
     * Calls GET /api/products/updated-since?date=YYYY-MM-DD HH:MM:SS
     *
     * @param string $since_date MySQL-formatted datetime string (e.g. "2025-12-11 10:30:00")
     * @return array|false Array with 'success', 'data' (items array), 'message' keys or false on error
     */
    public function get_product_updates_since( $since_date ) {
        if ( empty( $this->token ) ) {
            $login_result = $this->login();
            if ( ! $login_result['success'] ) {
                return array(
                    'success' => false,
                    'message' => __( 'Connection failed: ', 'flowdino' ) . $login_result['message'],
                );
            }
        }

        $url = add_query_arg(
            array( 'date' => $since_date ),
            $this->api_url . '/api/products/updated-since'
        );

        $response = wp_remote_get( $url, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type'  => 'application/json',
                'Accept'        => 'application/json',
            ),
            'timeout'   => 60,
            'sslverify' => false,
        ) );

        if ( is_wp_error( $response ) ) {
            return array(
                'success' => false,
                'message' => __( 'Network error: ', 'flowdino' ) . $response->get_error_message(),
            );
        }

        $response_code = wp_remote_retrieve_response_code( $response );
        $body          = wp_remote_retrieve_body( $response );
        $data          = json_decode( $body, true );

        if ( $response_code === 401 ) {
            update_option( 'flowdino_token', '' );
            $this->token = '';
            return array(
                'success' => false,
                'message' => __( 'Authentication failed. Please check your credentials.', 'flowdino' ),
            );
        }

        if ( $response_code !== 200 ) {
            $api_message = '';
            if ( is_array( $data ) ) {
                if ( ! empty( $data['detail'] ) ) {
                    $api_message = ' — ' . $data['detail'];
                } elseif ( ! empty( $data['message'] ) ) {
                    $api_message = ' — ' . $data['message'];
                } elseif ( ! empty( $data['error'] ) ) {
                    $api_message = ' — ' . $data['error'];
                }
            }
            if ( empty( $api_message ) && ! empty( $body ) ) {
                $api_message = ' — ' . wp_strip_all_tags( $body );
            }
            return array(
                'success' => false,
                /* translators: %d is the HTTP response code, %s is the API error detail */
                'message' => sprintf( __( 'Unexpected response code: %d', 'flowdino' ), $response_code ) . $api_message
                    . ' [URL: ' . esc_url( $url ) . ']',
            );
        }

        // The API returns an object with an "items" key
        $items = array();
        if ( isset( $data['items'] ) && is_array( $data['items'] ) ) {
            $items = $data['items'];
        } elseif ( is_array( $data ) && isset( $data[0] ) ) {
            // Fallback: direct array of items
            $items = $data;
        }

        return array(
            'success' => true,
            'items'   => $items,
            'total'   => count( $items ),
        );
    }

    /**
     * Check if connected to API
     */
    public function is_connected() {
        return !empty($this->token);
    }
    
    /**
     * Delete product from FlowDino
     */
    public function delete_product($product_id) {
        if (empty($this->token)) {
            return false;
        }
        
        $response = wp_remote_request($this->api_url . '/api/products/' . $product_id, array(
            'method' => 'DELETE',
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type' => 'application/json',
            ),
            'timeout' => 30
        ));
        
        // Si le token est invalide, nettoyer les credentials
        if (wp_remote_retrieve_response_code($response) === 401) {
            update_option('flowdino_token', '');
            update_option('flowdino_email', '');
            update_option('flowdino_password', '');
            $this->token = '';
            return false;
        }
        
        return !is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200;
    }
    
    /**
     * Get token
     */
    public function get_token() {
        return $this->token;
    }
    
    /**
     * Check if token should be refreshed
     */
    public function should_refresh_token() {
        $last_refresh = get_option('flowdino_token_last_refresh', 0);
        return (time() - $last_refresh) > 3600; // Refresh every hour
    }
    
    /**
     * Log API responses for debugging
     */
    private function log_response($endpoint, $response, $response_code) {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log(sprintf(
                'FlowDino API - Endpoint: %s, Code: %d, Response: %s',
                $endpoint,
                $response_code,
                substr($response, 0, 500)
            ));
        }
    }
    
    /**
     * Debug method to test API connection with detailed output
     */
    public function debug_connection() {
        $debug_info = array();
        
        // Test basic connection
        $debug_info['api_url'] = $this->api_url;
        $debug_info['has_email'] = !empty($this->email);
        $debug_info['has_password'] = !empty($this->password);
        $debug_info['has_token'] = !empty($this->token);
        
        // Test login if no token
        if (empty($this->token) && !empty($this->email) && !empty($this->password)) {
            $debug_info['login_attempt'] = $this->login();
        }
        
        // Test token validation if we have one
        if (!empty($this->token)) {
            $response = wp_remote_get($this->api_url . '/api/categories/tree', array(
                'headers' => array(
                    'Authorization' => 'Bearer ' . $this->token,
                    'Content-Type' => 'application/json',
                ),
                'timeout' => 30
            ));
            
            $debug_info['token_test'] = array(
                'response_code' => wp_remote_retrieve_response_code($response),
                'response_body' => wp_remote_retrieve_body($response)
            );
        }
        
        return $debug_info;
    }
    
    /**
     * Prepare product data for FlowDino sync
     * @param WC_Product $product
     * @return array Product data formatted for FlowDino API
     */
    public function prepare_product_data($product) {
        if (!$product instanceof WC_Product) {
            return false;
        }
        
        $database = new FlowDino_WC_Database();
        
        // Get FlowDino category ID for this product
        $flowdino_category_id = $database->get_flowdino_category_for_product($product->get_id());
        
        $product_data = array(
            'name' => $product->get_name(),
            'description' => $product->get_description(),
            'short_description' => $product->get_short_description(),
            'sku' => $product->get_sku(),
            'price' => $product->get_regular_price(),
            'sale_price' => $product->get_sale_price(),
            'weight' => $product->get_weight(),
            'length' => $product->get_length(),
            'width' => $product->get_width(),
            'height' => $product->get_height(),
            'status' => $product->get_status(),
            'stock_status' => $product->get_stock_status(),
            'manage_stock' => $product->get_manage_stock(),
            'stock_quantity' => $product->get_stock_quantity(),
            'woocommerce_id' => $product->get_id(),
        );
        
        // Add category ID if mapping exists
        if ($flowdino_category_id) {
            $product_data['category_id'] = $flowdino_category_id;
        }
        
        // Add product images
        $images = array();
        $image_id = $product->get_image_id();
        if ($image_id) {
            $image_url = wp_get_attachment_image_url($image_id, 'full');
            if ($image_url) {
                $images[] = $image_url;
            }
        }
        
        $gallery_ids = $product->get_gallery_image_ids();
        foreach ($gallery_ids as $gallery_id) {
            $gallery_url = wp_get_attachment_image_url($gallery_id, 'full');
            if ($gallery_url) {
                $images[] = $gallery_url;
            }
        }
        
        if (!empty($images)) {
            $product_data['images'] = $images;
        }
        
        return $product_data;
    }
    
    /**
     * Sync WooCommerce product to FlowDino
     * @param WC_Product|int $product Product object or product ID
     * @return array
     */
    public function sync_wc_product($product) {
        if (is_numeric($product)) {
            $product = wc_get_product($product);
        }
        
        if (!$product instanceof WC_Product) {
            return array(
                'success' => false,
                'message' => __('Invalid product', 'flowdino')
            );
        }
        
        // Prepare product data with FlowDino category mapping
        $product_data = $this->prepare_product_data($product);
        
        if (!$product_data) {
            return array(
                'success' => false,
                'message' => __('Failed to prepare product data', 'flowdino')
            );
        }
        
        // Check if product has a FlowDino category mapping
        if (!isset($product_data['category_id'])) {
            return array(
                'success' => false,
                'message' => __('No FlowDino category mapping found for this product', 'flowdino')
            );
        }
        
        // Sync using the regular sync_product method
        return $this->sync_product($product_data);
    }
    
    /**
     * Debug category mapping for a product
     * @param int $product_id
     * @return array Debug information
     */
    public function debug_product_category_mapping($product_id) {
        $database = new FlowDino_WC_Database();
        $product = wc_get_product($product_id);
        
        $debug_info = array();
        $debug_info['product_id'] = $product_id;
        $debug_info['product_exists'] = $product ? true : false;
        
        if (!$product) {
            return $debug_info;
        }
        
        $debug_info['product_name'] = $product->get_name();
        $debug_info['wc_category_ids'] = $product->get_category_ids();
        
        // Get category names
        $category_names = array();
        foreach ($product->get_category_ids() as $cat_id) {
            $term = get_term($cat_id, 'product_cat');
            if ($term && !is_wp_error($term)) {
                $category_names[$cat_id] = $term->name;
            }
        }
        $debug_info['wc_category_names'] = $category_names;
        
        // Check direct mappings
        $direct_mappings = array();
        foreach ($product->get_category_ids() as $cat_id) {
            $flowdino_id = $database->get_category_mapping($cat_id);
            if ($flowdino_id) {
                $direct_mappings[$cat_id] = $flowdino_id;
            }
        }
        $debug_info['direct_mappings'] = $direct_mappings;
        
        // Get final FlowDino category ID
        $debug_info['final_flowdino_category_id'] = $database->get_flowdino_category_for_product($product_id);
        
        // Get all mappings for reference
        $debug_info['all_mappings'] = $database->get_all_category_mappings();
        
        return $debug_info;
    }

    // =========================================================================
    // SALES — USER SITES
    // =========================================================================

    /**
     * Retrieve the list of platforms (sites) for the authenticated user.
     *
     * GET /api/user-sites
     *
     * @return array|false  Decoded response array or false on failure.
     */
    public function get_user_sites() {
        if (empty($this->token)) {
            return false;
        }

        $response = wp_remote_get($this->api_url . '/api/user-sites', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type'  => 'application/json',
            ),
            'timeout' => 30,
        ));

        if (is_wp_error($response)) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            error_log('FlowDino: get_user_sites error — ' . $response->get_error_message());
            return false;
        }

        $code = wp_remote_retrieve_response_code($response);

        if ($code === 401) {
            update_option('flowdino_token', '');
            $this->token = '';
            return false;
        }

        if ($code !== 200) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            error_log('FlowDino: get_user_sites HTTP ' . $code);
            return false;
        }

        $body = wp_remote_retrieve_body($response);
        return json_decode($body, true);
    }

    // =========================================================================
    // SALES — ORDERS
    // =========================================================================

    /**
     * Retrieve a page of orders for a given platform.
     *
     * GET /api/orders?siteSell={id}&sortBy=updatedAt&sortOrder=ASC
     *                &page={p}&limit={l}&updatedFrom={date}
     *
     * @param int    $site_id     FlowDino platform ID.
     * @param string $from_date   ISO 8601 / MySQL datetime string.
     * @param int    $page        1-based page number.
     * @param int    $limit       Items per page (default 100).
     *
     * @return array|false  Decoded response array or false on failure.
     */
    public function get_orders($site_id, $from_date = '', $page = 1, $limit = 100) {
        if (empty($this->token)) {
            return false;
        }

        $query = array(
            'siteSell'   => (int) $site_id,
            'sortBy'     => 'updatedAt',
            'sortOrder'  => 'ASC',
            'page'       => (int) $page,
            'limit'      => (int) $limit,
        );

        if (!empty($from_date)) {
            $query['updatedFrom'] = $from_date;
        }

        $url = $this->api_url . '/api/orders?' . http_build_query($query);

        $response = wp_remote_get($url, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->token,
                'Content-Type'  => 'application/json',
            ),
            'timeout' => 60,
        ));

        if (is_wp_error($response)) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            error_log('FlowDino: get_orders error — ' . $response->get_error_message());
            return false;
        }

        $code = wp_remote_retrieve_response_code($response);

        if ($code === 401) {
            update_option('flowdino_token', '');
            $this->token = '';
            return false;
        }

        if ($code !== 200) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            error_log('FlowDino: get_orders HTTP ' . $code . ' for site ' . $site_id);
            return false;
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (empty($data['success'])) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            error_log('FlowDino: get_orders success=false for site ' . $site_id);
            return false;
        }

        return $data;
    }
}



