<?php

namespace Meliconnect\Meliconnect\Modules\Importer\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;

/**
 * Provides functionality to create or update products in WooCommerce
 * using transformed product data.
 */
class WooCommerceProductCreationService
{

    public function createProduct($productsData, $meliListingData)
    {
        $woo_products_ids = array();
        $woo_product      = false;
        $import_settings  = Helper::getMeliconnectOptions('import');

        foreach ($productsData as $product_data) {
            Helper::logData('-------------- START Processing product: ' . $product_data['title'] . '---------------- ', 'custom-import');

            //Helper::logData('Received product data: ' . wp_json_encode($product_data), 'custom-import');
            //Helper::logData('Received meliListing data: ' . wp_json_encode($meliListingData), 'custom-import');

            if (isset($product_data['woo_product_id']) && $product_data['action'] === 'update') {
                $woo_product = wc_get_product($product_data['woo_product_id']);
            }

            if ($woo_product) {

                $current_type = $woo_product->get_type();
                $incoming_type = $product_data['type'];

                if ($current_type !== $incoming_type) {

                    Helper::logData("Changing product type from {$current_type} to {$incoming_type}", 'custom-import');

                    $woo_product = $this->convertProductType($woo_product, $incoming_type);
                }
            }

            // Crear una instancia del producto según su tipo
            if ($product_data['type'] === 'simple') {
                if (! $woo_product) {

                    if (isset($import_settings['meliconnect_import_type']) && $import_settings['meliconnect_import_type'] == 'onlyUpdate') {
                        Helper::logData('Product not found. Skipping creation process by setiings.', 'custom-import');
                        continue;
                    }

                    $woo_product = new \WC_Product_Simple();
                    $woo_product->save();
                }
                $this->add_simple_product_data($woo_product, $product_data);
            } elseif ($product_data['type'] === 'variable') {
                if (! $woo_product) {

                    if (isset($import_settings['meliconnect_import_type']) && $import_settings['meliconnect_import_type'] == 'onlyUpdate') {
                        Helper::logData('Product not found. Skipping creation process by setiings.', 'custom-import');
                        continue;
                    }

                    $woo_product = new \WC_Product_Variable();
                    $woo_product->save();
                }
            }

            Helper::logData('Product type: ' . $product_data['type'], 'custom-import');

            // Create a product with basic data and saves it
            $woo_product = $this->createBaseProduct($woo_product, $product_data);

            // Manejo de errores
            if (is_wp_error($woo_product)) {
                // Lógica de manejo de errores
                Helper::logData('Error creating product: ' . $woo_product->get_error_message(), 'custom-import');
                return false;
            }

            $template_id = Template::createUpdateTemplateFromMeliListing('product', $woo_product->get_id(), $meliListingData);

            if ($template_id) {
                Template::deleteCreateTemplatesMetasFromMeliListing($template_id, $meliListingData);

                $product_data['extra_data']['postmetas']['meliconnect_asoc_template_id'] = $template_id;
            } else {
                Helper::logData('Error creating template for product: ' . $woo_product->get_id(), 'custom-import');
                return false;
            }

            if (isset($product_data['extra_data']['attributes']) && $product_data['extra_data']['attributes'] !== false) {
                $productAttributes = $this->createOrUpdateProductAttributes($woo_product, $product_data['extra_data']['attributes']);

                // Helper::logData('Attributes created:' . wp_json_encode($productAttributes), 'custom-import');
                Helper::logData('Attributes created and assigned to product', 'custom-import');
                // $woo_product->set_attributes($productAttributes);
            } else {
                Helper::logData('Attributes ignored by settings', 'custom-import');
            }

            if (isset($product_data['variations']) && ! empty($product_data['variations'])) {

                $this->assignVariableAttributes($woo_product, $product_data['variations'], $template_id);

                $import_settings = Helper::getMeliconnectOptions('import');
                $update_variations_startegy = $import_settings['meliconnect_import_variable_update_strategy'] ?? 'recreate';

                if ($update_variations_startegy === 'recreate') {
                    $this->deleteAllProductVariations($woo_product->get_id());
                }


                $this->createProductVariations($woo_product->get_id(), $product_data['variations']);
            }

            // Crear postmetas si es necesario. Creates postmetas as meliconnect_meli_listing_id, meliconnect_meli_seller_id, meliconnect_meli_permalink when import
            if (isset($product_data['extra_data']['postmetas'])) {
                $this->createPostmetas($woo_product->get_id(), $product_data['extra_data']['postmetas']);
            }

            $woo_product->save();

            $woo_products_ids[] = $woo_product->get_id();

            Helper::logData('------------------ END Product created with id: ' . $woo_product->get_id() . '-------------------- ', 'custom-import');
        }

        return $woo_products_ids;
    }

    protected function convertProductType($product, $new_type)
    {

        $product_id = $product->get_id();

        Helper::logData("Converting product ID {$product_id} to {$new_type}", 'custom-import');

        // 1. Si era variable → eliminar variaciones
        if ($product->is_type('variable')) {

            $children = $product->get_children();

            foreach ($children as $child_id) {
                wp_delete_post($child_id, true);
            }

            Helper::logData("Deleted existing variations", 'custom-import');
        }

        // 2. Limpiar atributos completamente
        $product->set_attributes([]);
        delete_post_meta($product_id, '_product_attributes');

        // 3. Limpiar datos de pricing/stock
        $product->set_regular_price('');
        $product->set_sale_price('');
        $product->set_price('');
        $product->set_manage_stock(false);
        $product->set_stock_quantity(null);

        // 4. Cambiar tipo en taxonomy
        wp_set_object_terms($product_id, $new_type, 'product_type');

        // 5. Re-instanciar correctamente
        if ($new_type === 'variable') {
            $product = new \WC_Product_Variable($product_id);
        } else {
            $product = new \WC_Product_Simple($product_id);
        }

        $product->save();

        Helper::logData("Product converted successfully", 'custom-import');

        return $product;
    }


