<?php
/**
 * Generates an Amazon product slider using ASINs.
 *
 * @package Boxyfy
 * @param array $atts Shortcode attributes.
 * @return string Rendered HTML for the product slider.
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Shortcode-Funktion für den Amazon Products Slider.
 */
function boxyfy_amazon_products_slider_shortcode( $atts ) {

    if ( ! boxyfy_is_license_valid() ) {
        return '<p class="boxyfy-products-slider-info1">' . esc_html__( 'Amazon-Product-Slider - No products found: Please refresh the page or check your license status in Settings.', 'boxyfy' ) . '</p>';
    }

    $atts = shortcode_atts(
        array(
            'asins'           => '',
            'slider_template' => 'style1', // Default template
        ),
        $atts
    );

    $asin_list  = array_unique( array_map( 'trim', explode( ',', $atts['asins'] ) ) );
    $template   = $atts['slider_template'];
    $asin_count = count( $asin_list );

    if ( $asin_count < 4 || $asin_count > 10 ) {
        return '<p class="boxyfy-products-slider-info2">' . esc_html__( 'Amazon-Product-Slider: Please enter at least 4 and no more than 10 valid Amazon ASINs.', 'boxyfy' ) . '</p>';
    }

    // Produktdaten holen
    $product_data_slider = array();
    foreach ( $asin_list as $asin ) {
        $asin_trimmed = trim( $asin );
        $product_data_item = boxyfy_get_amazon_product_data_slider( $asin_trimmed );
        if ( $product_data_item ) {
            $product_data_slider[] = $product_data_item;
        }
    }

    // Falls alle leer sind
    if ( empty( $product_data_slider ) ) {
        return '<p>' . esc_html__( 'Product information could not be retrieved.', 'boxyfy' ) . '</p>';
    }

    // Ensure unique slides are available
    $slides_per_view       = $asin_count;
    $minimum_unique_slides = $slides_per_view + $asin_count;
    if ( count( $product_data_slider ) < $minimum_unique_slides && count( $product_data_slider ) > 0 ) {
        $original_count = count( $product_data_slider );
        for ( $i = 0; count( $product_data_slider ) < $minimum_unique_slides; $i++ ) {
            $product_data_slider[] = $product_data_slider[ $i % $original_count ];
        }
    }

    // Create Amazon partner URL
    $options = get_option(
        'boxyfy_amazon_settings',
        array(
            'partner_tag' => '',
        )
    );
    $partner_tag = $options['partner_tag'];

    $min_discount_percentage_amz_slider       = get_option( 'boxyfy_amazon_slider_reduce_label_schwelle', 10 );
    $min_discount_percentage_amz_slider_stark = get_option( 'boxyfy_amazon_slider_reduce_label_schwelle_stark', 20 );

    $unique_id = 'amazon-slider-' . uniqid();
	
	$latest_update = 0;
	foreach ( $product_data_slider as $p ) {
    	if ( ! empty( $p['fetched_at'] ) && $p['fetched_at'] > $latest_update ) {
        	$latest_update = $p['fetched_at'];
    	}
	}
	if ( ! $latest_update ) {
 		$latest_update = current_time( 'timestamp' ); // Fallback
	}
	
    ob_start();
    ?>

	<div class="boxyfy-sliderboxes">
    <div class="tsamazon-products-slider-wrapper" id="<?php echo esc_attr( $unique_id ); ?>">
        <div class="swiper amazon-products-slider">
            <div class="swiper-wrapper <?php echo esc_attr( $template ); ?>">
                <?php foreach ( $product_data_slider as $products ) : ?>
                    <?php
                    $price        = boxyfy_convert_price_to_float( $products['price'] );
                    $saving_basis = boxyfy_convert_price_to_float( $products['savingBasis'] );
                    $discount_percentage = ( $saving_basis > $price ) ? round( ( ( $saving_basis - $price ) / $saving_basis ) * 100 ) : 0;

                    $purchase_url_produktbox_slider = add_query_arg(
                        array(
                            'tag'      => esc_attr( $partner_tag ),
                            'linkCode' => 'ogi',
                            'th'       => '1',
                        ),
                        'https://www.amazon.de/dp/' . rawurlencode( $products['asin'] )
                    );
                    ?>
                    <div class="swiper-slide">
                        <div class="amazon-product-box-container <?php echo esc_attr( $template ); ?>">
                            <?php if ( $discount_percentage >= $min_discount_percentage_amz_slider ) : ?>
                                <div class="slider-ribbon <?php echo esc_attr( $template ); ?>">
                                    <?php
                                    echo $discount_percentage >= $min_discount_percentage_amz_slider_stark
                                        ? esc_html__( 'stark reduziert', 'boxyfy' )
                                        : esc_html__( 'reduziert', 'boxyfy' );
                                    ?>
                                </div>
                            <?php endif; ?>
                            <div class="product-image-slider-container-ts <?php echo esc_attr( $template ); ?>">
                                <a href="<?php echo esc_url( $purchase_url_produktbox_slider ); ?>" target="_blank">
                                    <img src="<?php echo esc_url( $products['primary_image'] ); ?>"
                                         alt="<?php echo esc_attr( $products['title'] ); ?>"
                                         class="product-thumbnail-slider" />
                                </a>
                            </div>
                            <a href="<?php echo esc_url( $purchase_url_produktbox_slider ); ?>" target="_blank" class="product-title-slider <?php echo esc_attr( $template ); ?>">
                                <?php
                                $title      = $products['title'];
                                $max_chars  = 200;
                                $short_title = ( mb_strlen( $title ) > $max_chars ) ? mb_substr( $title, 0, $max_chars ) . ' ...' : $title;
                                echo esc_html( $short_title );
                                ?>
                            </a>
                            <div class="product-price-details-wrappper">
                                <div class="product-price-container <?php echo esc_attr( $template ); ?>">
                                    <?php if ( $discount_percentage >= 1 ) : ?>
                                        <span class="discount-percentage-before">
                                            -<?php echo esc_html( $discount_percentage ); ?>%
                                        </span>
                                    <?php endif; ?>
                                    <span class="product-price-slider <?php echo esc_attr( $template ); ?>">
                                        <?php echo esc_html( $products['price'] ); ?>
                                    </span>
                                    <?php if ( $discount_percentage >= 1 ) :
                                        $discount_amount = $saving_basis - $price;
                                        ?>
                                        <span class="discount-badge-slider <?php echo esc_attr( $template ); ?>">
                                            - <?php echo esc_html( number_format( $discount_amount, 0, ',', '' ) . ' €' ); ?>
                                        </span>
                                    <?php endif; ?>
                                </div>
                                <?php if ( $discount_percentage >= 1 ) : ?>
                                    <div class="product-saveprice-slider <?php echo esc_attr( $template ); ?>">
                                        <?php echo esc_html__( 'UVP:', 'boxyfy' ); ?> <?php echo esc_html( $products['savingBasis'] ); ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="product-add-to-cart-slider <?php echo esc_attr( $template ); ?>">
                                <a href="https://www.amazon.de/gp/aws/cart/add.html?ASIN.1=<?php echo esc_attr( $products['asin'] ); ?>&Quantity.1=1&tag=<?php echo esc_attr( $partner_tag ); ?>"
                                   target="_blank"
                                   class="add-to-cart-link-slider <?php echo esc_attr( $template ); ?>"
                                >
                                    <svg fill="currentColor" version="1.1" id="Capa_1"
                                         xmlns="http://www.w3.org/2000/svg"
                                         xmlns:xlink="http://www.w3.org/1999/xlink"
                                         viewBox="0 0 902.86 902.86"
                                         xml:space="preserve">
                                        <g>
                                            <g>
                                                <path d="M671.504,577.829l110.485-432.609H902.86v-68H729.174L703.128,179.2L0,178.697l74.753,399.129h596.751V577.829z
                                                     M685.766,247.188l-67.077,262.64H131.199L81.928,246.756L685.766,247.188z"/>
                                                <path d="M578.418,825.641c59.961,0,108.743-48.783,108.743-108.744s-48.782-108.742-108.743-108.742H168.717
                                                     c-59.961,0-108.744,48.781-108.744,108.742s48.782,108.744,108.744,108.744c59.962,0,108.743-48.783,108.743-108.744
                                                     c0-14.4-2.821-28.152-7.927-40.742h208.069c-5.107,12.59-7.928,26.342-7.928,40.742
                                                     C469.675,776.858,518.457,825.641,578.418,825.641z M209.46,716.897c0,22.467-18.277,40.744-40.743,40.744
                                                     c-22.466,0-40.744-18.277-40.744-40.744c0-22.465,18.277-40.742,40.744-40.742C191.183,676.155,209.46,694.432,209.46,716.897z
                                                     M619.162,716.897c0,22.467-18.277,40.744-40.743,40.744s-40.743-18.277-40.743-40.744c0-22.465,18.277-40.742,40.743-40.742
                                                     S619.162,694.432,619.162,716.897z"/>
                                            </g>
                                        </g>
                                    </svg>
                                    <?php echo esc_html__( 'Amazon Warenkorb', 'boxyfy' ); ?>
                                </a>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
            <div class="slider-pagination <?php echo esc_attr( $template ); ?>">
                <?php for ( $i = 0; $i < $asin_count; $i++ ) : ?>
                    <span class="pagination-dot <?php echo esc_attr( $template ); ?>"></span>
                <?php endfor; ?>
            </div>
			<div class="boxyfy-products-slider-disclaimer">
   	 			<?php
        			echo esc_html__( 'Alle Preise inkl. MwSt', 'boxyfy' ) . ' | ';
        			echo esc_html__( 'Zuletzt aktualisiert: ', 'boxyfy' ) .
            			esc_html( date_i18n( 'd.m.Y H:i', $latest_update ) ) . ' | ';
        			echo esc_html__( 'Affiliate-Links enthalten', 'boxyfy' );
    			?>
			</div>
        </div>
        <div class="swiper-button-prev swiper-button-prev-<?php echo esc_attr( $unique_id ); ?>"></div>
        <div class="swiper-button-next swiper-button-next-<?php echo esc_attr( $unique_id ); ?>"></div>
	</div>
    </div>

    <?php
    return ob_get_clean();
}
add_shortcode( 'boxyfy_amazon_products_slider', 'boxyfy_amazon_products_slider_shortcode' );

