<?php

namespace Meliconnect\Meliconnect\Modules\Exporter\Services;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

use Meliconnect\Meliconnect\Core\Helpers\Helper;
use Meliconnect\Meliconnect\Core\Helpers\MeliconMeli;
use Meliconnect\Meliconnect\Core\Models\Template;
use Meliconnect\Meliconnect\Core\Models\UserConnection;

/**
 * Handles communication with the external server to processs and get raw listing data
 * to send to Mercado Libre API.
 */
class MercadoLibreListingAdapter {

	protected $apiEndpoint;
    protected $settings;

    protected $attribute_synonyms = [

        'marca' => [
            'marca',
            'brand',
            'fabricante',
            'maker',
            'manufacturer',
            'marca del producto',
            'marca fabricante',
            'marca do produto',       // PT
        ],

        'modelo' => [
            'modelo',
            'model',
            'modelo del producto',
            'modelo do produto',      // PT
            'referencia',
            'ref',
        ],

        'color' => [
            'color',
            'colour',
            'cor',                   // PT
            'color principal',
            'color del producto',
        ],

        'talle' => [
            'talle',
            'tamaño',
            'size',
            'size name',
            'talla',
            'medida',
            'tamano',                // sin acento
            'tamanho',               // PT
        ],

        'material' => [
            'material',
            'materia',
            'material principal',
            'material do produto',   // PT
        ],

        'genero' => [
            'genero',
            'género',
            'gender',
            'sexo',
            'genero del producto',
            'gênero',               // PT
        ],

        'peso' => [
            'peso',
            'weight',
            'peso del producto',
            'peso do produto',      // PT
        ],

        'dimensiones' => [
            'dimensiones',
            'dimensions',
            'tamaño del producto',
            'medidas',
            'medidas del producto',
            'dimensoes',            // PT
            'dimensões',            // PT con acento
        ],

        'capacidad' => [
            'capacidad',
            'capacity',
            'volumen',
            'volume',
            'capacidad del producto',
            'capacidade',           // PT
        ],

        'linea' => [
            'linea',
            'línea',
            'line',
            'linha',                // PT
        ],

    ];

	public function __construct() {

			$this->apiEndpoint = 'https://meliconnect.com/api/v1/process-listing-data-to-export';
            $this->settings = Helper::getMeliconnectOptions('export');

	}

	public function getTransformedListingData( $meli_user_data, $woo_product_id, $template_id, $meliListingId = null, $sync_options = null ) {
        
        if (empty($template_id)) {
            $saved_template_id = get_post_meta($woo_product_id, 'meliconnect_asoc_template_id', true);

            if (!empty($saved_template_id)) {
                $template_id = $saved_template_id;
            }
        }

        $template_id = $this->resolveOrCreateTemplate($woo_product_id, $meli_user_data, $template_id);

        Helper::logData('Template resolved', 'custom-export');
        Helper::logData([
            'woo_product_id' => $woo_product_id,
            'template_id'    => $template_id,
        ], 'custom-export');

        //$this->ensureRequiredAttributes($template_id, $meli_user_data);

		$rawData = array(
			'extra_data'      => array(
				'meli_user_id'   => $meli_user_data->user_id,
				'woo_product_id' => $woo_product_id,
				'template_id'    => $template_id,
				'meliListingId'  => $meliListingId,
				'domain'         => Helper::getDomainName(),
			),
			'meli_user'       => $meli_user_data,
			'export_settings' => $this->settings,
			'meli_listing'    => MeliconMeli::getMercadoLibreListingData( $meliListingId, $meli_user_data->access_token ),
			'woo_product'     => $this->getWooProductData( $woo_product_id ),
			'template'        => $this->getMeliconTemplateData( $template_id ),
			'sync_options'    => $sync_options,
		);

		//Helper::logData('Raw data sent to hub: ' . wp_json_encode($rawData), 'custom-export');
		update_post_meta( $woo_product_id, 'meliconnect_last_export_json_sent', $rawData );


		// Enviar datos sin procesar al servidor y recibir datos transformados
		$server_response = $this->sendDataToServer( $rawData );


		//Helper::logData( 'Server response:' . $server_response, 'custom-export' );

		return json_decode( $server_response, true );
	}


        
    protected function resolveDefaultAttributeValue($attr)
    {
        if ($attr['id'] === 'BRAND') {
            return ['id' => null, 'name' => 'Genérica'];
        }

        if ($attr['id'] === 'MODEL') {
            return ['id' => null, 'name' => 'Modelo genérico'];
        }

        if (!empty($attr['values'])) {
            return [
                'id'   => $attr['values'][0]['id'] ?? null,
                'name' => $attr['values'][0]['name'] ?? null,
            ];
        }

        return [
            'id'   => null,
            'name' => null,
        ];
    }