    private function createBaseProduct($woo_product, $product_data)
    {
        Helper::logData('Woo Product id: ' . $woo_product->get_id(), 'custom-import');

        //Helper::logData( 'Product data: ' . wp_json_encode( $product_data ), 'custom-import' );

        $meli_seller_id = $product_data['extra_data']['postmetas']['meliconnect_meli_seller_id'] ?? null;

        // Asignar el título del producto
        if (isset($product_data['title']) && $product_data['title'] !== false) {
            $woo_product->set_name($product_data['title']);

            Helper::logData('Title: ' . $product_data['title'] . 'updated in product.', 'custom-import');
        } else {
            Helper::logData('Title ignored by settings', 'custom-import');
        }

        if (isset($product_data['sku']) && $product_data['sku'] !== false) {
            // Verificar si el SKU ya existe
            $existing_product_id = Helper::get_active_product_id_by_sku($product_data['sku']);
            if ($product_data['sku']) {
                update_post_meta(
                    $woo_product->get_id(),
                    '_meliconnect_sku',
                    $product_data['sku']
                );
            }

            if ($existing_product_id) {
                // Si el SKU ya existe, puedes optar por omitir la asignación o manejarlo de otra manera
                Helper::logData('Sku ' . $product_data['sku'] . ' already exists. Para el producto con ID: ' . $existing_product_id, 'custom-import');
            } else {
                // Si el SKU no existe, lo asignamos al producto
                Helper::logData('SKU: ' . $product_data['sku'] . ' updated in product.', 'custom-import');
                $woo_product->set_sku($product_data['sku']);
            }
        } else {
            Helper::logData('SKU ignored by settings', 'custom-import');
        }

        if (isset($product_data['gtin']) && $product_data['gtin'] !== false) {

            Helper::logData('GTIN: ' . $product_data['gtin'] . ' updated in product.', 'custom-import');


            //Because GTIN is validated by woocommerce, we need to save it as a postmeta
            //$woo_product->set_global_unique_id( $product_data['gtin'] );

            update_post_meta(
                $woo_product->get_id(),
                '_meliconnect_gtin',
                $product_data['gtin']
            );
        } else {
            Helper::logData('GTIN ignored by settings', 'custom-import');
        }


        // Descripciones
        if (isset($product_data['short_description']) && $product_data['short_description'] !== false) {

            if (empty($product_data['short_description'])) {
                $product_data['short_description'] = '';
            }

            $woo_product->set_short_description($product_data['short_description']);

            Helper::logData('Short description UPDATED succesfully', 'custom-import');
        } else {
            Helper::logData('Short description ignored by settings', 'custom-import');
        }

        if (isset($product_data['description']) && $product_data['description'] !== false) {

            if (empty($product_data['description'])) {
                $product_data['description'] = '';
            }

            $woo_product->set_description($product_data['description']);
            Helper::logData('Description UPDATED succesfully', 'custom-import');
        } else {
            Helper::logData('Description ignored by settings', 'custom-import');
        }

        // Dimensiones
        if (isset($product_data['weight']) && $product_data['weight'] !== false) {
            $woo_product->set_weight(
                Helper::meliconnect_convert_weight_to_store_unit($product_data['weight'])
            );
        } else {
            //Helper::logData( 'Weight ignored by settings', 'custom-import' );
        }

        if (isset($product_data['length']) && $product_data['length'] !== false) {
            $woo_product->set_length(
                Helper::meliconnect_convert_dimension_to_store_unit($product_data['length'])
            );
        } else {
            //Helper::logData( 'Length ignored by settings', 'custom-import' );
        }

        if (isset($product_data['width']) && $product_data['width'] !== false) {
            $woo_product->set_width(
                Helper::meliconnect_convert_dimension_to_store_unit($product_data['width'])
            );
        } else {
            //Helper::logData( 'Width ignored by settings', 'custom-import' );
        }

        if (isset($product_data['height']) && $product_data['height'] !== false) {
            $woo_product->set_height(
                Helper::meliconnect_convert_dimension_to_store_unit($product_data['height'])
            );
        } else {
            //Helper::logData( 'Height ignored by settings', 'custom-import' );
        }

        // Imágenes
        if (isset($product_data['pictures']['main_image']) && $product_data['pictures']['main_image'] !== false) {
            $this->create_or_update_main_image($woo_product->get_id(), $product_data['pictures']['main_image'], $meli_seller_id);
            Helper::logData('Main image UPDATED succesfully', 'custom-import');
        } else {
            Helper::logData('Main image ignored by settings', 'custom-import');
        }

        if (isset($product_data['pictures']['gallery_images']) && $product_data['pictures']['gallery_images'] !== false) {
            $this->create_or_update_gallery_images($woo_product->get_id(), $product_data['pictures']['gallery_images'], $meli_seller_id);
            Helper::logData('Gallery images UPDATED succesfully', 'custom-import');
        } else {
            Helper::logData('Gallery images ignored by settings', 'custom-import');
        }

        // Categorías y etiquetas
        if (isset($product_data['extra_data']['categories']) && $product_data['extra_data']['categories'] !== false) {
            $this->createOrUpdateCategories($woo_product->get_id(), $product_data['extra_data']['categories']);
            Helper::logData('Categories UPDATED succesfully', 'custom-import');
        } else {
            Helper::logData('Categories ignored by settings', 'custom-import');
        }

        /*
		$tag_ids = $this->createUpdateTags($product_data['tags']);
		$woo_product->set_tag_ids($tag_ids); */

        // Estado del producto
        if (isset($product_data['status']) && $product_data['status'] !== false) {
            $prev_status = $woo_product->get_status();
            $new_status  = $product_data['status'];

            if ($prev_status !== $new_status) {

                $woo_product->set_status($new_status); // (draft, pending, private, publish)

                Helper::logData(
                    "STATUS CHANGED. FROM: {$prev_status} → TO: {$new_status}",
                    'custom-import'
                );
            } else {
                Helper::logData(
                    "STATUS unchanged: {$prev_status}",
                    'custom-import'
                );
            }
        } else {
            Helper::logData('Status ignored by settings', 'custom-import');
        }

        $woo_product->save();
        return $woo_product;
    }

