<?php
/**
 * Shortcode handler function for displaying Amazon bestseller product boxes in a list format.
 *
 * This function retrieves Amazon bestseller products based on a given keyword using the 
 * Amazon Product Advertising API. The retrieved products are displayed in a structured 
 * list format, featuring product images, titles, key features, and pricing information. 
 * The function also provides sorting options based on price or discount percentage.
 * 
 * @package Boxyfy
 */

// ----------------------------------------------
// Sicherheitscheck
// ----------------------------------------------
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! function_exists( 'boxyfy_amazon_liste_shortcode' ) ) {
	/**
	 * Shortcode-Funktion: Gibt Amazon-Bestseller in Boxenform (Listenlayout) aus.
	 *
	 * @param array $atts Array der Shortcode-Attribute.
	 * @return string HTML-Ausgabe des Shortcodes.
	 */
	function boxyfy_amazon_liste_shortcode( $atts ) {
		if ( boxyfy_is_license_valid() ) {
			$atts = shortcode_atts(
				array(
					'keyword'                 => '',
					'max_products'            => 6,   // Standardmäßig maximal 6 Produkte.
					'max_visible_list_items'  => 2,   // Anzahl der standardmäßig sichtbaren Details-Listenpunkte.
					'price_order'             => '',  // Sortierreihenfolge des Preises: 'asc' oder 'desc'.
					'discount_order'          => '',  // Sortierreihenfolge des Rabatts: 'asc' oder 'desc'.
					'display_discount'        => 'true', // kann ggf. entfernt werden.
					'max_title_length'        => 200, // Maximale Zeichenlänge der Produktbeschreibung.
					'button_text'             => 'Bei Amazon ansehen', // Text für den Button.
					'cart_button_text'        => 'Amazon Warenkorb',    // Text für den zweiten Button.
					'display_cart_button'     => 'true',
					'box_shadows'             => '',  // Bei 'yes' wird ein zusätzlicher inset-Shadow gesetzt.
					'max_list_length'         => 180, // NEU: Maximale Zeichenlänge für jeden Listenpunkt.
				),
				$atts
			);
		}

		// Prüfe, ob ein Keyword gesetzt ist.
		if ( empty( $atts['keyword'] ) ) {
			return '<p>Bitte ein bzw. mehrere Keywords angeben.</p>';
		}

		// Rufe Daten von Amazon (Bestseller) ab.
		$product_data_list_zwei = boxyfy_get_amazon_product_list_zwei( $atts['keyword'], $atts['max_products'] );
		if ( ! $product_data_list_zwei || ! isset( $product_data_list_zwei['products'] ) ) {
			return '<p style="color:red;">Keine Produkte beim Abruf gefunden: Bitte die Seite aktualisieren oder Lizenzschlüssel-Status unter Einstellungen überprüfen.</p>';
		}

		// Sortierung nach Preis?
		if ( ! empty( $atts['price_order'] ) ) {
			usort(
				$product_data_list_zwei['products'],
				function( $a, $b ) use ( $atts ) {
					$price_a = floatval( str_replace( array( '€', ',' ), array( '', '.' ), $a['Offers']['Listings'][0]['Price']['DisplayAmount'] ) );
					$price_b = floatval( str_replace( array( '€', ',' ), array( '', '.' ), $b['Offers']['Listings'][0]['Price']['DisplayAmount'] ) );

					return ( 'asc' === $atts['price_order'] )
						? $price_a <=> $price_b
						: $price_b <=> $price_a;
				}
			);
		} elseif ( ! empty( $atts['discount_order'] ) ) {
			// Sortierung nach Rabatt?
			usort(
				$product_data_list_zwei['products'],
				function( $a, $b ) use ( $atts ) {
					$price_a = floatval( str_replace( array( '€', ',' ), array( '', '.' ), $a['Offers']['Listings'][0]['Price']['DisplayAmount'] ) );
					$saving_basis_a = floatval(
						str_replace(
							array( '€', ',' ),
							array( '', '.' ),
							$a['Offers']['Listings'][0]['SavingBasis']['DisplayAmount'] ?? 0
						)
					);
					$discount_a = ( $saving_basis_a > 0 )
						? ( ( $saving_basis_a - $price_a ) / $saving_basis_a ) * 100
						: 0;

					$price_b = floatval( str_replace( array( '€', ',' ), array( '', '.' ), $b['Offers']['Listings'][0]['Price']['DisplayAmount'] ) );
					$saving_basis_b = floatval(
						str_replace(
							array( '€', ',' ),
							array( '', '.' ),
							$b['Offers']['Listings'][0]['SavingBasis']['DisplayAmount'] ?? 0
						)
					);
					$discount_b = ( $saving_basis_b > 0 )
						? ( ( $saving_basis_b - $price_b ) / $saving_basis_b ) * 100
						: 0;

					return ( 'asc' === $atts['discount_order'] )
						? $discount_a <=> $discount_b
						: $discount_b <=> $discount_a;
				}
			);
		}

		// Hole individuelle (Theme-)Einstellungen (nur falls du sie im HTML brauchst).
		$product_amz_bestseller_boxes_colorofribbon                 = get_option( 'boxyfy_amazon_bestseller_boxes_colorofribbon', '#e00000' );
		$product_amz_bestseller_boxes_background_first_button       = get_option( 'boxyfy_amazon_bestseller_boxes_background_first_button', '#0173ab' );
		$product_amz_bestseller_boxes_font_size_title               = get_option( 'boxyfy_amazon_bestseller_boxes_font_size_title', 20 );
		$product_amz_bestseller_boxes_font_size_listpoints          = get_option( 'boxyfy_amazon_bestseller_boxes_font_size_listpoints', 15 );
		$product_amz_bestseller_boxes_buttontextcolor_first_button  = get_option( 'boxyfy_amazon_bestseller_boxes_buttontextcolor_first_button', '#ffffff' );
		$product_amz_bestseller_boxes_background_second_button      = get_option( 'boxyfy_amazon_bestseller_boxes_background_second_button', '#dddddd' );
		$product_amz_bestseller_boxes_buttontextcolor_second_button = get_option( 'boxyfy_amazon_bestseller_boxes_buttontextcolor_second_button', '#333333' );

		// Zeitstempel (aktualisierte Daten) holen.
		$timestamp = date_i18n( 'd.m.Y H:i', $product_data_list_zwei['fetched_at'] ?? time() );

		// Box-Shadow-Klasse nur hinzufügen, wenn 'yes' angegeben.
		$box_shadow_klass = ( isset( $atts['box_shadows'] ) && 'yes' === $atts['box_shadows'] )
			? 'box-shadows'
			: '';

		ob_start();
		?>
		<div class="boxyfy-amz-bestseller-liste">
		<div class="amazon-bestseller-product-boxes-list-zwei">
			<?php foreach ( $product_data_list_zwei['products'] as $index => $product ) : ?>
				<?php
				$partner_settings = get_option( 'boxyfy_amazon_settings' );
				$partner_tag      = isset( $partner_settings['partner_tag'] ) ? $partner_settings['partner_tag'] : '';
				$purchase_url     = 'https://www.amazon.de/dp/' . esc_attr( $product['ASIN'] ) . '?tag=' . esc_attr( $partner_tag ) . '&linkCode=ogi&th=1';

				// Warenkorb-Link erstellen.
				$cart_url = 'https://www.amazon.de/gp/aws/cart/add.html?ASIN.1=' . esc_attr( $product['ASIN'] ) . '&Quantity.1=1&tag=' . esc_attr( $partner_tag );

				$price = floatval(
					str_replace(
						array( '€', ',' ),
						array( '', '.' ),
						$product['Offers']['Listings'][0]['Price']['DisplayAmount']
					)
				);
				$saving_basis = floatval(
					str_replace(
						array( '€', ',' ),
						array( '', '.' ),
						$product['Offers']['Listings'][0]['SavingBasis']['DisplayAmount'] ?? ''
					)
				);
				$discount_percentage = ( $saving_basis > 0 )
					? round( ( ( $saving_basis - $price ) / $saving_basis ) * 100 )
					: 0;
				?>
				<div class="amazon-product-box-zwei<?php echo $box_shadow_klass ? ' ' . esc_attr( $box_shadow_klass ) : ''; ?>">
					<div class="ranking-label-box-zwei">
						<?php
						printf(
							/* translators: %d is the rank number */
							esc_html__( 'Bestseller Nr. %d', 'boxyfy' ),
							intval( $index + 1 )
						);
						?>
					</div>

					<div class="amazon-product-content-zwei">
						<div class="amazon-best-productboxes-image-container">
							<img
								src="<?php echo esc_url( $product['Images']['Primary']['Large']['URL'] ); ?>"
								alt="<?php echo esc_attr( $product['ItemInfo']['Title']['DisplayValue'] ); ?>"
								class="amazon-product-thumbnail-zwei"
							/>
						</div>

						<div class="amazon-product-info-zwei">
							<div class="amazon-product-title-zwei">
								<?php
								echo esc_html(
									mb_strimwidth(
										$product['ItemInfo']['Title']['DisplayValue'],
										0,
										$atts['max_title_length'],
										'...'
									)
								);
								?>
							</div>

							<ul class="amazon-product-details-zwei">
								<?php
								$details = isset( $product['ItemInfo']['Features']['DisplayValues'] )
									? $product['ItemInfo']['Features']['DisplayValues']
									: array();
								$visible_items_count = intval( $atts['max_visible_list_items'] );

								if ( ! empty( $details ) ) {
									// Zeige nur die definierte Anzahl direkt an
									for ( $i = 0; $i < min( $visible_items_count, count( $details ) ); $i++ ) {
										echo '<li>' .
											esc_html(
												mb_strimwidth(
													$details[ $i ],
													0,
													$atts['max_list_length'],
													'...'
												)
											) .
										'</li>';
									}

									// Falls noch mehr Features existieren: "Mehr anzeigen" + die restlichen Punkte
									if ( count( $details ) > $visible_items_count ) {
										echo '<div class="toggle-details" onclick="toggleDetails(this)">' .
     										esc_html__( 'Mehr anzeigen', 'boxyfy' ) . ' ' .
     										'<img src="' . esc_url( plugins_url( 'assets/images/arrow-down.png', BOXYFY_PLUGIN_FILE ) ) . '" alt="' . esc_attr__( 'Pfeil nach unten', 'boxyfy' ) . '">' .
     										'</div>';

										echo '<ul class="more-details">';
										for ( $i = $visible_items_count; $i < count( $details ); $i++ ) {
											echo '<li>' .
												esc_html(
													mb_strimwidth(
														$details[ $i ],
														0,
														$atts['max_list_length'],
														'...'
													)
												) .
											'</li>';
										}
										echo '</ul>';
									}
								}
								?>
							</ul>

							<?php if ( $discount_percentage > 0 ) : ?>
								<span class="discount-percentage-zwei">
									<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" id="price-tag" class="icon glyph"><path d="M20,2H14a1,1,0,0,0-.7.29L3,12.55a2,2,0,0,0,0,2.83L8.62,21a2,2,0,0,0,1.41.59h0A2,2,0,0,0,11.45,21L21.71,10.7A1,1,0,0,0,22,10V4A2,2,0,0,0,20,2ZM16.5,9A1.5,1.5,0,1,1,18,7.5,1.5,1.5,0,0,1,16.5,9Z" style="fill:currentColor"></path>
									</svg>
									<?php
									printf(
										esc_html__( '%d%% günstiger', 'boxyfy' ),
										intval( $discount_percentage )
									);
									?>
								</span>
							<?php endif; ?>

							<div class="amazon-product-price-container-zwei">
								<span class="product-price-zwei">
									<?php echo esc_html( $product['Offers']['Listings'][0]['Price']['DisplayAmount'] ); ?>
								</span>

								<?php if ( ! empty( $product['Offers']['Listings'][0]['SavingBasis']['DisplayAmount'] ) ) : ?>
									<span class="product-saveprice-zwei">
										<?php echo esc_html__( 'UVP:', 'boxyfy' ); ?>
										<?php echo esc_html( $product['Offers']['Listings'][0]['SavingBasis']['DisplayAmount'] ); ?>
									</span>
								<?php endif; ?>
							</div>

							<div class="button-container-zwei">
								<a
									href="<?php echo esc_url( $purchase_url ); ?>"
									target="_blank"
									class="amazon-product-button-zwei"
								>
									<svg
										fill="currentColor"
										width="17px"
										height="17px"
										viewBox="0 0 24 24"
										xmlns="http://www.w3.org/2000/svg"
										style="vertical-align: middle; margin-right: 4px;"
									>
										<path
											d="M19.5 8.25H16.5V7.75C16.5 6.55653 16.0259 5.41193 15.182 4.56802C14.3381 3.72411 13.1935 3.25 12 3.25C10.8065 3.25 9.66193 3.72411 8.81802 4.56802C7.97411 5.41193 7.5 6.55653 7.5 7.75V8.25H4.5C4.16848 8.25 3.85054 8.3817 3.61612 8.61612C3.3817 8.85054 3.25 9.16848 3.25 9.5V18C3.25 18.7293 3.53973 19.4288 4.05546 19.9445C4.57118 20.4603 5.27065 20.75 6 20.75H18C18.7293 20.75 19.4288 20.4603 19.9445 19.9445C20.4603 19.4288 20.75 18.7293 20.75 18V9.5C20.75 9.16848 20.6183 8.85054 20.3839 8.61612 20.1495 8.3817 19.8315 8.25 19.5 8.25ZM9 7.75C9 6.95435 9.31607 6.19129 9.87868 5.62868C10.4413 5.06607 11.2044 4.75 12 4.75C12.7956 4.75 13.5587 5.06607 14.1213 5.62868C14.6839 6.19129 15 6.95435 15 7.75V8.25H9V7.75ZM19.25 18C19.25 18.3315 19.1183 18.6495 18.8839 18.8839C18.6495 19.1183 18.3315 19.25 18 19.25H6C5.66848 19.25 5.35054 19.1183 5.11612 18.8839C4.8817 18.6495 4.75 18.3315 4.75 18V9.75H7.5V12C7.5 12.1989 7.57902 12.3897 7.71967 12.5303C7.86032 12.671 8.05109 12.75 8.25 12.75C8.44891 12.75 8.63968 12.671 8.78033 12.5303C8.92098 12.3897 9 12.1989 9 12V9.75H15V12C15 12.1989 15.079 12.3897 15.2197 12.5303C15.3603 12.671 15.5511 12.75 15.75 12.75C15.9489 12.75 16.1397 12.671 16.2803 12.5303C16.421 12.3897 16.5 12.1989 16.5 12V9.75H19.25V18Z"
											fill="currentColor"
										/>
									</svg>
									<?php echo esc_html( translate( $atts['button_text'], 'boxyfy' ) ); ?>
								</a>

								<?php if ( 'true' === $atts['display_cart_button'] ) : ?>
									<a
										href="<?php echo esc_url( $cart_url ); ?>"
										target="_blank"
										class="amazon-cart-button-zwei"
									>
										<?php echo esc_html( translate( $atts['cart_button_text'], 'boxyfy' ) ); ?>
									</a>
								<?php endif; ?>
							</div>
						</div><!-- .amazon-product-info-zwei -->
					</div><!-- .amazon-product-content-zwei -->
				</div><!-- .amazon-product-box-zwei -->
			<?php endforeach; ?>

			<div class="disclaimer-amz-liste-boxes">
			<?php
				printf(
					/* translators: %s is the last updated date/time */
					esc_html__( 'Alle Preise inkl. MwSt | Zuletzt aktualisiert: %s | Preise können sich geändert haben | Affiliate-Links enthalten', 'boxyfy' ),
					esc_html( $timestamp )
				);
			?>
			</div>

		</div><!-- .amazon-bestseller-product-boxes-list-zwei -->
		</div><!-- .boxyfy-amz-bestseller-liste -->
		<?php

		// An dieser Stelle werden KEINE Inline-CSS oder JS mehr ausgegeben:
		// Alles bitte über externe Dateien (enqueue) laden.

		return ob_get_clean();
	}
}
add_shortcode( 'boxyfy_amazon_liste', 'boxyfy_amazon_liste_shortcode' );