    protected function resolveOrCreateTemplate($woo_product_id, $meli_user_data, $template_id)
    {
        //Helper::logData('Resolving template...', 'custom-export');
        //Helper::logData(['woo_product_id' => $woo_product_id, 'incoming_template_id' => $template_id,], 'custom-export');

        // Si ya tiene template válido → usarlo
        if (!empty($template_id)) {
            $existing = Template::getTemplateData($template_id);
            
            if (!empty($existing)) {
                Helper::logData('Template found and reused', 'custom-export');
                Helper::logData(['template_id' => $template_id], 'custom-export');
                
                return $template_id;
            }
        }

        // 1. Obtener producto
        $product = wc_get_product($woo_product_id);
        if (!$product) {
            return null;
        }

        // 2. Detectar categoría ML automáticamente
        $category = $this->detectMeliCategory($product->get_name(),$meli_user_data);
        $category_id = $category['category_id'] ?? null;

        if (!$category_id) {

            Helper::logData('No category detected for new template. Using fallback', 'custom-export');
            Helper::logData(['category_id' => 'MLA3530'], 'custom-export');
            
            $category_id = 'MLA3530';
        }

        //Helper::logData('Category detected', 'custom-export');
        //Helper::logData(['category_id' => $category_id], 'custom-export');

        // 3. Crear template automático
        $data = [
            'used_by'        => 'product',
            'used_asoc_id'   => $woo_product_id,
            'seller_meli_id' => $meli_user_data->user_id,
            'name'           => $product->get_name(),
            'category_id'    => $category_id,
            'category_name'  => $category['category_name'] ?? null,
            'category_path'  => "",
            'status'         => 1,
        ];

        //Helper::logData('Creating new template...', 'custom-export');
        //Helper::logData(['data' => $data], 'custom-export');

        $new_template_id = Template::createUpdateTemplate($data);

        //Helper::logData('Template created', 'custom-export');
        //Helper::logData(['template_id' => $new_template_id], 'custom-export');

        update_post_meta($woo_product_id, 'meliconnect_asoc_template_id', $new_template_id);

        if (!$new_template_id) {
            return null;
        }

        // 4. Armar metas dinámicas
        $template_metas = $this->buildTemplateMetas($meli_user_data, $category);

        //Helper::logData('Creating template metas...', 'custom-export');
        //Helper::logData($template_metas, 'custom-export');

        // 5. Crear metas
        // 5.1. Guardar metas de ML (IMPORTANTISIMO)
        $this->saveListingMetas($new_template_id, $template_metas);

        // 5.2. Crear metas custom (defaults)
        Template::createCustomTemplateMetas($new_template_id, []);

        $category_attrs = MeliconMeli::getWithHeader(
            'categories/' . $category_id . '/attributes',
            $meli_user_data->access_token
        );

        $category_attrs = json_decode(json_encode($category_attrs), true);

        /* Helper::logData('Category attrs', 'custom-export');
        Helper::logData(var_export($category_attrs,true), 'custom-export'); */

       if (
            !empty($category_attrs['httpCode']) &&
            (int) $category_attrs['httpCode'] === 200 &&
            !empty($category_attrs['body']) &&
            is_array($category_attrs['body'])
        ) {

            $relevant_attrs    = [];
            $allows_variations = false;

            foreach ($category_attrs['body'] as $attr) {

                $tags = $attr['tags'] ?? [];

                // detectar si permite variaciones (lo hacemos SIEMPRE)
                if (!$allows_variations && !empty($tags['allow_variations'])) {
                    $allows_variations = true;
                }

                // filtrar atributos relevantes
                if (!empty($tags['hidden']) || !empty($tags['read_only'])) {
                    continue;
                }

                if (!empty($tags['required']) || !empty($tags['catalog_required'])) {
                    $relevant_attrs[] = $attr;
                }
            }

            //Helper::logData('Relevant attrs', 'custom-export');
            //Helper::logData($relevant_attrs, 'custom-export');

            $this->createAttributesFromCategory(
                $new_template_id,
                $woo_product_id,
                $relevant_attrs
            );

            Template::upsertTemplateMeta(
                $new_template_id,
                'meliconnect_allows_variations',
                $allows_variations ? 1 : 0
            );
        }

      

        return $new_template_id;
    }

    