    private function add_simple_product_data($woo_product, $product_data)
    {

        // ====== PREVIOUS VALUES ======
        $prev_regular_price = $woo_product->get_regular_price();
        $prev_sale_price    = $woo_product->get_sale_price();
        $prev_manage_stock  = $woo_product->get_manage_stock();
        $prev_stock_qty     = $woo_product->get_stock_quantity();
        $prev_stock_status  = $woo_product->get_stock_status();

        // ====== NEW VALUES ======
        $new_regular_price = $product_data['regular_price'];
        $new_sale_price    = $product_data['sale_price'] ?? '';
        $new_manage_stock  = $product_data['manage_stock'];
        $new_stock_qty     = $product_data['available_quantity'];
        $new_stock_status  = ($new_stock_qty > 0) ? 'instock' : 'outofstock';

        // ====== PRICE ======
        $woo_product->set_regular_price($new_regular_price);

        if (!empty($new_sale_price) && $new_sale_price < $new_regular_price) {
            $woo_product->set_sale_price($new_sale_price);
        } else {
            // limpia promo si no corresponde
            $woo_product->set_sale_price('');
        }

        // ====== STOCK ======
        $woo_product->set_manage_stock($new_manage_stock);
        $woo_product->set_stock_quantity($new_stock_qty);
        $woo_product->set_stock_status($new_stock_status);

        // ====== LOGGING ======
        Helper::logData(
            'Product stock/price diff: ' . wp_json_encode([
                'regular_price' => ['old' => $prev_regular_price, 'new' => $new_regular_price],
                'sale_price'    => ['old' => $prev_sale_price, 'new' => $new_sale_price],
                'manage_stock'  => ['old' => $prev_manage_stock, 'new' => $new_manage_stock],
                'stock_qty'     => ['old' => $prev_stock_qty, 'new' => $new_stock_qty],
                'stock_status'  => ['old' => $prev_stock_status, 'new' => $new_stock_status],
            ]),
            'custom-import'
        );

        return true;
    }

    private function assignVariableAttributes($woo_product, $variations)
    {
        $attributes              = array();
        $variable_attrs_fromated = array();

        foreach ($variations as $variation) {
            foreach ($variation['variable_attrs'] as $attr) {
                //Helper::logData('Variable attribute: ' . wp_json_encode($attr), 'custom-import');

                // bloquear atributos que nunca deben ser variables
                if (in_array($attr['id'], ['GTIN', 'SELLER_SKU'])) {
                    continue;
                }

                $variable_attrs_fromated[$attr['name']][] = $attr['value_name'];
            }
        }

        foreach ($variable_attrs_fromated as $attr_name => $attr_options) {
            // Eliminar duplicados en las opciones de atributos
            $attr_options = array_unique($attr_options);

            // Crear o actualizar el atributo del producto usando la función helper
            $productAttributes = $this->createOrUpdateProductAttributes(
                $woo_product,
                array(
                    array(
                        'name'      => $attr_name,
                        'options'   => $attr_options,
                        'position'  => 0,
                        'visible'   => true,
                        'variation' => true,
                    ),
                ),
            );
        }

        return true;
    }

    /**
     * Crea las variaciones para un producto variable.
     */
    /**
     * Crea las variaciones para un producto variable.
     */
    private function createProductVariations($product_id, $variations)
    {

        /**
         * =========================================================
         * MERGE DUPLICATE VARIATIONS
         * =========================================================
         *
         * Detects variations with identical attributes and keeps
         * only one according to the configured strategy.
         */
        $import_settings = Helper::getMeliconnectOptions('import');

        //Helper::logData('Import settings:'. var_export($import_settings,true), 'custom-import');

        $dedupe_enabled = ($import_settings['meliconnect_import_dedupe_variations'] ?? 'false') === 'true';

        if ($dedupe_enabled) {

            $strategy = $import_settings['meliconnect_import_dedupe_strategy'] ?? 'lowest_price';

            Helper::logData('Deduping variations using strategy: ' . $strategy, 'custom-import');

            $variations = $this->filterDuplicateVariations($variations, $strategy);
        }

        /**
         * =========================================================
         * CREATE / UPDATE VARIATIONS
         * =========================================================
         */

        foreach ($variations as $variation_data) {

            $variation_id = isset($variation_data['variation_id'])
                ? $variation_data['variation_id']
                : null;

            // Try to find existing variation
            if ($variation_id) {

                $existing_variation_id = $this->getExistingVariationId(
                    $variation_id,
                    $product_id
                );
            } else {

                $existing_variation_id = null;
            }

            if ($existing_variation_id) {

                // Update existing variation
                $variation = new \WC_Product_Variation(
                    $existing_variation_id
                );

                Helper::logData(
                    'Updating variation: ' . $existing_variation_id,
                    'custom-import'
                );
            } else {

                // Create new variation
                $variation = new \WC_Product_Variation();

                $variation->set_parent_id($product_id);

                Helper::logData(
                    'Creating variation for product: ' . $product_id,
                    'custom-import'
                );
            }

            /**
             * =========================================================
             * PREVIOUS VALUES
             * =========================================================
             */

            $prev_price        = $variation->get_regular_price();
            $prev_stock_qty    = $variation->get_stock_quantity();
            $prev_manage_stock = $variation->get_manage_stock();
            $prev_stock_status = $variation->get_stock_status();

            /**
             * =========================================================
             * NEW VALUES
             * =========================================================
             */

            $new_price = isset($variation_data['price'])
                ? (float) $variation_data['price']
                : 0;

            $new_stock_qty = isset($variation_data['available_quantity'])
                ? (int) $variation_data['available_quantity']
                : 0;

            $new_manage_stock = isset($variation_data['manage_stock'])
                ? (bool) $variation_data['manage_stock']
                : true;

            $new_stock_status = ($new_stock_qty > 0)
                ? 'instock'
                : 'outofstock';

            /**
             * =========================================================
             * PRICE / STOCK
             * =========================================================
             */

            $variation->set_regular_price($new_price);

            $final_sku = $this->resolveVariationSku(
                $variation_data,
                $existing_variation_id
            );

            if ($final_sku) {

                $variation->set_sku($final_sku);
            }

            $variation->set_manage_stock($new_manage_stock);

            if ($new_manage_stock) {

                $variation->set_stock_quantity($new_stock_qty);
                $variation->set_stock_status($new_stock_status);
            } else {

                $variation->set_stock_quantity(null);
                $variation->set_stock_status($new_stock_status);
            }

            /**
             * =========================================================
             * ATTRIBUTES
             * =========================================================
             */

            $attributes = array();

            if (! empty($variation_data['variable_attrs'])) {

                foreach ($variation_data['variable_attrs'] as $attr) {

                    if (
                        empty($attr['name']) ||
                        empty($attr['value_name'])
                    ) {
                        continue;
                    }

                    $attribute_name = wc_sanitize_taxonomy_name(
                        $attr['name']
                    );

                    $taxonomy_name = 'pa_' . $attribute_name;

                    $term = get_term_by(
                        'name',
                        $attr['value_name'],
                        $taxonomy_name
                    );

                    if ($term) {

                        $attributes[$taxonomy_name] = $term->slug;
                    }
                }
            }

            Helper::logData(
                'Attributes to set in variation: ' .
                    wp_json_encode($attributes),
                'custom-import'
            );

            $variation->set_attributes($attributes);

            /**
             * =========================================================
             * SAVE VARIATION
             * =========================================================
             */

            $variation->save();

            $variation_post_id = $variation->get_id();

            /**
             * =========================================================
             * META
             * =========================================================
             */

            update_post_meta(
                $variation_post_id,
                'meliconnect_meli_asoc_variation_id',
                $variation_id
            );

            if (! empty($variation_data['user_product_id'])) {

                update_post_meta(
                    $variation_post_id,
                    'meliconnect_meli_user_product_id',
                    $variation_data['user_product_id']
                );
            }

            if (! empty($variation_data['permalink'])) {

                update_post_meta(
                    $variation_post_id,
                    'meliconnect_meli_permalink',
                    $variation_data['permalink']
                );
            }

            if (! empty($variation_data['status'])) {

                update_post_meta(
                    $variation_post_id,
                    'meliconnect_meli_status',
                    $variation_data['status']
                );
            }

            if (! empty($variation_data['family_id'])) {

                update_post_meta(
                    $variation_post_id,
                    'meliconnect_meli_family_id',
                    $variation_data['family_id']
                );
            }

            /**
             * =========================================================
             * IMAGES
             * =========================================================
             */

            if (! empty($variation_data['pictures'])) {

                $this->assignVariationImage(
                    $variation,
                    $variation_data['pictures']
                );
            }

            /**
             * =========================================================
             * NON VARIABLE ATTRIBUTES
             * =========================================================
             */

            $this->setNonVariableAttributes(
                $variation,
                $variation_data['non_variable_attrs']
            );

            /**
             * =========================================================
             * LOG DIFF
             * =========================================================
             */

            /*
            Helper::logData(
                'Variation diff: ' . wp_json_encode([
                    'variation_id' => $existing_variation_id ?: 'NEW',
                    'price' => [
                        'old' => $prev_price,
                        'new' => $new_price
                    ],
                    'stock_qty' => [
                        'old' => $prev_stock_qty,
                        'new' => $new_stock_qty
                    ],
                    'manage_stock' => [
                        'old' => $prev_manage_stock,
                        'new' => $new_manage_stock
                    ],
                    'stock_status' => [
                        'old' => $prev_stock_status,
                        'new' => $new_stock_status
                    ],
                ]),
                'custom-import'
            );
            */
        }
    }