if ( ! function_exists( 'boxyfy_get_amazon_product_list_zwei' ) ) {
	/* -------------------------------------------------------------------------
 * Amazon-Bestseller-Daten holen  (mit zentralem Caching)
 * ---------------------------------------------------------------------- */
function boxyfy_get_amazon_product_list_zwei( $keyword, $max_items = 10, $force_refresh = false ) {

	/* -- 1. Lizenzcheck --------------------------------------------- */
	if ( ! boxyfy_is_license_valid() ) {
		return null;
	}

	/* -- 2. Cache-Einstellungen ------------------------------------- */
	$cache_enabled = ( get_option( 'boxyfy_cache_enable', 'no' ) === 'yes' );
	$cache_ttl     = (int) get_option( 'boxyfy_cache_ttl', 360 ) * MINUTE_IN_SECONDS;
	$cache_key     = boxyfy_build_cache_key( 'list2', $keyword ); //  ➜  _transient_boxyfy_amz_list2_<hash>

	if ( $cache_enabled && ! $force_refresh ) {
		if ( ( $cached = get_transient( $cache_key ) ) !== false ) {
			return $cached;
		}
	}

	/* -- 3. API-Aufruf ---------------------------------------------- */
	$options = get_option(
		'boxyfy_amazon_settings',
		array(
			'access_key'  => '',
			'secret_key'  => '',
			'partner_tag' => '',
			'host'        => 'webservices.amazon.de',
			'region'      => 'eu-west-1',
		)
	);

	$payload = wp_json_encode(
		array(
			'Keywords'    => $keyword,
			'PartnerTag'  => sanitize_text_field( $options['partner_tag'] ),
			'PartnerType' => 'Associates',
			'Marketplace' => 'www.amazon.de',
			'Operation'   => 'SearchItems',
			'Resources'   => array(
				'ItemInfo.Title',
				'ItemInfo.Features',            //  ➜  für die Aufzählung
				'Images.Primary.Large',
				'Offers.Listings.Price',
				'Offers.Listings.SavingBasis',
			),
		)
	);

	$uri_path = '/paapi5/searchitems';

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

	$awsv4 = new AwsV4( $options['access_key'], $options['secret_key'] );
	$awsv4->setRegionName( $options['region'] );
	$awsv4->setServiceName( 'ProductAdvertisingAPI' );
	$awsv4->setPath( $uri_path );
	$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', $options['host'] );
	$awsv4->addHeader( 'x-amz-target', 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.SearchItems' );

	$response = wp_remote_post(
		'https://' . $options['host'] . $uri_path,
		array(
			'timeout'   => 15,
			'sslverify' => false,
			'headers'   => $awsv4->getHeaders(),
			'body'      => $payload,
			'method'    => 'POST',
		)
	);

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

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

	if ( isset( $data['SearchResult']['Items'] ) && count( $data['SearchResult']['Items'] ) > 0 ) {

		$result = array(
			'products'   => array_slice( $data['SearchResult']['Items'], 0, $max_items ),
			'fetched_at' => current_time( 'timestamp' ),
		);

		if ( $cache_enabled ) {
			set_transient( $cache_key, $result, $cache_ttl );
		}

		return $result;
	}

	return null;
	}
}