    protected function createAttributesFromCategory($template_id, $woo_product_id, $required_attrs)
    {
        $useGenericAttributes = isset($this->settings['meliconnect_export_use_generic_attributes']) && $this->settings['meliconnect_export_use_generic_attributes'] === 'true';

        foreach ($required_attrs as $attr) {
            
            $woo_value = $this->resolveWooAttributeValue($woo_product_id, $attr);

            if ($woo_value) {
                $default = $woo_value;

                Helper::logData('Attribute matched from Woo', 'custom-export');

            } else {
                 if ($useGenericAttributes) {

                    $default = $this->resolveDefaultAttributeValue($attr);

                    Helper::logData('Using generic fallback value', 'custom-export');

                } else {

                    Helper::logData([
                        'Attribute skipped (no match and use generic values are disabled)',
                        'meli_attribute_id' => $attr['id'],
                        'required' => !empty($attr['tags']['required'])
                    ], 'custom-export');

                    continue;
                }
                
            }
            
            Helper::logData([
                'meli_attribute_id' => $attr['id'],
                'value' => $default
            ], 'custom-export');

            $data = [
                'template_id'             => $template_id,
                'used_by'                 => 'product',
                'used_asoc_id'            => $woo_product_id,
                'meli_attribute_id'       => $attr['id'],
                'meli_attribute_name'     => $attr['name'],
                'meli_value_type'         => $attr['value_type'],
                'woo_attribute_id'        => '',
                'product_parent_id'       => 0,
                'allow_variations_tag'    => !empty($attr['tags']['allow_variations']) ? 1 : 0,
                'variation_attribute_tag' => !empty($attr['tags']['variation_attribute']) ? 1 : 0,
                'required_tag'            => !empty($attr['tags']['required']) ? 1 : 0,
                'meli_value_id'           => $default['id'] ?? null,
                'meli_value_name'         => $default['name'] ?? (is_string($default) ? $default : null),
            ];

            Template::createUpdateTemplateAttributes(
                'product',
                $woo_product_id,
                $attr['id'],
                $data
            );

            Helper::logData('Creating attribute', 'custom-export');
            Helper::logData([
                'meli_attribute_id' => $attr['id'],
                'default' => $default
            ], 'custom-export');
        }
    }