    /**
     * Removes duplicate variations that have the same attributes.
     *
     * Keeps only one variation according to the configured strategy.
     *
     * @param array $variations
     * @return array
     */
    private function filterDuplicateVariations($variations, $strategy)
    {

        if (empty($variations) || ! is_array($variations)) {
            return $variations;
        }

        /**
         * =========================================================
         * GROUPED VARIATIONS
         * =========================================================
         */

        $grouped = array();

        foreach ($variations as $variation) {

            /* Helper::logData(
                'FULL VARIATION DATA: ' .
                    var_export($variation, true),
                'custom-import'
            ); */

            /**
             * =====================================================
             * BUILD SIGNATURE
             * =====================================================
             *
             * Variations with the same attributes will generate
             * the same signature.
             */

            $signature = $this->buildVariationSignature(
                $variation['variable_attrs'] ?? array()
            );

            /**
             * =====================================================
             * FIRST OCCURRENCE
             * =====================================================
             */

            if (! isset($grouped[$signature])) {

                $grouped[$signature] = $variation;

                continue;
            }

            /**
             * =====================================================
             * COMPARE AGAINST EXISTING
             * =====================================================
             */

            $existing = $grouped[$signature];

            Helper::logData(
                'Duplicate variation detected: ' .
                    wp_json_encode(array(
                        'strategy' => $strategy,

                        'signature' => $signature,

                        'candidate' => array(
                            'id' => $variation['variation_id'] ?? '',
                            'price' => $variation['price'] ?? '',
                            'stock' => $variation['available_quantity'] ?? '',
                            'date_created' => $variation['date_created'] ?? '',
                            'permalink' => $variation['permalink'] ?? '',
                        ),

                        'existing' => array(
                            'id' => $existing['variation_id'] ?? '',
                            'price' => $existing['price'] ?? '',
                            'stock' => $existing['available_quantity'] ?? '',
                            'date_created' => $existing['date_created'] ?? '',
                            'permalink' => $existing['permalink'] ?? '',
                        ),
                    )),
                'custom-import'
            );

            $replace = false;

            switch ($strategy) {

                /**
                 * =============================================
                 * LOWEST PRICE
                 * =============================================
                 */

                case 'lowest_price':

                    $replace =
                        (float) ($variation['price'] ?? 0)
                        <
                        (float) ($existing['price'] ?? 0);

                    break;

                /**
                 * =============================================
                 * HIGHEST PRICE
                 * =============================================
                 */

                case 'highest_price':

                    $replace =
                        (float) ($variation['price'] ?? 0)
                        >
                        (float) ($existing['price'] ?? 0);

                    break;

                /**
                 * =============================================
                 * LOWEST STOCK
                 * =============================================
                 */

                case 'lowest_stock':

                    $replace =
                        (int) ($variation['available_quantity'] ?? 0)
                        <
                        (int) ($existing['available_quantity'] ?? 0);

                    break;

                /**
                 * =============================================
                 * HIGHEST STOCK
                 * =============================================
                 */

                case 'highest_stock':

                    $replace =
                        (int) ($variation['available_quantity'] ?? 0)
                        >
                        (int) ($existing['available_quantity'] ?? 0);

                    break;

                /**
                 * =============================================
                 * OLDEST LISTING
                 * =============================================
                 */

                case 'oldest_listing':

                    $replace =
                        strcmp(
                            (string) ($variation['variation_id'] ?? ''),
                            (string) ($existing['variation_id'] ?? '')
                        ) < 0;

                    break;

                /**
                 * =============================================
                 * NEWEST LISTING
                 * =============================================
                 */

                case 'newest_listing':

                    $replace =
                        strcmp(
                            (string) ($variation['variation_id'] ?? ''),
                            (string) ($existing['variation_id'] ?? '')
                        ) > 0;

                    break;

                default:

                    $replace = false;
            }

            Helper::logData(
                'Duplicate comparison result: ' .
                    wp_json_encode(array(
                        'strategy' => $strategy,
                        'replace' => $replace,

                        'winner_id' => $replace
                            ? ($variation['variation_id'] ?? '')
                            : ($existing['variation_id'] ?? ''),

                        'loser_id' => $replace
                            ? ($existing['variation_id'] ?? '')
                            : ($variation['variation_id'] ?? ''),
                    )),
                'custom-import'
            );
            /**
             * =====================================================
             * REPLACE SELECTED VARIATION
             * =====================================================
             */

            if ($replace) {

                Helper::logData(
                    'Replacing duplicate variation: ' .
                        wp_json_encode(array(
                            'strategy' => $strategy,
                            'old_id' => $existing['variation_id'] ?? '',
                            'new_id' => $variation['variation_id'] ?? '',
                            'old_price' => $existing['price'] ?? '',
                            'new_price' => $variation['price'] ?? '',
                            'old_stock' => $existing['available_quantity'] ?? '',
                            'new_stock' => $variation['available_quantity'] ?? '',
                        )),
                    'custom-import'
                );

                $grouped[$signature] = $variation;
            }
        }

        /**
         * =========================================================
         * RESULT
         * =========================================================
         */

        $filtered = array_values($grouped);

        Helper::logData(
            'Duplicate variation filter reduced variations from ' .
                count($variations) .
                ' to ' .
                count($filtered),
            'custom-import'
        );

        return $filtered;
    }

