<?php

namespace Meliconnect\Meliconnect\Modules\Importer\Controllers;

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

use Meliconnect\Meliconnect\Core\Helpers\Helper;
use Meliconnect\Meliconnect\Core\Helpers\MeliconMeli;
use Meliconnect\Meliconnect\Core\Interfaces\ControllerInterface;
use Meliconnect\Meliconnect\Core\Models\Process;
use Meliconnect\Meliconnect\Core\Models\UserConnection;
use Meliconnect\Meliconnect\Modules\Importer\Models\UserListingToImport;

class ImportController implements ControllerInterface {



	public function __construct() {}

	public function getData() {

        $import_process  = Process::getCurrentProcessData('custom-import');
        $delete_process  = Process::getCurrentProcessData('delete-products-and-images');

        $import_finished = Process::getCurrentProcessData('custom-import', ['finished']);
        $delete_finished = Process::getCurrentProcessData('delete-products-and-images', ['finished']);

        // Elegir el proceso activo (prioridad: el que esté en processing)
        $current_process = null;
        $current_finished = null;

        if (!empty($import_process) && $import_process->status === 'processing') {
            $current_process = $import_process;
        } elseif (!empty($delete_process) && $delete_process->status === 'processing') {
            $current_process = $delete_process;
        }

        if (!$current_process) {
            if (!empty($import_finished)) {
                $current_finished = $import_finished;
            } elseif (!empty($delete_finished)) {
                $current_finished = $delete_finished;
            }
        }

        return [
            'current_process'  => $current_process,
            'current_finished' => $current_finished,
            'execution_time'   => Process::calculateExecutionTime($current_process),
            'meli_user_listings_to_import_count' => UserListingToImport::get_user_listings_count(),
            'meli_user_listings_active_to_import_count' => UserListingToImport::get_user_listings_count_by_status('active'),
            'woo_total_active_products' => Helper::get_woo_active_products_count(),
            'woo_total_vinculated_products' => count(Helper::getProductsWithMeta('meliconnect_meli_listing_id')),
        ];
    }




	/* START HANDLE AJAX METHODS */

    public static function handleProcessActionImport() {

        if (
            ! isset( $_POST['nonce'] ) ||
            ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'process_action_nonce' )
        ) {
            wp_send_json_error( esc_html__( 'Invalid nonce', 'meliconnect' ) );
        }