/**
 * Holt Produktdaten **mit zentral gesteuertem Cache**.
 *
 * @param string $asin
 * @return array|null
 */
function boxyfy_get_amazon_product_data_slider( $asin ) {

	// 1) Lizenz-Check
	if ( ! boxyfy_is_license_valid() ) {
		return null;
	}

	// 2) Globale Cache-Einstellungen
	$cache_enabled = ( get_option( 'boxyfy_cache_enable', 'no' ) === 'yes' );
	$cache_ttl     = (int) get_option( 'boxyfy_cache_ttl', 360 ) * MINUTE_IN_SECONDS;

	// 3) Key generieren  ( Modul = 'slider',  ID = ASIN )
	$cache_key = boxyfy_build_cache_key( 'slider', $asin );

	// 4) Falls aktiv → versuchen, aus dem Cache zu lesen
	if ( $cache_enabled ) {
		$cached = get_transient( $cache_key );
		if ( $cached !== false ) {
			return $cached; // ↩ Sofort zurück
		}
	}

	/* ----------------------------------------------------------------
	 * 5)  API-Call  (dein Original-Code, nur leicht gekürzt & sanitized)
	 * ---------------------------------------------------------------- */
	$options = get_option(
		'boxyfy_amazon_settings',
		array(
			'access_key'  => '',
			'secret_key'  => '',
			'partner_tag' => '',
			'host'        => 'webservices.amazon.de',
			'region'      => 'eu-west-1',
		)
	);

	$host       = sanitize_text_field( $options['host'] );
	$region     = sanitize_text_field( $options['region'] );
	$access_key = sanitize_text_field( $options['access_key'] );
	$secret_key = sanitize_text_field( $options['secret_key'] );
	$partnerTag = sanitize_text_field( $options['partner_tag'] );

	$payload = wp_json_encode(
		array(
			'ItemIds'   => array( $asin ),
			'Resources' => array(
				'ItemInfo.Title',
				'Images.Primary.Large',
				'Offers.Listings.Price',
				'Offers.Listings.SavingBasis',
			),
			'PartnerTag'  => $partnerTag,
			'PartnerType' => 'Associates',
			'Marketplace' => 'www.amazon.de',
		)
	);

	if ( ! class_exists( 'AwsV4' ) ) {
		require_once plugin_dir_path( BOXYFY_PLUGIN_FILE ) . 'assets/vendor/amazon/boxyfy-class-aws-v4.php';
	}

	$awsv4 = new AwsV4( $access_key, $secret_key );
	$awsv4->setRegionName( $region );
	$awsv4->setServiceName( 'ProductAdvertisingAPI' );
	$awsv4->setPath( '/paapi5/getitems' );
	$awsv4->setPayload( $payload );
	$awsv4->setRequestMethod( 'POST' );
	$awsv4->addHeader( 'content-encoding', 'amz-1.0' );
	$awsv4->addHeader( 'content-type', 'application/json; charset=utf-8' );
	$awsv4->addHeader( 'host', $host );
	$awsv4->addHeader( 'x-amz-target', 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.GetItems' );

	$response = wp_remote_post(
		"https://{$host}/paapi5/getitems",
		array(
			'headers' => $awsv4->getHeaders(),
			'body'    => $payload,
			'timeout' => 15,
		)
	);

	if ( is_wp_error( $response ) ) {
		return null;
	}

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

	if ( empty( $data['ItemsResult']['Items'][0] ) ) {
		return null;
	}

	$item = $data['ItemsResult']['Items'][0];

	$result = array(
		'asin'          => $asin,
		'title'         => $item['ItemInfo']['Title']['DisplayValue']             ?? '',
		'primary_image' => $item['Images']['Primary']['Large']['URL']             ?? '',
		'price'         => $item['Offers']['Listings'][0]['Price']['DisplayAmount']       ?? '',
		'savingBasis'   => $item['Offers']['Listings'][0]['SavingBasis']['DisplayAmount'] ?? '',
		'fetched_at'    => current_time( 'timestamp' ),
	);

	// 6)  Im Cache ablegen
	if ( $cache_enabled ) {
		set_transient( $cache_key, $result, $cache_ttl );
	}

	return $result;
}