    private function deleteAllProductVariations($product_id)
    {
        $children = get_children([
            'post_parent' => $product_id,
            'post_type'   => 'product_variation',
            'numberposts' => -1,
            'fields'      => 'ids',
        ]);

        foreach ($children as $child_id) {

            Helper::logData(
                'Deleting variation: ' . $child_id,
                'custom-import'
            );

            wp_delete_post($child_id, true);
        }
    }

    /**
     * Builds a unique signature for variation attributes.
     *
     * @param array $attrs
     * @return string
     */
    private function buildVariationSignature($attrs)
    {
        //Helper::logData('Attributes used to build signature: ' . var_export($attrs, true), 'custom-import');

        if (empty($attrs)) {
            return 'no_attributes';
        }

        $signature = array();

        foreach ($attrs as $attr) {

            if (
                empty($attr['name']) ||
                empty($attr['value_name'])
            ) {
                continue;
            }

            $signature[] =
                wc_sanitize_taxonomy_name($attr['name']) .
                ':' .
                sanitize_title($attr['value_name']);
        }

        sort($signature);

        return md5(
            implode('|', $signature)
        );
    }

    protected function resolveVariationSku($variation_data, $existing_variation_id)
    {

        // Si ya existe la variación → NO tocar SKU
        if ($existing_variation_id) {

            $existing_product = wc_get_product($existing_variation_id);

            if ($existing_product && $existing_product->get_sku()) {

                Helper::logData('Variation already exists with SKU: ' . $existing_product->get_sku(), 'custom-import');

                return $existing_product->get_sku();
            }
        }

        // Si es nueva variación → generar SKU

        $base_sku = ! empty($variation_data['sku']) ? trim($variation_data['sku']) : '';
        $variation_meli_id = $variation_data['variation_id'] ?? '';

        // 1. Intentar SKU original
        if ($base_sku && Helper::canSetSku($base_sku, $existing_variation_id)) {
            Helper::logData('Using original SKU: ' . $base_sku, 'custom-import');
            update_post_meta($existing_variation_id, '_meliconnect_original_sku', $base_sku);

            return $base_sku;
        }

        // 2. Fallback con variation_id
        if ($variation_meli_id) {

            $generated_sku = $base_sku
                ? "{$base_sku}-{$variation_meli_id}"
                : "meli-{$variation_meli_id}";

            Helper::logData('Using generated SKU: ' . $generated_sku, 'custom-import');

            if (Helper::canSetSku($generated_sku, $existing_variation_id)) {
                return $generated_sku;
            }
        }

        // 3. Último fallback
        Helper::logData('Using unique SKU', 'custom-import');
        return uniqid('meli_');
    }

    private function assignVariationImage($variation, $pictures)
    {

        if (empty($pictures)) {
            return;
        }

        $image_data = $pictures[0]; // primera imagen

        if (empty($image_data['id'])) {
            return;
        }

        $image_id = $image_data['id'];

        // buscar si ya existe en la librería
        $attachment_id = $this->attachment_exists_by_meta(
            'meliconnect_meli_image_id',
            $image_id
        );

        if (! $attachment_id) {

            $image_url = $image_data['secure_url'] ?? $image_data['url'] ?? null;

            if (! $image_url) {
                return;
            }

            $attachment_id = $this->upload_image_to_media_library($image_url);

            if (! $attachment_id) {
                return;
            }

            update_post_meta(
                $attachment_id,
                'meliconnect_meli_image_id',
                $image_id
            );

            update_post_meta(
                $attachment_id,
                'meliconnect_meli_image_url',
                $image_url
            );
        }

        if ($attachment_id) {

            $variation->set_image_id($attachment_id);
            $variation->save();

            Helper::logData(
                'Variation image assigned: ' . $attachment_id .
                    ' to variation ' . $variation->get_id(),
                'custom-import'
            );
        }
    }

