<?php

namespace Meliconnect\Meliconnect\Core\Helpers;

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

use Meliconnect\Meliconnect\Core\Models\Template;
use Meliconnect\Meliconnect\Core\Models\UserConnection;

class Helper {


	private static $optionPrefix = 'meliconnect_';

	public static function getOption( $optionName, $default = null ) {
		return get_option( self::$optionPrefix . $optionName, $default );
	}

	public static function setOption( $optionName, $optionValue, $autoLoad = null ) {
		return update_option( self::$optionPrefix . $optionName, $optionValue, $autoLoad );
	}

	public static function deleteOption( $optionName ) {
		return delete_option( self::$optionPrefix . $optionName );
	}

	public static function meliconnectPrintTag( $name, $class ) {
		return '<span class="meliconnect-tag tag ' . $class . '"> ' . $name . '</span>';
	}

	public static function get_active_product_id_by_sku( $sku ) {
		if ( empty( $sku ) ) {
			return null;
		}

		// WooCommerce ya maneja la consulta internamente
		$product_id = wc_get_product_id_by_sku( $sku );

		return $product_id ? (int) $product_id : null;
	}


	public static function canSetSku( $sku, $variation_id = null ) {

        $sku = trim( (string) $sku );

        if ( $sku === '' ) {
            return false;
        }

        $existing_id = wc_get_product_id_by_sku( $sku );

        if ( ! $existing_id ) {
            return true;
        }

        // Permitir si es la misma variación (update)
        if ( $variation_id && (int) $existing_id === (int) $variation_id ) {
            return true;
        }

        return false;
    }






	/**
	 * Method printMessageBox
	 * Generates HTML for a message box to display information based on the parameters provided.
	 *
	 * @param string $text The text to be displayed in the message box.
	 * @param string $alert Optional. The type of alert for the message box (e.g., 'is-info', 'is-warning', etc.). Defaults to 'is-info'.
	 * @param bool   $canDelete Optional. Whether a delete button should be included in the message box. Defaults to false.
	 *
	 * @return string HTML markup for the message box.
	 */
	public static function printMessageBox( $text, $alert = 'is-info', $canDelete = false ) {
		// Escape the text to prevent XSS attacks
		$escapedText = esc_html( $text );
		$alertClass  = esc_attr( $alert );

		if ( empty( $escapedText ) ) {
			return '';
		}

		$deleteButton = $canDelete ? '<button class="delete"></button>' : '';

		$messageBox = sprintf(
			'<div class="meliconnect-notification %s">%s%s</div>',
			$alertClass,
			$deleteButton,
			$escapedText
		);

		return $messageBox;
	}


	public static function getDomainName() {
		/*
		// Verificar si HTTPS está habilitado
		$https  = isset( $_SERVER['HTTPS'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTPS'] ) ) : '';
		$scheme = ( ! empty( $https ) && strtolower( $https ) === 'on' ) ? 'https' : 'http';

		// Obtener solo el dominio sin rutas adicionales
		$host = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';

		// Construir y devolver la URL base
		return "$scheme://$host"; */

		if ( defined( 'WP_CLI' ) || php_sapi_name() === 'cli' ) {
			$_SERVER['HTTPS'] = 'on';
		}

		return get_site_url();
	}

	public static function getMeliconnectOptions( $type = 'all' ) {
		$options = array();

		// Definir prefijos según el tipo
		switch ( $type ) {
			case 'general':
				$prefix = 'meliconnect_general';
				break;
			case 'export':
				$prefix = 'meliconnect_export';
				break;
			case 'import':
				$prefix = 'meliconnect_import';
				break;
			case 'sync':
				$prefix = 'meliconnect_sync';
				break;
			default:
				$prefix = 'meliconnect_';
				break;
		}

		// Recuperar todas las opciones en caché
		$all_options = wp_load_alloptions();

		foreach ( $all_options as $name => $value ) {
			if ( strpos( $name, $prefix ) === 0 ) {
				$options[ $name ] = maybe_unserialize( $value );
			}
		}

		// Agregar 'meliconnect_general_sync_type' si corresponde
		if ( $type === 'export' || $type === 'import' ) {
			$general_sync_type                        = get_option( 'meliconnect_general_sync_type' );
			$options['meliconnect_general_sync_type'] = maybe_unserialize( $general_sync_type );
		}

		return $options;
	}





