<?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\UserConnection;
use Meliconnect\Meliconnect\Modules\Importer\Models\UserListingToImport;

/**
 * Handles communication with the external server to processs and send raw product data
 * and receive transformed product data.
 */
class WooCommerceProductAdapter {

	protected $apiEndpoint;

	public function __construct() {
		// Detectar entorno y seleccionar la URL correspondiente

		$this->apiEndpoint = 'https://meliconnect.com/api/v1/process-product-data-to-import';
	}

	public function getTransformedProductData( $meli_listing_data, $meli_user_id, $template_id = null, $woo_product_id = null, $sync_options = null ) {
        
        $pre_import_data = UserListingToImport::get_user_listing_by_listing_id( $meli_listing_data['data']->id );



		$rawData = array(
			'extra_data'   => array(
				'meli_user_id'   => $meli_user_id,
				'woo_product_id' => $woo_product_id,
				'template_id'    => $template_id,
				'domain'         => Helper::getDomainName(),
			),

			'meli_listing' => $meli_listing_data,
			'settings'     => Helper::getMeliconnectOptions( 'import' ),
			'sync_options' => $sync_options,
            'pre_import_data' => $pre_import_data,
			// 'woo_product' => $this->getWooProductData($woo_product_id),
			// 'woo_variations' => $this->getWooProductVariations($woo_product_id),
			// 'template' => $this->getMeliconTemplateData($template_id),

		);

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

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

        if ( is_wp_error( $server_response ) ) {
            Helper::logData('WP Error: ' . $server_response->get_error_message(), 'custom-import');
            return null;
        }

        if ( empty( $server_response ) ) {
            Helper::logData('Empty server response', 'custom-import');
            return null;
        }

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

        $decoded = json_decode( $server_response, true );

        if ( json_last_error() !== JSON_ERROR_NONE ) {
            Helper::logData('JSON decode error: ' . json_last_error_msg(), 'custom-import');
            return null;
        }

		return $decoded;
	}

	private function getWooProductData( $woo_product_id = null ) {
		if ( $woo_product_id == null ) {
			return array();
		}

		// Obtén el objeto del producto
		$product = wc_get_product( $woo_product_id );

		if ( ! $product ) {
			return array();
		}

		// Extrae la información necesaria
		$product_data = array(
			'id'                => $product->get_id(),
			'title'             => $product->get_name(),
			'short_description' => $product->get_short_description(),
			'long_description'  => $product->get_description(),
			'_sku'              => $product->get_sku(),
			'is_variable'       => $product->is_type( 'variable' ),
			'categories'        => $this->getProductCategories( $product ),
		);

		return $product_data;
	}

	private function getWooProductVariations( $woo_product_id = null ) {
		if ( $woo_product_id == null ) {
			return array();
		}

		// Obtén el objeto del producto
		$product = wc_get_product( $woo_product_id );

		// Verifica que el producto sea de tipo variable
		if ( ! $product || ! $product->is_type( 'variable' ) ) {
			return array();
		}

		// Obtén las variaciones del producto
		$variations    = array();
		$variation_ids = $product->get_children();

		foreach ( $variation_ids as $variation_id ) {
			$variation = wc_get_product( $variation_id );
			if ( $variation ) {
				$variations[] = array(
					'id'             => $variation->get_id(),
					'_sku'           => $variation->get_sku(),
					'price'          => $variation->get_price(),
					'regular_price'  => $variation->get_regular_price(),
					'sale_price'     => $variation->get_sale_price(),
					'stock_quantity' => $variation->get_stock_quantity(),
					'attributes'     => $variation->get_attributes(),
					'is_in_stock'    => $variation->is_in_stock(),
				);
			}
		}

		return $variations;
	}




	private function getMeliconTemplateData() {
		return array();
	}

	private function sendDataToServer( array $productData ) {

        $max_retries = 3;
        $attempt = 0;

        do {

            $attempt++;

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

            // Error de conexión
            if ( is_wp_error( $response ) ) {

                Helper::logData("Attempt {$attempt}: WP Error: " . $response->get_error_message() . ". For product data: " . wp_json_encode($productData));

                // retry
                if ( $attempt < $max_retries ) {
                    sleep( $attempt ); // backoff progresivo (1s, 2s, 3s)
                    continue;
                }

                return null;
            }

            $status_code = wp_remote_retrieve_response_code( $response );
            $body        = wp_remote_retrieve_body( $response );

            // HTTP error
            if ( $status_code !== 200 ) {

                Helper::logData("Attempt {$attempt}: HTTP Error {$status_code}. For product data: " . wp_json_encode($productData));
                Helper::logData("Response body: " . $body);

                // Retry SOLO en errores de servidor
                if ( $status_code >= 500 && $attempt < $max_retries ) {
                    sleep( $attempt );
                    continue;
                }

                return null;
            }

            // Body vacío
            if ( empty( $body ) ) {

                Helper::logData("Attempt {$attempt}: Empty response body. For product data: " . wp_json_encode($productData));

                if ( $attempt < $max_retries ) {
                    sleep( $attempt );
                    continue;
                }

                return null;
            }

            // OK
            return $body;

        } while ( $attempt < $max_retries );

        return null;
    }


	/**
	 * Función auxiliar para obtener las categorías del producto.
	 */
	private function getProductCategories( $product ) {
		$categories = array();
		$terms      = get_the_terms( $product->get_id(), 'product_cat' );

		if ( $terms && ! is_wp_error( $terms ) ) {
			foreach ( $terms as $term ) {
				if ( $term->parent == 0 ) {
					$categories[] = $term->name;
				}
			}
		}

		return $categories;
	}
}