    private function setNonVariableAttributes($variation, $non_variable_attrs)
    {
        $sku               = '';
        $gtin              = '';
        $custom_attributes = array();

        // Registrar los atributos no variables recibidos
        // Helper::logData('Non-variable attributes received: ' . wp_json_encode($non_variable_attrs), 'custom-import');

        foreach ($non_variable_attrs as $attr) {
            if ($attr['id'] === 'SELLER_SKU') {
                $sku = $attr['value_name'];
            } elseif ($attr['id'] === 'GTIN') {
                $gtin = $attr['value_name'];
            } else {
                $custom_attributes[$attr['id']] = $attr['value_name'];
            }
        }

        if ($sku) {
            update_post_meta(
                $variation->get_id(),
                '_meliconnect_sku',
                $sku
            );
        }

        if (Helper::canSetSku($sku, $variation->get_id())) {

            $variation->set_sku($sku);

            Helper::logData('Assigned SKU from Meli attribute: ' . $sku, 'custom-import');
        } else {
            Helper::logData(
                'Variation Attr SKU skipped because it already exists. SKU="' . $sku . '" Variation ID =' . $variation->get_id(),
                'custom-import'
            );
        }

        // Guardar GTIN como postmeta y registrar resultado
        if ($gtin) {
            $result = update_post_meta($variation->get_id(), '_global_unique_id', $gtin);
            if ($result === false) {
                Helper::logData('Failed to update GTIN for variation ID ' . $variation->get_id(), 'custom-import');
            } else {
                Helper::logData('Successfully updated GTIN for variation ID ' . $variation->get_id(), 'custom-import');
            }
        }

        // Asignar y guardar atributos personalizados, registrar cada uno
        foreach ($custom_attributes as $attribute_id => $attribute_value) {
            $taxonomy_name = 'pa_' . sanitize_title($attribute_id);

            $result = update_post_meta($variation->get_id(), '_' . $taxonomy_name, $attribute_value);
            /*
			if ($result === false) {
				Helper::logData('Failed to update custom attribute ' . $attribute_id . ' for variation ID ' . $variation->get_id(), 'custom-import');
			} else {
				Helper::logData('Successfully updated custom attribute ' . $attribute_id . ' with value ' . $attribute_value . ' for variation ID ' . $variation->get_id(), 'custom-import');
			} */
        }

        // Guardar variación y registrar resultado
        $saved = $variation->save();
        /*
		if (!$saved) {
			Helper::logData('Failed to save variation ID ' . $variation->get_id(), 'custom-import');
		} else {
			Helper::logData('Successfully saved variation ID ' . $variation->get_id(), 'custom-import');
		} */

        return $saved;
    }

    private function getExistingVariationId($variation_id, $product_id)
    {
        $args = array(
            'post_type'      => 'product_variation',
            'post_status'    => 'any',
            'meta_key'       => 'meliconnect_meli_asoc_variation_id',
            'meta_value'     => $variation_id,
            'posts_per_page' => 1,
            'post_parent'    => $product_id,
        );

        $query = new \WP_Query($args);

        if ($query->have_posts()) {
            return $query->posts[0]->ID;
        }

        return null;
    }




    private function createOrUpdateProductAttributes($product, $attrs)
    {
        $productAttributes = $product->get_attributes(); // Obtener los atributos existentes
        $log_text          = '---- Start createOrUpdateProductAttributes for product ID: ' . $product->get_id() . '----';

        foreach ($attrs as $attributeData) {
            $attributeName = wc_sanitize_taxonomy_name($attributeData['name']);
            $taxonomyName  = 'pa_' . $attributeName;

            $log_text .= "\n\n";
            $log_text .= 'Processing attribute: ' . $attributeData['name'] . "\n";

            $attributeId = wc_attribute_taxonomy_id_by_name($attributeName);

            if (! $attributeId) {
                $log_text .= 'Attribute not found. Creating new attribute: ' . $attributeData['name'] . "\n";

                $attributeId = wc_create_attribute(
                    array(
                        'name'         => $attributeData['name'],
                        'slug'         => $attributeName,
                        'type'         => 'select',
                        'order_by'     => 'menu_order',
                        'has_archives' => false,
                    )
                );

                if (is_wp_error($attributeId)) {
                    $log_text .= 'Error creating attribute: ' . $attributeId->get_error_message() . "\n";
                    continue;
                } else {
                    $log_text .= 'Attribute created successfully with ID: ' . $attributeId . "\n";
                }
            }

            // Asegurarse de que los términos (opciones) existan en la taxonomía del atributo
            foreach ($attributeData['options'] as $option) {
                if (! term_exists($option, $taxonomyName)) {
                    $log_text .= 'Creating term: ' . $option . ' in taxonomy: ' . $taxonomyName . "\n";
                    $term      = wp_insert_term($option, $taxonomyName);

                    if (is_wp_error($term)) {
                        $log_text .= 'Error creating term: ' . $term->get_error_message() . "\n";
                    } else {
                        $log_text .= 'Term created successfully with ID: ' . $term['term_id'] . "\n";
                    }
                } else {
                    $log_text .= 'Term already exists: ' . $option . "\n";
                }
            }

            $attr = new \WC_Product_Attribute();
            $attr->set_id($attributeId);
            $attr->set_name($taxonomyName);

            // Obtener los IDs de los términos
            $option_ids = array_map(
                function ($option) use ($taxonomyName) {
                    $term = get_term_by('name', $option, $taxonomyName);
                    return $term ? $term->term_id : null;
                },
                $attributeData['options']
            );
            $option_ids = array_filter($option_ids);

            $attr->set_options($option_ids);

            /*  wp_set_object_terms(
                $product->get_id(),
                $option_ids,
                $taxonomyName
            ); */

            $attr->set_position($attributeData['position']);
            $attr->set_visible($attributeData['visible']);
            $attr->set_variation($attributeData['variation']);

            $log_text .= 'Final attribute object created or updated: ' . wp_json_encode($attr) . "\n";

            // Añadir o actualizar el atributo en el array existente
            $productAttributes[$taxonomyName] = $attr;
        }

        $log_text .= "\n\n\n";
        $log_text .= 'Final product attributes array: ' . wp_json_encode($productAttributes) . "\n";

        $product->set_attributes($productAttributes); // Guardar todos los atributos combinados
        $product->save();

        $log_text .= 'Product saved with attributes: ' . wp_json_encode($productAttributes) . "\n";
        $log_text .= '---- End createOrUpdateProductAttributes for product ID: ' . $product->get_id() . '----';
        $log_text .= "\n\n\n";

        //Helper::logData($log_text, 'custom-import');

        return $productAttributes;
    }



    private function createOrUpdateAttributes($attrs)
    {
        $productAttributes = array();

        foreach ($attrs as $attributeData) {
            $attributeName = wc_sanitize_taxonomy_name($attributeData['name']);

            $attributeId = wc_attribute_taxonomy_id_by_name($attributeName);
            if (! $attributeId) {
                $attributeId = wc_create_attribute(
                    array(
                        'name'         => $attributeData['name'],
                        'slug'         => $attributeName,
                        'type'         => 'select',
                        'order_by'     => 'menu_order',
                        'has_archives' => false,
                    )
                );
            }

            foreach ($attributeData['options'] as $option) {
                wp_insert_term($option, 'pa_' . $attributeName);
            }

            $productAttributes['pa_' . $attributeName] = array(
                'name'         => 'pa_' . $attributeName,
                'value'        => implode(' | ', $attributeData['options']),
                'position'     => $attributeData['position'],
                'is_visible'   => $attributeData['visible'],
                'is_variation' => $attributeData['variation'],
                'is_taxonomy'  => true,
            );
        }

        return $productAttributes;
    }