	public static function getSellersIdsAndNames() {

		$sellers = UserConnection::getUser();

		$sellersList = array();

		if ( is_object( $sellers ) ) {
			$sellers = array( $sellers );
		}

		if ( empty( $sellers ) || ! is_array( $sellers ) ) {
			// return empty array
			return $sellersList;
		}

		foreach ( $sellers as $seller ) {

			// if is not object
			if ( ! is_object( $seller ) ) {
				continue;
			}

			if ( isset( $seller->user_id ) && isset( $seller->nickname ) ) {
				$sellersList[ $seller->user_id ] = $seller->nickname;
			}
		}

		return $sellersList;
	}

	public static function getSellersSelect( $selectName = 'user_id', $addAll = false, $default = null ) {
		$sellers = UserConnection::getUser();

		$output = '';

		if ( empty( $sellers ) ) {
			$output .= '<p>' . esc_html__( 'Please connect a user to your account.', 'meliconnect' ) . '</p>';
		} elseif ( count( $sellers ) === 1 ) {
			$seller  = $sellers[0];
			$output .= '<p>' . esc_html( $seller->nickname ) . '</p>';
			$output .= '<input type="hidden" name="' . esc_attr( $selectName ) . '" value="' . esc_attr( $seller->user_id ) . '">';
		} else {
			$output .= '<div class="meliconnect-control">';
			$output .= '<div class="meliconnect-select">';
			$output .= '<select name="' . esc_attr( $selectName ) . '">';

			if ( $addAll ) {
				$output .= '<option value="all"' . selected( $default, 'all', false ) . '>' . esc_html__( 'All Sellers', 'meliconnect' ) . '</option>';
			}

			foreach ( $sellers as $seller ) {
				$output .= '<option value="' . esc_attr( $seller->user_id ) . '"'
					. selected( $default, $seller->user_id, false ) . '>'
					. esc_html( $seller->nickname ) . '</option>';
			}

			$output .= '</select>';
			$output .= '</div>';
			$output .= '</div>';
		}

		return $output;
	}

	public static function logData( $data, $log_name = 'errors' ) {
		$logger  = new \WC_Logger();
		$context = array( 'source' => 'meliconnect-' . $log_name );

		if ( is_array( $data ) || is_object( $data ) ) {
			$data = wp_json_encode( $data, JSON_PRETTY_PRINT );
		}

		$logger->info( $data, $context );
	}

	public static function getProductsWithMeta( $meta_key ) {
		$args = array(
			'post_type'      => 'product',
			'post_status'    => 'publish',
			'meta_key'       => $meta_key,  // Meta key to filter
			'meta_compare'   => 'EXISTS', // Ensures that the meta key exists
			'fields'         => 'ids',     // Retrieve only product IDs
			'posts_per_page' => -1,
		);

		$query = new \WP_Query( $args );
		return $query->posts; // Returns an array of product IDs
	}

	public static function getPostsWithMetaArray( $meta_key ) {
		$args = array(
			'post_type'      => 'any',
			'post_status'    => 'any',
			'posts_per_page' => -1,
			'fields'         => 'ids',
			'meta_query'     => array(
				array(
					'key'     => $meta_key,
					'compare' => 'EXISTS',
				),
			),
		);

		$posts = get_posts( $args );

		$formatted_results = array();

		if ( $posts ) {
			foreach ( $posts as $post_id ) {
				$value                       = get_post_meta( $post_id, $meta_key, true );
				$formatted_results[ $value ] = $post_id;
			}
		}

		return $formatted_results;
	}