    protected function resolveWooAttributeValue($woo_product_id, $meli_attr)
    {
        //Helper::logData('--- PRO Attribute Matching ---', 'custom-export');

        $product = wc_get_product($woo_product_id);

        if (!$product) {
            //Helper::logData('Product not found', 'custom-export');
            return null;
        }

        /**
         * 🔥 Si es variación, también traer atributos del padre
         */
        $woo_attributes = $product->get_attributes();

        if ($product->is_type('variation')) {
            $parent = wc_get_product($product->get_parent_id());

            if ($parent) {
                $woo_attributes = array_merge(
                    $parent->get_attributes(),
                    $woo_attributes
                );
            }
        }

        $meli_name  = $this->normalize($meli_attr['name']);
        $meli_id    = strtoupper($meli_attr['id'] ?? '');
        $meli_group = $this->getSynonymGroup($meli_name);

        $best_match = null;
        $best_score = 0;

        // =========================
        // 1. MATCH CONTRA ATRIBUTOS WOO
        // =========================
        foreach ($woo_attributes as $key => $attribute) {

            $woo_name = null;

            /**
             * ✔ Caso 1: atributo estándar
             */
            if (is_object($attribute) && method_exists($attribute, 'get_name')) {

                $woo_name = wc_attribute_label($attribute->get_name());
            }

            /**
             * ✔ Caso 2: variación (attribute_pa_color)
             */
            elseif (is_string($key)) {

                $woo_name = str_replace('attribute_', '', $key);
                $woo_name = str_replace('pa_', '', $woo_name);
            }

            if (!$woo_name) {
                continue;
            }

            $woo_name = $this->normalize($woo_name);

            $score = $this->scoreAttributeMatch($meli_name, $woo_name);

            $woo_group = $this->getSynonymGroup($woo_name);

            if ($meli_group && $woo_group && $meli_group === $woo_group) {
                $score += 5;
            }

            //Helper::logData(['meli'  => $meli_name,'woo'   => $woo_name,'score' => $score], 'custom-export');

            if ($score > $best_score) {
                $best_score = $score;
                $best_match = [
                    'attribute' => $attribute,
                    'key'       => $key
                ];
            }
        }

        /**
         * ✔ MATCH ENCONTRADO
         */
        if ($best_score >= 3 && $best_match) {

            //Helper::logData([ 'BEST MATCH FOUND','score' => $best_score], 'custom-export');

            $attribute = $best_match['attribute'];
            $key       = $best_match['key'];

            /**
             * 🔥 Caso 1: objeto (producto normal)
             */
            if (is_object($attribute) && method_exists($attribute, 'get_name')) {
                return $this->extractWooAttributeValue($attribute, $woo_product_id);
            }

            /**
             * 🔥 Caso 2: variación (key => value)
             */
            if (is_string($key)) {

                $variation_attributes = $product->get_attributes();

                if (isset($variation_attributes[$key])) {

                    $value = $variation_attributes[$key];

                    if (!empty($value)) {

                        return [
                            'id'     => null,
                            'name'   => $value,
                            'struct' => null
                        ];
                    }
                }
            }
        }

        // =========================
        // 2. FALLBACK DIMENSIONES
        // =========================
        //Helper::logData('No attribute match, trying dimensions...', 'custom-export');

        $dimension_attrs = ['WIDTH', 'HEIGHT', 'DEPTH', 'LENGTH', 'MAX_HEIGHT'];

        if (in_array($meli_id, $dimension_attrs)) {

            $length = $product->get_length();
            $width  = $product->get_width();
            $height = $product->get_height();

            //Helper::logData(['length' => $length,'width'  => $width,'height' => $height,'meli_attr_id' => $meli_id], 'custom-export');

            $value = null;

            switch ($meli_id) {
                case 'WIDTH':
                    $value = $width;
                    break;

                case 'HEIGHT':
                case 'MAX_HEIGHT':
                    $value = $height;
                    break;

                case 'DEPTH':
                case 'LENGTH':
                    $value = $length;
                    break;
            }

            if (!empty($value)) {

                $unit = get_option('woocommerce_dimension_unit', 'cm');
                $unit = strtolower($unit);

                $unit_map = [
                    'cm' => 'cm',
                    'm'  => 'm',
                    'mm' => 'mm',
                    'in' => 'in',
                ];

                $unit = $unit_map[$unit] ?? 'cm';

                return [
                    'id'   => null,
                    'name' => $value . ' ' . $unit,
                    'struct' => [
                        'number' => (float) $value,
                        'unit'   => strtoupper($unit),
                    ]
                ];
            }
        }

        //Helper::logData('No match found at all', 'custom-export');

        return null;
    }

    protected function scoreAttributeMatch($meli_name, $woo_name)
    {
        $meli_tokens = explode(' ', $meli_name);
        $woo_tokens  = explode(' ', $woo_name);

        $score = 0;

        foreach ($meli_tokens as $mt) {
            foreach ($woo_tokens as $wt) {

                // match exacto
                if ($mt === $wt) {
                    $score += 3;
                }

                // match parcial
                elseif (strpos($wt, $mt) !== false || strpos($mt, $wt) !== false) {
                    $score += 1;
                }
            }
        }

        return $score;
    }