    private function create_or_update_main_image($post_id, $main_image_data, $seller_id = null)
    {
        // Extraer el ID de la imagen
        $image_id = $main_image_data['id'];

        if (empty($seller_id)) {
            $seller_id = get_post_meta($post_id, 'meliconnect_meli_seller_id', true);
        }

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

        if (empty($access_token)) {
            Helper::logData('No access token found for seller ID: ' . $seller_id, 'custom-import');
            return;
        }

        // Obtener la URL de la imagen más grande
        $image_url = $this->get_meli_largest_image_url($image_id, $access_token);

        if (empty($image_url)) {
            Helper::logData('No valid image URL found for image ID: ' . $image_id, 'custom-import');
            return;
        }

        // Verificar si la imagen ya existe en la galería de medios usando el meta `meliconnect_meli_image_id`
        $attachment_id = $this->attachment_exists_by_meta('meliconnect_meli_image_id', $image_id);

        if (! $attachment_id) {
            Helper::logData('Image not exists', 'custom-import');

            // Subir la imagen si no existe
            $attachment_id = $this->upload_image_to_media_library($image_url);

            if ($attachment_id) {
                // Agregar los metadatos de la imagen al adjunto
                update_post_meta($attachment_id, 'meliconnect_meli_image_id', $image_id, true);
                update_post_meta($attachment_id, 'meliconnect_meli_image_url', $image_url, true);

                Helper::logData('Image uploaded and meta added: ' . $attachment_id, 'custom-import');
            } else {
                Helper::logData('Failed to upload image', 'custom-import');
                return;
            }
        }

        Helper::logData('Upload image with attachment ID: ' . $attachment_id, 'custom-import');

        // Verificar el post ID y el attachment ID
        if ($post_id && $attachment_id) {
            delete_post_thumbnail($post_id);

            $set_post_thumbnail = set_post_thumbnail($post_id, $attachment_id);
            if ($set_post_thumbnail) {
                Helper::logData('SUCCESS on Set main image for post ID: ' . $post_id, 'custom-import');
            } else {
                Helper::logData('ERROR on Set main image for post ID: ' . $post_id, 'custom-import');
            }
        } else {
            Helper::logData('ERROR on Set main image for post ID: ' . $post_id . '. Invalid post ID or attachment ID', 'custom-import');
        }
    }

    private function get_meli_largest_image_url($image_id, $access_token)
    {
        // Obtener los datos de la imagen desde la API de Meli
        $meli_image_data = MeliconMeli::getMeliImageData($image_id, $access_token);

        // Obtener el tamaño máximo de la imagen
        $meli_image_max_size = isset($meli_image_data['max_size']) ? $meli_image_data['max_size'] : 0;

        // Inicializar la URL de la imagen
        $image_url = '';

        // Buscar la URL de la imagen que coincida con el tamaño máximo
        if (isset($meli_image_data['variations']) && ! empty($meli_image_data['variations'])) {
            foreach ($meli_image_data['variations'] as $image_variation) {
                if ($image_variation['size'] == $meli_image_max_size) {
                    $image_url = $image_variation['secure_url'];
                    break;
                }
            }
        }

        return $image_url;
    }

    private function attachment_exists_by_meta($meta_key, $meta_value)
    {
        global $wpdb;

        $query = $wpdb->get_var(
            $wpdb->prepare(
                "
            SELECT post_id FROM $wpdb->postmeta
            WHERE meta_key = %s AND meta_value = %s
            LIMIT 1
        ",
                $meta_key,
                $meta_value
            )
        );

        return $query;
    }

    private function upload_image_to_media_library($image_url)
    {
        global $wp_filesystem;

        // Inicializar el sistema de archivos
        if (! function_exists('WP_Filesystem')) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }

        if (! WP_Filesystem()) {
            Helper::logData('Error initializing WP_Filesystem', 'custom-import');
            return false;
        }

        // Obtener datos de la imagen usando wp_remote_get()
        $response = wp_remote_get($image_url);

        if (is_wp_error($response)) {
            Helper::logData('Error fetching image data: ' . $response->get_error_message(), 'custom-import');
            return false;
        }

        $image_data = wp_remote_retrieve_body($response);

        if (! $image_data) {
            Helper::logData('Error retrieving image body', 'custom-import');
            return false;
        }

        // Obtener directorio de uploads
        $upload_dir = wp_upload_dir();
        $filename   = basename($image_url);
        $file_path  = trailingslashit($upload_dir['path']) . $filename;

        // Guardar la imagen usando WP_Filesystem
        if (! $wp_filesystem->put_contents($file_path, $image_data, FS_CHMOD_FILE)) {
            Helper::logData('Failed to save image to upload directory', 'custom-import');
            return false;
        }