	public static function getPostByMeta( $meta_key, $meta_value ) {
		$args = array(
			'post_type'      => 'any',
			'post_status'    => 'any',
			'posts_per_page' => 1,
			'meta_query'     => array(
				array(
					'key'   => $meta_key,
					'value' => $meta_value,
				),
			),
		);

		$posts = get_posts( $args );

		return ! empty( $posts ) ? $posts[0] : null;
	}


	public static function unlinkProduct( $woo_product_id ) {

        self::maybeDeleteUnusedTemplate( $woo_product_id );

        self::clearProductMeta( $woo_product_id );

        self::clearVariationMeta( $woo_product_id );

        clean_post_cache( $woo_product_id );

        return true;
    }

    private static function maybeDeleteUnusedTemplate( $woo_product_id ) {

        $template_id = get_post_meta(
            $woo_product_id,
            'meliconnect_asoc_template_id',
            true
        );

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

        if ( ! self::isTemplateUsedByOtherProducts( $template_id, $woo_product_id ) ) {

            Template::deleteTemplate( $template_id );
        }
    }

    private static function isTemplateUsedByOtherProducts( $template_id,$excluded_product_id ) {

        global $wpdb;

        $count = $wpdb->get_var(
            $wpdb->prepare(
                "
                SELECT COUNT(post_id)
                FROM {$wpdb->postmeta}
                WHERE meta_key = %s
                AND meta_value = %s
                AND post_id != %d
                ",
                'meliconnect_asoc_template_id',
                $template_id,
                $excluded_product_id
            )
        );

        return intval( $count ) > 0;
    }

    private static function clearProductMeta( $product_id ) {

        foreach ( self::getUnlinkMetaKeys() as $meta_key ) {

            delete_post_meta( $product_id, $meta_key );
        }
    }

    private static function clearVariationMeta( $woo_product_id ) {

        $product = wc_get_product( $woo_product_id );

        if ( ! $product || ! $product->is_type( 'variable' ) ) {
            return;
        }

        foreach ( $product->get_children() as $variation_id ) {

            self::clearProductMeta( $variation_id );
        }
    }

    private static function getUnlinkMetaKeys() {

        return array(

            // Association
            'meliconnect_meli_listing_id',
            'meliconnect_meli_permalink',
            'meliconnect_meli_seller_id',
            'meliconnect_meli_status',
            'meliconnect_meli_sub_status',
            'meliconnect_meli_catalog_product_id',
            'meliconnect_meli_sold_quantity',
            'meliconnect_meli_asoc_variation_id',
            'meliconnect_meli_family_id',
            'meliconnect_meli_family_name',
            'meliconnect_meli_family_is_parent',
            'meliconnect_meli_family_parent_id',
            'meliconnect_meli_user_product_id',

            'meliconnect_meli_image_id',
            'meliconnect_meli_image_url',

            // Template
            'meliconnect_asoc_template_id',
        );
    }

	public static function change_woo_product_status( $product_id, $status = 'draft' ) {

		if ( empty( $product_id ) || ! is_numeric( $product_id ) ) {
			return false;
		}

		$post_data = array(
			'ID'          => $product_id,
			'post_status' => $status,
		);

		$result = wp_update_post( $post_data, true );

		if ( is_wp_error( $result ) ) {
			self::logData( 'Error al cambiar el estado del producto ' . $product_id . ' a borrador: ' . $result->get_error_message() );
			return false;
		}

		return true;
	}


	public static function get_product_by_name( $name ) {
		$args = array(
			'post_type'      => 'product',
			'title'          => trim( $name ),
			'posts_per_page' => 1,
			'post_status'    => 'publish',
		);

		$products = get_posts( $args );

		return ! empty( $products ) ? $products[0] : null;
	}