    protected function getSynonymGroup($name)
    {
        foreach ($this->attribute_synonyms as $group => $synonyms) {

            $normalized_synonyms = array_map([$this, 'normalize'], $synonyms);

            if (in_array($name, $normalized_synonyms)) {
                return $group;
            }
        }

        return null;
    }

    protected function normalize($string)
    {
        return strtolower(remove_accents(trim($string)));
    }

    protected function extractWooAttributeValue($attribute, $woo_product_id)
    {
        if ($attribute->is_taxonomy()) {

            $terms = wc_get_product_terms(
                $woo_product_id,
                $attribute->get_name(),
                ['fields' => 'names']
            );

            if (!empty($terms)) {
                return [
                    'id'   => null,
                    'name' => $terms[0],
                ];
            }

        } else {

            $options = $attribute->get_options();

            if (!empty($options)) {
                return [
                    'id'   => null,
                    'name' => $options[0],
                ];
            }
        }

        return null;
    }

    protected function saveListingMetas($template_id, $metas)
    {
        foreach ($metas as $key => $value) {
            Template::upsertTemplateMeta($template_id, $key, $value);
        }
    }

    protected function buildTemplateMetas($meli_user_data, $category)
    {
        
        $meli_countries = [
            "MCR" => "CRC",
            "MLA" => "ARS",
            "MLM" => "MXN",
            "MLV" => "VES",
            "MPY" => "PYG",
            "MLC" => "CLP",
            "MLU" => "UYU",
            "MPA" => "PAB",
            "MRD" => "DOP",
            "MCU" => "CUP",
            "MPE" => "PEN",
            "MCO" => "COP",
            "MLB" => "BRL",
            "MHN" => "HNL",
            "MEC" => "USD",
            "MBO" => "BOB",
            "MSV" => "USD",
            "MNI" => "NIO",
            "MGT" => "GTQ",
        ];

        $siteId = $meli_user_data->site_id ?? 'MLA';

        $currency = $meli_countries[$siteId] ?? 'USD';


        return [
            'currency_id'     => $currency,
            'domain_id'       => $category['domain_id'] ?? null,
            'catalog_domain'  => $category['domain_id'] ?? null, 
            'listing_type_id' => 'gold_special',
            'buying_mode'     => 'buy_it_now',
            'condition'       => 'new',
        ];
    }

    /* protected function getDomainFromCategory($category_id, $meli_user_data)
    {
        Helper::logData('Getting domain from category ', 'custom-export');
        $meli_category_data =  MeliconMeli::simpleGet( 'https://api.mercadolibre.com/categories/' . $category_id, ['access_token' => $meli_user_data->access_token] );


        Helper::logData($meli_category_data, 'custom-export');
        return $meli_category_data['settings']['catalog_domain'] ?? null;
    } */

    protected function detectMeliCategory($query, $meli_user_data)
    {
        $site_id = $meli_user_data->site_id ?? 'MLA';

        $url = 'https://api.mercadolibre.com/sites/' . $site_id . '/domain_discovery/search?q=' . urlencode($query);

        Helper::logData('Calling ML domain_discovery', 'custom-export');
        Helper::logData(['url' => $url], 'custom-export');

        $response = wp_remote_get($url);

        if (is_wp_error($response)) {
            Helper::logData('ML request error', 'custom-export');
            Helper::logData($response->get_error_message(), 'custom-export');
            return null;
        }

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

        /* Helper::logData('ML response', 'custom-export');
        Helper::logData($body, 'custom-export'); */

        if (!is_array($body) || empty($body[0]['category_id'])) {
            return null;
        }

        return $body[0] ?? null;
    }

	public function getMeliconTemplateData( $template_id ) {
		$template['data'] = Template::getTemplateData( $template_id );

		if ( empty( $template['data'] ) ) {
			return null;
		}
		$template['attributes'] = Template::getTemplateAttributes( $template_id );
		return $template;
	}