        if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
            wp_send_json_error( esc_html__( 'You do not have permission', 'meliconnect' ) );
        }

        $action = sanitize_text_field( wp_unslash( $_POST['action_to_do'] ?? '' ) );
        $selected_ids = sanitize_text_field( wp_unslash( $_POST['selected_ids'] ?? '' ) );

        

        $filters = [];
        if ( ! empty( $_POST['filters'] ) ) {
            parse_str( ltrim( $_POST['filters'], '?' ), $filters );
        }

        $selected_ids_arr = ! empty( $selected_ids ) ? explode( ',', $selected_ids ) : [];

        

        // 🔥 PRIORIDAD: seleccionados > filtros
        if ( ! empty( $selected_ids_arr ) ) {
            $items = UserListingToImport::get_user_listings_to_import( $selected_ids_arr );
        } else {
            $items = UserListingToImport::get_user_listings_to_import_filtered( $filters );
        }

        if ( empty( $items ) ) {
            wp_send_json_error( esc_html__( 'No items found', 'meliconnect' ) );
        }

        switch ( $action ) {

            case 'import-selected':
                self::runImportProcess( $items );
                break;
            case 'clear-matches':
                Helper::logData( 'Clearing matches', 'import-actions' );
                UserListingToImport::clear_matches( (!empty($selected_ids_arr)) ? $selected_ids_arr : 'all' );
                break;

            case 'match-items-products-by-name':
            case 'match-items-products-by-sku':
                Helper::logData( 'Matching items with products by ' . ( $action === 'match-items-products-by-name' ? 'name' : 'sku' ), 'import-actions' );
                foreach ( $items as $user_listing ) {

                    $product = ( $action === 'match-items-products-by-name' )
                        ? Helper::get_product_by_name( $user_listing->meli_listing_title )
                        : Helper::get_product_by_sku( $user_listing->meli_sku );

                    if ( $product ) {
                        UserListingToImport::update_vinculated_product(
                            $user_listing->id,
                            $product->ID,
                            $action === 'match-items-products-by-name' ? 'name' : 'sku'
                        );
                    }
                }
                break;

            case 'desvinculate-items-products':
            case 'delete-items-in-woocommerce':

                $delete = $action === 'delete-items-in-woocommerce';

                foreach ( $items as $item ) {

                    if ( empty( $item->vinculated_product_id ) ) continue;

                    Helper::unlinkProduct( $item->vinculated_product_id );
                    UserListingToImport::unlink_woo_product( $item->meli_listing_id );

                    if ( $delete ) {
                        Helper::change_woo_product_status( $item->vinculated_product_id, 'trash' );
                    }
                }
                break;

            case 'delete-items-in-woocommerce-and-images':

                $ids = array_column( $items, 'meli_listing_id' );
                self::initDeleteProcess( $ids );
                break;

            default:
                wp_send_json_error( esc_html__( 'Invalid action', 'meliconnect' ) );
        }

        wp_send_json_success();
    }

	public static function handleClearSelectedProductsMatch() {

		// Verificar nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'clear_selected_matches_nonce' ) ) {
			wp_send_json_error( esc_html__( 'Invalid nonce', 'meliconnect' ) );
			return;
		}

		// Verificar permisos
		if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action', 'meliconnect' ) );
			return;
		}

		// Obtener IDs seleccionados y sanitizar
		$meli_listings_ids = isset( $_POST['meli_listings_ids'] )
			? array_map( 'sanitize_text_field', wp_unslash( $_POST['meli_listings_ids'] ) )
			: null;

		if ( ! $meli_listings_ids || ! is_array( $meli_listings_ids ) ) {
			wp_send_json_error( esc_html__( 'Invalid data', 'meliconnect' ) );
			return;
		}

		// Limpiar matches
		$cleared = UserListingToImport::clear_matches( $meli_listings_ids );

		if ( $cleared ) {
			wp_send_json_success();
		} else {
			wp_send_json_error( esc_html__( 'Something went wrong', 'meliconnect' ) );
		}
	}


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

		if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action', 'meliconnect' ) );
			return;
		}

		$user_listing_id = isset( $_POST['user_listing_id'] ) ? sanitize_text_field( wp_unslash( $_POST['user_listing_id'] ) ) : null;
		$woo_product_id  = isset( $_POST['woo_product_id'] ) ? sanitize_text_field( wp_unslash( $_POST['woo_product_id'] ) ) : null;

		if ( ! $user_listing_id || ! $woo_product_id ) {
			wp_send_json_error( esc_html__( 'Invalid data', 'meliconnect' ) );
			return;
		}

		$applied_match = UserListingToImport::update_vinculated_product( $user_listing_id, $woo_product_id, 'manual' );

		if ( $applied_match ) {
			wp_send_json_success();
		} else {
			wp_send_json_error( esc_html__( 'Error applying match', 'meliconnect' ) );
		}
	}

	public static function handleMatchListingsWithProducts() {

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

		if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action', 'meliconnect' ) );
			return;
		}

		Helper::logData( '------ START Match listings with products ------', 'import-actions' );

		$match_by = isset( $_POST['match_by'] ) ? sanitize_text_field( wp_unslash( $_POST['match_by'] ) ) : 'name';

		Helper::logData( 'Match by: ' . $match_by . '', 'import-actions' );

		$user_listings_to_import = UserListingToImport::get_not_vinculated_user_listings_to_import();

		if ( ! $user_listings_to_import ) {
			Helper::logData( 'No listings to import with pending vinculation', 'import-actions' );
			Helper::logData( '------ END Match listings with products ------', 'import-actions' );
			wp_send_json_error( esc_html__( 'No listings to import with pending vinculation', 'meliconnect' ) );
			return;
		}
		// Helper::logData('Listings to import: ' . wp_json_encode($user_listings_to_import) , 'import');

		foreach ( $user_listings_to_import as $user_listing ) {
			$product = null;

			if ( $match_by == 'name' ) {
				Helper::logData( 'NAME to find: ' . $user_listing->meli_listing_title . '', 'import-actions' );
				$product = Helper::get_product_by_name( $user_listing->meli_listing_title );
			}

			if ( $match_by == 'sku' ) {
				Helper::logData( 'SKU to find: ' . $user_listing->meli_sku . '', 'import-actions' );
				$product = Helper::get_product_by_sku( $user_listing->meli_sku );
			}

			if ( $product ) {
				Helper::logData( 'Product found: ' . $product->post_title . '', 'import-actions' );

				UserListingToImport::update_vinculated_product( $user_listing->id, $product->ID, $match_by );
			} else {
				Helper::logData( 'Product NOT found by name or sku.', 'import-actions' );
			}
		}
		Helper::logData( '------ END Match listings with products ------', 'import-actions' );
		wp_send_json_success( esc_html__( 'Listings matched with products', 'meliconnect' ) );
	}

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

		if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action', 'meliconnect' ) );
			return;
		}

		$clear = UserListingToImport::clear_matches();

		if ( ! $clear ) {
			wp_send_json_error( esc_html__( 'Problem clearing matches', 'meliconnect' ) );
			return;
		}

		wp_send_json_success( esc_html__( 'Matches cleared', 'meliconnect' ) );
	}

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

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

		if ( ! $process_id ) {
			wp_send_json_error( esc_html__( 'Invalid data', 'meliconnect' ) );
			return;
		}

		$progress_data = Process::getProcessProgress( $process_id );

		if ( ! $progress_data ) {
			wp_send_json_error( esc_html__( 'Process not found', 'meliconnect' ) );
			return;
		}

		wp_send_json_success( $progress_data );
	}

	public static function handleGetMeliUserListings() {
		// Verifica el nonce
		$nonce = filter_input( INPUT_POST, 'nonce', FILTER_SANITIZE_STRING );
		if ( ! $nonce || ! wp_verify_nonce( $nonce, 'get_meli_user_listings_nonce' ) ) {
			wp_send_json_error( esc_html__( 'Invalid nonce', 'meliconnect' ) );
			return;
		}

		// Verifica permisos
		if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action', 'meliconnect' ) );
			return;
		}

		// Sanitiza y valida user_id
		$user_id = filter_input( INPUT_POST, 'user_id', FILTER_VALIDATE_INT );
		if ( ! $user_id || $user_id <= 0 ) {
			wp_send_json_error( esc_html__( 'Invalid user ID', 'meliconnect' ) );
			return;
		}

		$meli_user = UserConnection::getUser( $user_id );
		if ( ! $meli_user ) {
			wp_send_json_error( esc_html__( 'User not found', 'meliconnect' ) );
			return;
		}

		$meli_user_listings_ids = self::getMeliUserLisntingIds( $meli_user );

		if ( $meli_user_listings_ids === false ) {
			wp_send_json_error( esc_html__( 'There was an error getting the user listings. Check connections page.', 'meliconnect' ) );
			return;
		}

		UserListingToImport::create_or_skip_meli_user_listings_ids_to_import( $meli_user, $meli_user_listings_ids );

		$listings_extra_data = self::multiGetListingsData( $meli_user, $meli_user_listings_ids );
		UserListingToImport::update_meli_user_listings_extra_data_to_import( $listings_extra_data );
	}

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

		// Verifica los permisos del usuario
		if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action', 'meliconnect' ) );
			return;
		}

		UserListingToImport::reset_meli_user_listings();

		wp_send_json_success();
	}

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

		// Verifica los permisos del usuario
		if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action', 'meliconnect' ) );
			return;
		}

         $filters = [];

        if ( ! empty( $_POST['filters'] ) ) {
            parse_str( ltrim( $_POST['filters'], '?' ), $filters );
        }

       

		self::initImportProcessFiltered($filters);

		wp_send_json_success();
	}

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

		// Verifica los permisos del usuario
		if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action', 'meliconnect' ) );
			return;
		}

		// UserListingToImport::pause_import_process();

		wp_send_json_success();
	}

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

		// Verifica los permisos del usuario
		if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action', 'meliconnect' ) );
			return;
		}

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

		if ( ! $process_id ) {
			wp_send_json_error( esc_html__( 'Invalid data', 'meliconnect' ) );
			return;
		}

        UserListingToImport::update_processing_listings('pending');

		update_option( 'meliconnect_import_cancel_requested', true );

		sleep( 2 );

		Process::cancelProcess( $process_id );

		// unlock custom import process cron
		delete_option( 'meliconnect_custom_import_lock' );

		wp_send_json_success();
	}

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

		// Verifica los permisos del usuario
		if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action', 'meliconnect' ) );
			return;
		}

		$process_types = [
            'custom-import',
            'delete-products-and-images',
        ];

        $deleted = false;

        foreach ($process_types as $type) {
            if (Process::cancelFinishedProcesses($type)) {
                $deleted = true;
            }
        }

        // limpiar locks
        delete_option('meliconnect_custom_import_lock');
        delete_option('meliconnect_delete_worker_lock');

        if ( ! $deleted ) {
            wp_send_json_error();
        }

        wp_send_json_success();
	}

	


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

		// Verifica los permisos del usuario
		if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action', 'meliconnect' ) );
			return;
		}

		$wooProductId  = isset( $_POST['wooProductId'] ) ? sanitize_text_field( wp_unslash( $_POST['wooProductId'] ) ) : '';
		$meliListingId = isset( $_POST['meliListingId'] ) ? sanitize_text_field( wp_unslash( $_POST['meliListingId'] ) ) : '';

		if ( ! $wooProductId || ! $meliListingId ) {
			wp_send_json_error( esc_html__( 'Invalid data', 'meliconnect' ) );
		}

		Helper::unlinkProduct( $wooProductId );

		if ( ! empty( $meliListingId ) ) {
			UserListingToImport::unlink_woo_product( $meliListingId );
		}

		wp_send_json_success( array( 'message' => esc_html__( 'Product desvinculated successfully.', 'meliconnect' ) ) );
	}

	public static function handleGetMatchAvailableProducts() {

		if ( ! isset( $_GET['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['nonce'] ) ), 'get_match_available_products_nonce' ) ) {
			wp_send_json_error( esc_html__( 'Invalid nonce', 'meliconnect' ) );
			return;
		}

		// Verifica los permisos del usuario
		if ( ! current_user_can( 'meliconnect_manage_plugin' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to perform this action', 'meliconnect' ) );
			return;
		}

		global $wpdb;

		$product_type = isset( $_GET['productType'] ) ? sanitize_text_field( wp_unslash( $_GET['productType'] ) ) : '';

		// Consulta para obtener productos de WooCommerce que no tienen el postmeta 'meliconnect_meli_listing_id'

		$results = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT p.ID, p.post_title, p.post_type, p.post_status
                FROM {$wpdb->posts} p
                LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = 'meliconnect_meli_listing_id'
                WHERE pm.post_id IS NULL
                AND p.post_type = 'product'
                ORDER BY p.post_title ASC"
			),
			ARRAY_A
		);

		// Construir la respuesta HTML para Select2
		$options = '';
		foreach ( $results as $product ) {
			$product_id  = $product['ID'];
			$product_obj = wc_get_product( $product_id );
			/*
			$product_type = $product_obj->get_type();
			echo PHP_EOL . '-------------------- product type --------------------' . PHP_EOL;
			echo '<pre>' . wp_json_encode( $product_id) . '</pre>';
			echo '<pre>' . wp_json_encode( $product_type) . '</pre>';
			echo PHP_EOL . '-------------------  FINISHED  ---------------------' . PHP_EOL; */
			if ( $product_obj->is_type( $product_type ) ) {
				if ( $product_type === 'simple' ) {
					$sku   = $product_obj->get_sku();
					$price = $product_obj->get_price();
					$stock = $product_obj->get_stock_quantity();

					$options .= sprintf(
						'<option value="%d" data-status="%s" data-stock="%d" data-price="%s" data-type="%s" data-sku="%s">%s</option>',
						esc_attr( $product_id ),
						esc_attr( $product['post_status'] ),
						esc_attr( $stock ),
						esc_attr( $price ),
						esc_attr( $product_type ),
						esc_attr( $sku ),
						esc_html( $product['post_title'] )
					);
				} elseif ( $product_type === 'variable' ) {
					$variations      = $product_obj->get_available_variations();
					$variations_data = array();

					foreach ( $variations as $variation ) {
						$variations_data[] = array(
							'variation_id' => $variation['variation_id'],
							'sku'          => $variation['sku'],
							'price'        => $variation['display_price'],
							'stock'        => $variation['max_qty'],
						);
					}

					$options .= sprintf(
						'<option value="%d" data-status="%s" data-type="%s" data-variations="%s">%s</option>',
						esc_attr( $product_id ),
						esc_attr( $product['post_status'] ),
						esc_attr( $product_type ),
						esc_attr( wp_json_encode( $variations_data ) ),
						esc_html( $product['post_title'] )
					);
				}
			}
		}

		if ( empty( $options ) ) {
			wp_send_json_success( esc_html__( 'No products found', 'meliconnect' ) );
		} else {
			wp_send_json_success( array( 'options' => $options ) );
		}
	}

	/* START CUSTOM METHODS */

    public static function initDeleteProcess( $meli_listings_ids = [] ) {

        $items = UserListingToImport::get_user_listings_to_import( $meli_listings_ids );

        return self::runDeleteProcess( $items );
    }

	public static function initImportProcess( $meli_listings_ids = [] ) {

        $items = UserListingToImport::get_user_listings_to_import( $meli_listings_ids );

        return self::runImportProcess( $items );
    }


    public static function initImportProcessFiltered( array $filters ) {

        $items = UserListingToImport::get_user_listings_to_import_filtered( $filters );

        if ( empty( $items ) ) {
            Helper::logData( 'No items found to import', 'initImportProcessFiltered' );
            return false;
        }

        return self::runImportProcess( $items );
    }


    /**
     * Ejecuta el proceso de importación
     */
    private static function runImportProcess( $items ) {

        if ( empty( $items ) ) {
            return false;
        }

        $formattedItems = array_map(
            function ( $item ) {
                return [
                    'meli_user_id'    => $item->meli_user_id,
                    'meli_listing_id' => $item->meli_listing_id,
                    'woo_product_id'  => $item->vinculated_product_id,
                    'template_id'     => $item->vinculated_template_id,
                    'process_status'  => 'pending',
                ];
            },
            $items
        );

        $process_id = Process::createProcess( 'custom-import', $formattedItems );

        if ( ! $process_id ) {
            return false;
        }

        UserListingToImport::update_user_listing_item_import_status(
            array_column( $items, 'meli_listing_id' ),
            'processing'
        );

        // Limpiar flag de cancelación
        delete_option( 'meliconnect_import_cancel_requested' );

        
        // Lanzar worker
        wp_schedule_single_event(
            time() + 10,
            'meliconnect_process_user_custom_import',
            [ $process_id ]
        );
        //Helper::logData( 'Process ID: ' . $process_id, 'initImportProcess' );

        return true;
    }

    private static function runDeleteProcess( $items ) {

        if ( empty( $items ) ) {
            return false;
        }

        $formattedItems = array_map(
            function ( $item ) {
                return [
                    'meli_user_id'    => $item->meli_user_id,
                    'meli_listing_id' => $item->meli_listing_id,
                    'woo_product_id'  => $item->vinculated_product_id,
                    'process_status'  => 'pending',
                ];
            },
            $items
        );

        $process_id = Process::createProcess( 'delete-products-and-images', $formattedItems );


        if ( ! $process_id ) {
            return false;
        }

        UserListingToImport::update_user_listing_item_import_status(
            array_column( $items, 'meli_listing_id' ),
            'processing'
        );

        wp_schedule_single_event(
            time() + 10,
            'meliconnect_process_delete_products_and_images',
            [ $process_id ]
        );

        return true;
    }

	public static function multiGetListingsData( $seller_data, $meli_user_listings_ids ) {
		$meli_user_listings_ids_chunk = array_chunk( $meli_user_listings_ids, 20 );

		Helper::logData( 'Getting imported products extra data from seller: ' . $seller_data->user_id, 'import-actions');

		$base_url = 'items?ids=';

		$meli_user_listings_with_data = array();
		$listings_with_errors         = array();

		foreach ( $meli_user_listings_ids_chunk as $chunk ) {

			$current_url = $base_url . implode( ',', $chunk ) . '&attributes=id,site_id,title,seller_id,category_id,price,initial_quantity,available_quantity,sold_quantity,listing_type_id,condition,permalink,variations,domain_id,channels,status,sub_status,family_id,family_name,user_product_id,seller_custom_field';

			$listingsWithExtraData = MeliconMeli::getWithHeader( $current_url, $seller_data->access_token );

			if ( ! isset( $listingsWithExtraData['body'] ) || $listingsWithExtraData['httpCode'] !== 200 ) {
				Helper::logData( 'Error getting chunk extra data in listings: ' . implode( ',', $chunk ), 'import-actions');

				Helper::logData( 'ListingsWithExtraData: ' . wp_json_encode( $listingsWithExtraData, JSON_PRETTY_PRINT ), 'import-actions');

				Helper::logData( 'Access Token: ' . $seller_data->access_token, 'import-actions');
				Helper::logData( 'current_url: ' . $current_url, 'import-actions');

				continue;
			}

			foreach ( $listingsWithExtraData['body'] as $listing ) {

				if ( ! isset( $listing->body ) || $listing->code !== 200 ) {
					$listings_with_errors[] = $listing;
					continue;
				}

				$meli_user_listings_with_data[ $listing->body->id ] = (array) $listing->body;
			}
		}

		if ( ! empty( $listings_with_errors ) ) {
			Helper::logData( 'Listings with errors: ' . wp_json_encode( $listings_with_errors, JSON_PRETTY_PRINT ), 'import-actions');
		}

		Helper::logData( 'Obteined extra data from:' . count( $meli_user_listings_with_data ) . ' listings', 'import-actions');

		return $meli_user_listings_with_data;
	}

	public static function getMeliUserLisntingIds( $seller_data ) {
		$meli_user_listings = array();
		Helper::logData( 'Getting products from seller: ' . $seller_data->user_id, 'import-actions');

		$base_url = 'users/' . $seller_data->user_id . '/items/search?search_type=scan';
		$items    = MeliconMeli::getWithHeader( $base_url, $seller_data->access_token );

		if ( ! isset( $items['body']->results ) || ! is_iterable( $items['body']->results ) ) {
			Helper::logData( 'Error getting products from seller: ' . $seller_data->user_id, 'import-actions');
			return false;
		}

		$meli_user_listings = $items['body']->results;
		$scroll_id          = $items['body']->scroll_id;
		$total_pages        = intval( ceil( $items['body']->paging->total / $items['body']->paging->limit ) );

		for ( $i = 1; $i <= $total_pages; $i++ ) {
			$current_url   = $base_url . '&scroll_id=' . $scroll_id;
			$current_items = MeliconMeli::getWithHeader( $current_url, $seller_data->access_token );

			if ( isset( $current_items['body']->results ) && is_iterable( $current_items['body']->results ) ) {
				foreach ( $current_items['body']->results as $current_item ) {
					if ( ! in_array( $current_item, $meli_user_listings ) ) {
						$meli_user_listings[] = $current_item;
					}
				}

				// Actualizar el scroll_id para la próxima iteración
				if ( isset( $current_items['body']->scroll_id ) ) {
					$scroll_id = $current_items['body']->scroll_id;
				} else {
					break; // Si no hay scroll_id, salir del bucle
				}
			} elseif ( isset( $current_items['body']->error ) && ( $current_items['body']->error == 'client.exception' ) ) {
					break;
			}
		}

		Helper::logData( 'Listings from seller: ' . $seller_data->user_id . ' are: ' . wp_json_encode( $meli_user_listings, JSON_PRETTY_PRINT ), 'import-actions');

		return $meli_user_listings;
	}

	public static function getPublishedVariableProducts() {
		global $wpdb;

		$product_ids = $wpdb->get_col(
			"
            SELECT ID FROM {$wpdb->posts} 
            WHERE post_type = 'product' 
            AND post_status = 'publish'
        "
		);

		$variable_products = array();

		foreach ( $product_ids as $product_id ) {
			$product = wc_get_product( $product_id );

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

				foreach ( $variations as $variation_id ) {
					$variation = wc_get_product( $variation_id );

					if ( $variation ) {
						$variable_products[ $product_id ] = array(
							'product_id'     => $product_id,
							'variation_id'   => $variation_id,
							'sku'            => $variation->get_sku(),
							'price'          => $variation->get_price(),
							'stock_quantity' => $variation->get_stock_quantity(),
						);
					}
				}
			}
		}

		return $variable_products;
	}
}