	public static function get_product_by_sku( $sku ) {
		if ( empty( $sku ) ) {
			return null;
		}

		// WooCommerce ya maneja la query y cache interno
		$product_id = wc_get_product_id_by_sku( $sku );

		return $product_id ? wc_get_product( $product_id ) : null;
	}

	public static function get_woo_active_products($limit = 500, $offset = 0) {

        global $wpdb;

        $sql = "
            SELECT 
                p.ID AS product_id,
                p.post_title AS product_name,
                pm_sku.meta_value AS sku,
                pm_gtin.meta_value AS gtin,
                pm_asoc_template.meta_value AS vinculated_template_id,
                pm_asoc_listing.meta_value AS vinculated_listing_id,
                pm_listing_permalink.meta_value AS meli_permalink,
                pm_listing_seller_id.meta_value AS meli_seller_id,
                p.post_status AS status,

                CASE 
                    WHEN EXISTS (
                        SELECT 1 FROM {$wpdb->posts} v
                        WHERE v.post_parent = p.ID
                        AND v.post_type = 'product_variation'
                    )
                    THEN 'variable'
                    ELSE 'simple'
                END AS product_type

            FROM {$wpdb->posts} p

            LEFT JOIN {$wpdb->postmeta} pm_sku 
                ON p.ID = pm_sku.post_id AND pm_sku.meta_key = '_sku'

            LEFT JOIN {$wpdb->postmeta} pm_gtin 
                ON p.ID = pm_gtin.post_id AND pm_gtin.meta_key = '_global_unique_id'

            LEFT JOIN {$wpdb->postmeta} pm_asoc_template 
                ON p.ID = pm_asoc_template.post_id AND pm_asoc_template.meta_key = 'meliconnect_asoc_template_id'

            LEFT JOIN {$wpdb->postmeta} pm_asoc_listing 
                ON p.ID = pm_asoc_listing.post_id AND pm_asoc_listing.meta_key = 'meliconnect_meli_listing_id'

            LEFT JOIN {$wpdb->postmeta} pm_listing_permalink 
                ON p.ID = pm_listing_permalink.post_id AND pm_listing_permalink.meta_key = 'meliconnect_meli_permalink'

            LEFT JOIN {$wpdb->postmeta} pm_listing_seller_id 
                ON p.ID = pm_listing_seller_id.post_id AND pm_listing_seller_id.meta_key = 'meliconnect_meli_seller_id'

            WHERE p.post_type = 'product'
            AND p.post_status = 'publish'

            LIMIT %d OFFSET %d
            ";

        return $wpdb->get_results(
            $wpdb->prepare($sql, $limit, $offset),
            ARRAY_A
        );
    }



	public static function normalizeString( $string ) {
		// Convertir a minúsculas
		$string = strtolower( $string );

		// Reemplazar caracteres acentuados
		$string = str_replace(
			array( 'á', 'é', 'í', 'ó', 'ú', 'ñ' ),
			array( 'a', 'e', 'i', 'o', 'u', 'n' ),
			$string
		);

		// Reemplazar espacios y guiones por una cadena vacía
		$string = str_replace( array( ' ' ), '-', $string );

		return $string;
	}


	public static function get_woo_active_products_count() {
		$count_posts = wp_count_posts( 'product' );
		return isset( $count_posts->publish ) ? (int) $count_posts->publish : 0;
	}