	public function getWooProductData( $woo_product_id ) {
		$product = wc_get_product( $woo_product_id );
		if ( ! $product ) {
			return null;
		}

		$product_meta = $this->getWooProductMeta( $woo_product_id );

		// Obtener la URL y los metadatos de la imagen principal
		$image_id   = $product->get_image_id();
		$image_data = $this->getImageData( $image_id );

		// Obtener las URLs y los metadatos de la galería de imágenes
		$gallery_image_ids = $product->get_gallery_image_ids();
		$gallery_images    = array();
		foreach ( $gallery_image_ids as $gallery_image_id ) {
			$gallery_images[] = $this->getImageData( $gallery_image_id );
		}

		$product_data = array(
			'data' => array(
				'id'                 => $product->get_id(),
				'name'               => $this->sanitizeText($product->get_name()),
				'price'              => $product->get_price(),
				'regular_price'      => $product->get_regular_price(),
				'sale_price'         => $product->get_sale_price(),
				'sku'                => $product->get_sku(),
				'description'        => $this->sanitizeText($product->get_description()),
                'short_description'  => $this->sanitizeText($product->get_short_description()),
				'status'             => $product->get_status(),
				'date_created'       => $product->get_date_created(),
				'date_modified'      => $product->get_date_modified(),
				'stock_quantity'     => $product->get_stock_quantity(),
				'stock_status'       => $product->get_stock_status(),
				'weight'             => $product->get_weight(),
				'dimensions'         => $product->get_dimensions( false ),
				'shipping_class'     => $product->get_shipping_class(),
				'image'              => $image_data,
				'gallery_images'     => $gallery_images,
				'category_ids'       => $product->get_category_ids(),
				'tag_ids'            => $product->get_tag_ids(),
				'total_sales'        => $product->get_total_sales(),
				'manage_stock'       => $product->get_manage_stock(),
				'type'               => $product->get_type(),
				'catalog_visibility' => $product->get_catalog_visibility(),
			),
			'meta' => $product_meta,
		);

		if ( $product->is_type( 'variable' ) ) {
			$variations    = array();
			$variation_ids = $product->get_children();

			foreach ( $variation_ids as $variation_id ) {
				$variation      = wc_get_product( $variation_id );
				$variation_meta = $this->getWooProductMeta( $variation_id );

				// Obtener la URL y los metadatos de la imagen de la variación
				$variation_image_id   = $variation->get_image_id();
				$variation_image_data = $this->getImageData( $variation_image_id );

				$variations[] = array(
					'variations_data' => array(
						'id'                => $variation->get_id(),
						'price'             => $variation->get_price(),
						'regular_price'     => $variation->get_regular_price(),
						'sale_price'        => $variation->get_sale_price(),
						'sku'               => $variation->get_sku(),
						'stock_status'      => $variation->get_stock_status(),
						'attributes'        => $variation->get_attributes(),
						'weight'            => $variation->get_weight(),
						'dimensions'        => $variation->get_dimensions( false ),
						'shipping_class_id' => $variation->get_shipping_class_id(),
						'image'             => $variation_image_data,
					),
					'variations_meta' => $variation_meta,
				);
			}

			$product_data['variations'] = $variations;
		}

		return $product_data;
	}

    private function sanitizeText($text)
    {
        if (empty($text)) return '';

        // Decode HTML entities
        $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');

        // Remove HTML
        $text = str_replace(['</p>', '</li>', '<br>', '<br/>'], "\n", $text);
        
        $text = wp_strip_all_tags($text);

        // Remove emojis (más completo)
        $text = preg_replace('/[\x{1F000}-\x{1FFFF}]/u', '', $text);

        // Replace problematic chars
        $replace = [
            '–' => '-',
            '—' => '-',
            '•' => '-',
            "\t" => ' ',
        ];
        $text = str_replace(array_keys($replace), array_values($replace), $text);

        // Normalize line breaks
        $text = str_replace(["\r\n", "\r"], "\n", $text);

        // Clean excessive line breaks
        $text = preg_replace("/\n{3,}/", "\n\n", $text);

        // Trim + limitar largo (ML safe)
        $text = trim($text);
        $text = mb_substr($text, 0, 5000);

        return $text;
    }