        // Preparar los datos para insertar en la biblioteca de medios
        $wp_filetype = wp_check_filetype($filename, null);
        $attachment  = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_title'     => sanitize_file_name($filename),
            'post_content'   => '',
            'post_status'    => 'inherit',
        );

        // Insertar el archivo en la biblioteca de medios
        $attach_id = wp_insert_attachment($attachment, $file_path);

        if (! $attach_id || is_wp_error($attach_id)) {
            Helper::logData('Error inserting attachment to media library', 'custom-import');
            return false;
        }

        // Generar metadatos para la imagen
        require_once ABSPATH . 'wp-admin/includes/image.php';
        $attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
        wp_update_attachment_metadata($attach_id, $attach_data);

        return $attach_id;
    }


    private function create_or_update_gallery_images($post_id, $gallery_images_data, $meli_seller_id = null)
    {
        $gallery_ids    = array();

        if (empty($meli_seller_id)) {
            $meli_seller_id = get_post_meta($post_id, 'meliconnect_meli_seller_id', true);
        }


        foreach ($gallery_images_data as $image_data) {
            // Extraer el ID de la imagen
            $image_id = $image_data['id'];

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

            // Obtener la URL de la imagen más grande
            $image_url = $this->get_meli_largest_image_url($image_id, $access_token);

            if (empty($image_url)) {
                Helper::logData('No valid image URL found for image ID: ' . $image_id, 'custom-import');
                continue;
            }

            // Verificar si la imagen ya existe en la galería de medios usando el meta `meliconnect_meli_image_id`
            $attachment_id = $this->attachment_exists_by_meta('meliconnect_meli_image_id', $image_id);

            if (! $attachment_id) {
                // Subir la imagen si no existe
                $attachment_id = $this->upload_image_to_media_library($image_url);

                if ($attachment_id) {
                    // Agregar los metadatos de la imagen al adjunto
                    update_post_meta($attachment_id, 'meliconnect_meli_image_id', $image_id, true);
                    update_post_meta($attachment_id, 'meliconnect_meli_image_url', $image_url, true);
                    update_post_meta($attachment_id, 'meliconnect_meli_image_seller_id', $meli_seller_id, true);
                } else {
                    Helper::logData('Failed to upload image for image ID: ' . $image_id, 'custom-import');
                    continue;
                }
            }

            // Agregar el ID del adjunto al array de IDs de la galería
            $gallery_ids[] = $attachment_id;
        }

        // Establecer la galería de imágenes para el producto
        if (! empty($gallery_ids)) {
            update_post_meta($post_id, '_product_image_gallery', implode(',', $gallery_ids));
        }
    }




    private function createOrUpdateCategories($productId, $categoryTree)
    {

        $maxLevel = (int) get_option('meliconnect_max_category_level', 2);

        //$this->logCategoryPath( $categoryTree );

        $categoryId = $this->processCategoryTree(
            $categoryTree,
            0,
            1,
            $maxLevel
        );

        if ($categoryId) {
            wp_set_object_terms($productId, [$categoryId], 'product_cat');
        }
    }

    private function logCategoryPath($categoryTree)
    {

        $path = [];
        $level = 1;

        while (! empty($categoryTree)) {

            if (empty($categoryTree['name'])) {
                break;
            }

            $path[] = $categoryTree['name'];

            Helper::logData(
                "Level {$level}: {$categoryTree['name']} ({$categoryTree['id']})",
                'custom-import'
            );

            if (empty($categoryTree['children'])) {
                break;
            }

            $categoryTree = $categoryTree['children'];
            $level++;
        }

        Helper::logData(
            'Full Category Path: ' . implode(' > ', $path),
            'custom-import'
        );
    }

    private function processCategoryTree(
        $category,
        $parentId = 0,
        $currentLevel = 1,
        $maxLevel = 2
    ) {

        if (empty($category['name']) || empty($category['id'])) {
            return null;
        }

        Helper::logData(
            'Processing category: ' . $category['name'] .
                ' | MELI ID: ' . $category['id'] .
                ' | Level: ' . $currentLevel,
            'custom-import'
        );

        // Corte por nivel
        if ($currentLevel > $maxLevel) {
            return $parentId;
        }

        $categoryId = null;
        $meliId = (string) $category['id'];

        /**
         * 1️Buscar SOLO por meli_id
         */
        $existing = get_terms([
            'taxonomy'   => 'product_cat',
            'meta_query' => [
                [
                    'key'   => 'meliconnect_meli_category_id',
                    'value' => $meliId,
                ]
            ],
            'hide_empty' => false,
            'number'     => 1,
        ]);

        if (! empty($existing) && ! is_wp_error($existing)) {

            // Ya existe → usarla
            $categoryId = $existing[0]->term_id;

            Helper::logData(
                'Category found by MELI ID: ' . $existing[0]->name,
                'custom-import'
            );
        } else {

            /**
             * 2️No existe → crear nueva
             */
            Helper::logData(
                'Creating new category: ' . $category['name'],
                'custom-import'
            );

            $slug = sanitize_title($category['name'] . '-' . $meliId);

            $new = wp_insert_term(
                $category['name'],
                'product_cat',
                [
                    'parent' => $parentId,
                    'slug'   => $slug,
                ]
            );

            if (is_wp_error($new)) {

                Helper::logData(
                    'Error creating category: ' . $new->get_error_message(),
                    'custom-import'
                );

                return null;
            }

            $categoryId = $new['term_id'];

            // Guardar meta SOLO al crear
            update_term_meta(
                $categoryId,
                'meliconnect_meli_category_id',
                $meliId
            );
        }

        /**
         * 3️ Recursión
         */
        if (
            ! empty($category['children']) &&
            $currentLevel < $maxLevel
        ) {

            return $this->processCategoryTree(
                $category['children'],
                $categoryId,
                $currentLevel + 1,
                $maxLevel
            );
        }

        return $categoryId;
    }

    private function processCategory($category, $parentId = 0)
    {
        // Helper::logData('processCategory: ' . wp_json_encode($category), 'custom-import');

        if (! isset($category['name'])) {
            return null;
        }

        // Helper::logData('processCategoryName: ' . wp_json_encode($category['name']), 'custom-import');
        // Verificar si la categoría ya existe por nombre y padre
        $existingCategory = get_term_by('name', $category['name'], 'product_cat');

        if ($existingCategory && $existingCategory->parent == $parentId) {
            // Si la categoría ya existe, usar su ID
            $categoryId = $existingCategory->term_id;
        } else {
            // Si no existe, crear la categoría
            $newCategory = wp_insert_term(
                $category['name'],
                'product_cat',
                array(
                    'parent' => $parentId,
                    'slug'   => sanitize_title($category['name']),
                )
            );

            if (is_wp_error($newCategory)) {
                // Manejar errores en la creación de la categoría
                return null;
            }

            $categoryId = $newCategory['term_id'];
        }

        // Procesar las subcategorías (si existen)
        if (isset($category['children']) && ! empty($category['children'])) {
            $this->processCategory($category['children'], $categoryId);
        }

        return $categoryId;
    }

    private function createUpdateTags($tag_name)
    {

        // Verifica si la etiqueta ya existe
        $term = term_exists($tag_name, 'product_tag');

        if ($term !== 0 && $term !== null) {
            // Si la etiqueta ya existe, devuelve el ID
            return is_array($term) ? $term['term_id'] : $term;
        } else {
            // Si la etiqueta no existe, créala
            $new_term = wp_insert_term($tag_name, 'product_tag');

            if (! is_wp_error($new_term)) {
                // Devuelve el ID de la nueva etiqueta
                return $new_term['term_id'];
            } else {
                // En caso de error, devuelve false
                return false;
            }
        }
    }

    private function createPostmetas($product_id, $meta_array)
    {
        if (! is_array($meta_array) || empty($product_id)) {
            return false;
        }

        foreach ($meta_array as $meta_key => $meta_value) {
            update_post_meta($product_id, $meta_key, $meta_value);
        }

        return true;
    }
}