	public static function change_meli_listing_status( $product_id, $status ) {
		// Obtener IDs asociados
		$asoc_listing = get_post_meta( $product_id, 'meliconnect_meli_listing_id', true );
		$seller_id    = get_post_meta( $product_id, 'meliconnect_meli_seller_id', true );

		// Validar si los datos requeridos están presentes
		if ( ! $asoc_listing || ! $seller_id ) {
			self::logData( "Error changing product {$product_id} status: 'asoc_listing' or 'seller_id' not found." );
			return false;
		}

		// Obtener datos del vendedor
		$seller_data = UserConnection::getUser( $seller_id );
		if ( ! $seller_data ) {
			self::logData( "Error changing product {$product_id} status: Seller data not found for seller_id {$seller_id}." );
			return false;
		}

		// Crear instancia de MeliconMeli
		$meli = new MeliconMeli( $seller_data->app_id, $seller_data->secret_key, $seller_data->access_token );

		// Actualizar el estado del producto en MercadoLibre
		$response = $meli->put_v2( "/items/{$asoc_listing}", array( 'status' => $status ), array( 'access_token' => $seller_data->access_token ) );

		// Verificar el código de respuesta HTTP
		if ( $response['httpCode'] !== 200 ) {
			self::logData( "Error changing status of Listing {$asoc_listing} for product {$product_id}: {$response['body']}" );
			return false;
		}

		// Verificar si el estado se actualizó correctamente
		if ( isset( $response['body']->status ) && $response['body']->status === $status ) {
            self::logData( "Listing {$asoc_listing} status was successfully updated for product {$product_id}." );
			return $response['body'];
		}

		self::logData( "Unexpected error: Listing {$asoc_listing} status was not correctly updated for product {$product_id}." );
		return false;
	}

	public static function load_partial( $template_path, $data = array(), $once = true, $print = true ) {
		$full_path = MELICONNECT_PLUGIN_ROOT . $template_path;

		if ( ! file_exists( $full_path ) ) {
			/* translators: %s is the template path that could not be found. */
			printf( esc_html__( 'View: %s not found.', 'meliconnect' ), esc_html( $template_path ) );
			return;
		}

		extract( $data ); // Extract variables for use in the template

		ob_start();
		if ( $once ) {
			include_once $full_path;
		} else {
			include $full_path;
		}
		$output = ob_get_clean();

		if ( $print ) {
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			echo $output;
		} else {
			return $output;
		}
	}