	private function getWooProductMeta( $product_id ) {
		$meta_data   = array();
		$meta_fields = get_post_meta( $product_id );

		$metas_to_send = array(
			'meliconnect_meli_listing_id',
            'meliconnect_meli_user_product_id',
			'meliconnect_meli_seller_id',
			'meliconnect_meli_permalink',
			'meliconnect_meli_listing_type_id',
			'meliconnect_meli_category_id',
			'meliconnect_meli_status',
			'meliconnect_meli_sub_status',
			'meliconnect_meli_site_id',
			'meliconnect_meli_catalog_product_id',
			'meliconnect_meli_domain_id',
			'meliconnect_asoc_template_id',
			'meliconnect_last_export_time',
			'meliconnect_meli_channels',
			'meliconnect_meli_sold_quantity',
			'meliconnect_meli_shipping_mode',
			'meliconnect_meli_shipping_logistic_type',
			'meliconnect_meli_shipping_has_free_shipping',
			'total_sales',
			'_thumbnail_id',
			'_manage_stock',
			'_sold_individually',
			'_stock',
			'_stock_status',
			'_product_image_gallery',
			'_price',
			'_sale_price',
			'_regular_price',
			'_product_attributes',
		);

		foreach ( $meta_fields as $key => $value ) {
			if ( ! in_array( $key, $metas_to_send ) ) {
				continue;
			}
			$meta_data[ $key ] = maybe_unserialize( $value[0] );
		}

		return $meta_data;
	}

	private function getImageData( $woo_image_id ) {
		if ( ! $woo_image_id ) {
			return null;
		}

		$image_url = wp_get_attachment_url( $woo_image_id );

		// Obtiene el ID de MercadoLibre asociado desde los meta datos de la imagen en WooCommerce
		$ml_image_id        = get_post_meta( $woo_image_id, 'meliconnect_meli_image_id', true );
		$ml_image_seller_id = get_post_meta( $woo_image_id, 'meliconnect_meli_image_seller_id', true );
		$ml_image_url       = get_post_meta( $woo_image_id, 'meliconnect_meli_image_url', true );

        $access_token = UserConnection::get_meli_access_token_by_seller( $ml_image_seller_id );

		// Si existe un ID de MercadoLibre, verifica que la imagen exista en MercadoLibre
		if ( ! empty( $ml_image_id ) ) {
			$ml_image_data = MeliconMeli::getMeliImageData( $ml_image_id, $access_token );

			if ( isset( $ml_image_data['id'] ) && ! empty( $ml_image_data['id'] ) ) {
				$ml_image_id = $ml_image_data['id'];
			}
		}

		// Si no hay un ID de MercadoLibre o la imagen no existe en MercadoLibre, sube la imagen
		/*
		if (empty($ml_image_id)) {
			$acces_token = '';
			$ml_image_id = MeliconMeli::uploadPictureToMeli($woo_image_id, $acces_token);
		} */

		return array(
			'woo_id'             => $woo_image_id,
			'ml_image_id'        => ! empty( $ml_image_id ) ? $ml_image_id : null,
			'ml_image_url'       => ! empty( $ml_image_url ) ? $ml_image_url : null,
			'ml_image_seller_id' => ! empty( $ml_image_seller_id ) ? $ml_image_seller_id : null,
			'url'                => $image_url,
		);
	}



	private function sendDataToServer( array $productData ) {
		$response = wp_remote_post(
			$this->apiEndpoint,
			array(
				'method'  => 'POST',
				'body'    => wp_json_encode( $productData ),
				'headers' => array(
					'Content-Type' => 'application/json',
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			// Manejo de error en la conexión
			return false;
		}

		$body = wp_remote_retrieve_body( $response );

		if ( isset( $body['data'] ) && ! empty( $body['data'] ) ) {
			return $body['data'];
		}

		return $body;
	}
}