	public static function handleDismissNotifications() {
		global $wpdb;

		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'meliconnect_notifications_nonce' ) ) {
			wp_send_json_error( esc_html__( 'Invalid nonce', 'meliconnect' ) );
			return;
		}
		$table_name = $wpdb->prefix . 'meliconnect_notifications';

		$notification_id = isset( $_POST['notificationId'] )
		? sanitize_text_field( wp_unslash( $_POST['notificationId'] ) )
		: '';

		if ( empty( $notification_id ) ) {
			wp_send_json_error( array( 'message' => 'Notification ID missing' ) );
		}

		// hide all
		if ( $notification_id === 'all' ) {

			$updated = $wpdb->update(
				$table_name,
				array(
					'status'     => 'hide',
					'updated_at' => current_time( 'mysql' ),
				),
				array( 'status' => 'show' )  // Solo las visibles
			);

			wp_send_json_success(
				array(
					'notification_id' => 'all',
					'updated'         => $updated,
				)
			);
		}

		// hide single
		$updated = $wpdb->update(
			$table_name,
			array(
				'status'     => 'hide',
				'updated_at' => current_time( 'mysql' ),
			),
			array( 'unique_id' => $notification_id )
		);

		wp_send_json_success(
			array(
				'notification_id' => $notification_id,
				'updated'         => $updated,
			)
		);
	}

	public static function handleLoadMeliCategories() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'meliconnect_load_meli_categories_nonce' ) ) {
			wp_send_json_error( esc_html__( 'Invalid nonce', 'meliconnect' ) );
			return;
		}

		$category_id = isset( $_POST['category_id'] ) ? sanitize_text_field( wp_unslash( $_POST['category_id'] ) ) : null;
		$seller_id   = isset( $_POST['seller_id'] ) ? sanitize_text_field( wp_unslash( $_POST['seller_id'] ) ) : null;

		if ( empty( $seller_id ) ) {
			wp_send_json_error( array( 'message' => 'Seller ID is required' ) );
			wp_die();
		}

		$seller_data = UserConnection::getUser( $seller_id );

		if ( ! $seller_data ) {
			wp_send_json_error( array( 'message' => 'Seller data not found' ) );
			wp_die();
		}

		$meli           = new MeliconMeli( $seller_data->app_id, $seller_data->secret_key, $seller_data->access_token );
		$categories     = array();
		$path_from_root = array();
		$category_name  = '';

		if ( empty( $category_id ) ) {
			$response   = $meli->get( '/sites/' . $seller_data->site_id . '/categories', array( 'access_token' => $seller_data->access_token ) );
			$categories = $response['body'];
		} else {
			$response = $meli->get( '/categories/' . $category_id, array( 'access_token' => $seller_data->access_token ) );
			if ( isset( $response['body']->children_categories ) && ! empty( $response['body']->children_categories ) ) {
				$categories = $response['body']->children_categories;
			}
			if ( isset( $response['body']->path_from_root ) && ! empty( $response['body']->path_from_root ) ) {
				$path_from_root = $response['body']->path_from_root;
			}

			$category_name = $response['body']->name;
		}

		if ( $response['httpCode'] !== 200 || empty( $response['body'] ) ) {
			wp_send_json_error(
				array(
					'message'  => 'Error fetching categories',
					'response' => $response,
				)
			);
			wp_die();
		}

		// Datos para la vista
		$data = array(
			'categories'     => $categories,
			'path_from_root' => $path_from_root,
			'category_name'  => $category_name,
		);

		// Load category options from the partial view
		$options = self::load_partial( 'includes/Core/Views/Partials/meliconnect_product_edit_category_options.php', array( 'categories' => $categories ), true, false );

		// Cargar la vista y obtener el HTML generado
		$path_from_route_html = self::load_partial( 'includes/Core/Views/Partials/meliconnect_product_edit_category_path.php', $data, true, false );

		// Responder con JSON
		wp_send_json_success(
			array(
				'options'              => $options,
				'path_from_route_html' => $path_from_route_html,
				'path_from_route_json' => $path_from_root,
				'category_name'        => $category_name,
			)
		);

		wp_die();
	}


	public static function handleLoadMeliCategories_OLD() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'meliconnect_load_meli_categories_nonce' ) ) {
			wp_send_json_error( esc_html__( 'Invalid nonce', 'meliconnect' ) );
			return;
		}

		$category_id = isset( $_POST['category_id'] ) ? sanitize_text_field( wp_unslash( $_POST['category_id'] ) ) : null;
		$seller_id   = isset( $_POST['seller_id'] ) ? sanitize_text_field( wp_unslash( $_POST['seller_id'] ) ) : null;

		if ( empty( $seller_id ) ) {
			wp_send_json_error( array( 'message' => 'Seller ID is required' ) );
			wp_die();
		}

		$seller_data = UserConnection::getUser( $seller_id );

		if ( ! $seller_data ) {
			wp_send_json_error( array( 'message' => 'Seller data not found' ) );
			wp_die();
		}

		$meli           = new MeliconMeli( $seller_data->app_id, $seller_data->secret_key, $seller_data->access_token );
		$categories     = array();
		$path_from_root = array();
		$category_name  = '';

		if ( empty( $category_id ) ) {
			$response   = $meli->get( '/sites/' . $seller_data->site_id . '/categories', array( 'access_token' => $seller_data->access_token ) );
			$categories = $response['body'];
		} else {
			$response = $meli->get( '/categories/' . $category_id, array( 'access_token' => $seller_data->access_token ) );
			if ( isset( $response['body']->children_categories ) && ! empty( $response['body']->children_categories ) ) {
				$categories = $response['body']->children_categories;
			}
			if ( isset( $response['body']->path_from_root ) && ! empty( $response['body']->path_from_root ) ) {
				$path_from_root = $response['body']->path_from_root;
			}

			$category_name = $response['body']->name;
		}

		if ( $response['httpCode'] !== 200 || empty( $response['body'] ) ) {
			wp_send_json_error(
				array(
					'message'  => 'Error fetching categories',
					'response' => $response,
				)
			);
			wp_die();
		}

		// Generar opciones para el select
		if ( ! empty( $categories ) ) {
			$options = '<option value="">' . esc_html__( 'Select a category', 'meliconnect' ) . '</option>';
			foreach ( $categories as $category ) {
				$options .= '<option value="' . esc_attr( $category->id ) . '">' . esc_html( $category->name ) . '</option>';
			}
		} else {
			$options = null;
		}

		$path_from_route_html = '<div class="options_group"><p class="form-field"><label class="meliconnect-selected-category-span">' . esc_html__( 'Category Root', 'meliconnect' ) . ': </label>';

		// Generar HTML para path_from_root
		$path_from_route_html .= '<nav class="description meliconnect-is-inline-block meliconnect-category-path meliconnect-breadcrumb meliconnect-has-succeeds-separator meliconnect-ml-4" aria-label="breadcrumbs"><ul>';

		foreach ( $path_from_root as $parent ) {
			$path_from_route_html .= '<li><a href="/" class="meliconnect-category-link" data-category-id="' . esc_attr( $parent->id ) . '">' . esc_html( $parent->name ) . '</a></li>';
		}

		if ( ! empty( $path_from_root ) ) {
			$path_from_route_html .= '<li><a href="" class="meliconnect-category-link" data-category-id="0"><i class="fa fa-times meliconnect-ml-2" aria-hidden="true"></i></a></li>';
		}

		$path_from_route_html .= '</ul></nav></p></div>';

		// Devolver ambos valores como JSON
		wp_send_json_success(
			array(
				'options'              => $options,
				'path_from_route_html' => $path_from_route_html,
				'path_from_route_json' => $path_from_root,
				'category_name'        => $category_name,
			)
		);

		wp_die();
	}

	public static function handleUpdateMeliCategory() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'meliconnect_update_meli_category_nonce' ) ) {
			wp_send_json_error( esc_html__( 'Invalid nonce', 'meliconnect' ) );
			return;
		}

		$category_id    = isset( $_POST['category_id'] ) ? sanitize_text_field( wp_unslash( $_POST['category_id'] ) ) : null;
		$woo_product_id = isset( $_POST['woo_product_id'] ) ? sanitize_text_field( wp_unslash( $_POST['woo_product_id'] ) ) : null;
		$product_title  = isset( $_POST['product_title'] ) ? sanitize_text_field( wp_unslash( $_POST['product_title'] ) ) : null;
		$seller_meli_id = isset( $_POST['seller_meli_id'] ) ? sanitize_text_field( wp_unslash( $_POST['seller_meli_id'] ) ) : null;
		$category_tree  = isset( $_POST['category_tree'] ) ? sanitize_text_field( wp_unslash( $_POST['category_tree'] ) ) : null;
		$category_name  = isset( $_POST['category_name'] ) ? sanitize_text_field( wp_unslash( $_POST['category_name'] ) ) : null;

		if ( empty( $category_id ) || empty( $woo_product_id ) ) {
			wp_send_json_error( array( 'message' => 'Category ID or product ID is required' ) );
			wp_die();
		}

		$template_id = get_post_meta( $woo_product_id, 'meliconnect_asoc_template_id', true );

		if ( empty( $template_id ) ) {

			$template_data = array(
				'used_by'           => 'product',
				'used_asoc_id'      => $woo_product_id,
				'seller_meli_id'    => $seller_meli_id,
				'name'              => $product_title,
				'short_description' => 'Template created on edit product page',
				'category_id'       => $category_id,
				'category_name'     => $category_name,
				'category_path'     => $category_tree,
				'status'            => 1,
			);

			$template_id = Template::createUpdateTemplate( $template_data );

			if ( ! $template_id ) {
				wp_send_json_error( array( 'message' => 'Error creating template' ) );
				wp_die();
			}

			update_post_meta( $woo_product_id, 'meliconnect_asoc_template_id', $template_id );
			update_post_meta( $woo_product_id, 'meliconnect_meli_seller_id', $seller_meli_id );
			update_post_meta( $woo_product_id, 'meliconnect_meli_category_id', $category_id );

			wp_send_json_success(
				array(
					'message'     => 'Template created successfully',
					'template_id' => $template_id,
				)
			);
			wp_die();
		}

		$template_data = Template::deleteCategoryRelatedDataFromTemplate( $template_id );

		if ( $template_data ) {
			Template::updateTemplateData( $template_id, array( 'category_id' => $category_id ) );

			wp_send_json_success( array( 'message' => 'Category updated successfully' ) );
		}
	}

    public static function meliconnect_find_variation_by_meli_asoc_variation_id($meliVariationId)
    {
        $args = [
            'post_type'  => 'product_variation',
            'meta_query' => [
                [
                    'key'   => 'meliconnect_meli_asoc_variation_id',
                    'value' => $meliVariationId,
                ]
            ],
            'fields' => 'ids',
            'posts_per_page' => 1
        ];

        $query = new \WP_Query($args);

        return $query->have_posts() ? $query->posts[0] : null;
    }

    public static function meliconnect_find_product_by_listing_id( string $listingId, $logChannel='sync_product_callback' ): ?int
    {
        global $wpdb;

        // 1. Buscar producto padre
        $postId = $wpdb->get_var(
            $wpdb->prepare(
                "
                SELECT post_id
                FROM {$wpdb->postmeta}
                WHERE meta_key = 'meliconnect_meli_listing_id'
                AND meta_value = %s
                LIMIT 1
                ",
                $listingId
            )
        );

        if ( $postId ) {
            return (int) $postId;
        }

        Helper::logData(
            'Listing no encontrado como producto. Buscando como variación: ' . $listingId,
            $logChannel
        );

        // 2. Buscar variación
        $variationId = $wpdb->get_var(
            $wpdb->prepare(
                "
                SELECT p.ID
                FROM {$wpdb->posts} p
                INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
                WHERE pm.meta_key = 'meliconnect_meli_asoc_variation_id'
                AND pm.meta_value = %s
                AND p.post_type = 'product_variation'
                LIMIT 1
                ",
                $listingId
            )
        );

        if ( $variationId ) {

            $parentId = $wpdb->get_var(
                $wpdb->prepare(
                    "
                    SELECT post_parent
                    FROM {$wpdb->posts}
                    WHERE ID = %d
                    LIMIT 1
                    ",
                    $variationId
                )
            );

            if ( $parentId ) {
                Helper::logData(
                    'Variación encontrada. Parent product ID: ' . $parentId,
                    $logChannel
                );

                return (int) $parentId;
            }

            Helper::logData(
                'Variación encontrada pero sin parent válido. Variation ID: ' . $variationId,
                $logChannel
            );
        } else {
            Helper::logData(
                'Variación no encontrada.',
                $logChannel
            );
        }

        return null;
    }

    public static function meliconnect_convert_weight_to_store_unit( $grams ) {
        $unit = get_option( 'woocommerce_weight_unit', 'kg' );

        return match ( $unit ) {
            'kg' => $grams / 1000,
            'g'  => $grams,
            'lbs'=> $grams * 0.00220462,
            'oz' => $grams * 0.035274,
            default => $grams,
        };
    }

    public static function meliconnect_convert_dimension_to_store_unit( $cm ) {
        $unit = get_option( 'woocommerce_dimension_unit', 'cm' );

        return match ( $unit ) {
            'cm' => $cm,
            'm'  => $cm / 100,
            'mm' => $cm * 10,
            'in' => $cm * 0.393701,
            default => $cm,
        };
    }
}
