<?php
/**
 * Generates an Amazon product box with customizable options.
 *
 * Fetches and displays product details, including title, image, price, discount, and
 * purchase buttons based on the provided ASIN. Supports different templates,
 * customizable text, and a responsive layout with optional image sliders.
 *
 * Includes API validation, price calculations, and discount handling.
 * Optimized for mobile and desktop display.
 *
 * @package Boxyfy
 * @param array $atts Shortcode attributes.
 * @return string Rendered HTML for the product box.
 */

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

function boxyfy_amazon_productbox_shortcode( $atts ) {

	// Shortcode-Attribute mit Defaults zusammenführen.
	$atts = shortcode_atts(
		array(
			'asin'               => '',
			'max_list_items'     => 2,
			'box_template'       => '', // Muss 'simple1' oder 'simple2' sein.
			'title'              => '',
			'next_button'        => '',
			'next_button_link'   => '',
			'next_button_rel'    => '',
			'button_title'       => 'bei Amazon kaufen',
			'product_tag'        => '',
			'max_title_length'   => '100',
			'max_list_length'    => '250',
		),
		$atts
	);

	// ASIN und passendes Template prüfen.
	if ( empty( $atts['asin'] )
		|| ( 'simple1' !== $atts['box_template'] && 'simple2' !== $atts['box_template'] ) ) {
		return '<p>Bitte eine gültige ASIN und das Template "simple1" oder "simple2" angeben.</p>';
	}

	// Titel-Länge begrenzen.
	$title_length = intval( $atts['max_title_length'] );
	if ( $title_length > 136 ) {
		$title_length = 136;
	}
	// Maximale Details-Länge.
	$max_detail_length = intval( $atts['max_list_length'] );

	// Produktdaten abrufen.
	$product_data = boxyfy_get_amazon_product_data( $atts['asin'] );
	if ( ! $product_data ) {
		return '<p>Keine Produkte beim Abruf gefunden: Bitte Seite aktualisieren oder Lizenz prüfen.</p>';
	}

	// Produkt-Titel (entweder benutzerdefiniert oder aus Daten).
	$product_title = ! empty( $atts['title'] ) ? $atts['title'] : $product_data['title'];

	// Rabatt berechnen, falls UVP und Preis vorhanden.
	$price        = boxyfy_convert_price_to_float( $product_data['price'] );
	$saving_basis = boxyfy_convert_price_to_float( $product_data['savingBasis'] );
	$discount_percentage = ( $saving_basis > 0 )
		? round( ( ( $saving_basis - $price ) / $saving_basis ) * 100 )
		: 0;

	// Amazon-URL zusammensetzen.
	$options      = get_option( 'boxyfy_amazon_settings', array( 'partner_tag' => '' ) );
	$partner_tag  = $options['partner_tag'];
	$purchase_url = 'https://www.amazon.de/dp/' . esc_attr( $atts['asin'] )
		. '?tag=' . esc_attr( $partner_tag ) . '&linkCode=ogi&th=1';

	// Discount-Badge-Klasse je nach Template.
	$discount_badge_class = ( 'simple2' === $atts['box_template'] )
		? 'amazon-discount-badge2'
		: 'amazon-discount-badge';

	// HTML-Ausgabe starten.
	ob_start();
	?>
	<div class="boxyfy-simpleboxes">
	<div class="amazon-product-box-<?php echo esc_attr( $atts['box_template'] ); ?>">
		<?php if ( $discount_percentage > 0 ) : ?>
			<div class="<?php echo esc_attr( $discount_badge_class ); ?>">
				<?php
				printf(
					/* translators: %d is the discount percentage */
					esc_html__( '%d%% günstiger', 'boxyfy' ),
					(int) $discount_percentage
				);
				?>
			</div>
		<?php endif; ?>

		<div class="amazon-product-content">
			<?php if ( 'simple2' === $atts['box_template'] ) : ?>
				<div class="slider-wrapper-simple2box">
					<button class="slider-arrow-simple2box left-arrow-simple2box">
						<svg fill="#6e6c6c" viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <path d="M23.505 0c0.271 0 0.549 0.107 0.757 0.316 0.417 0.417 0.417 1.098 0 1.515l-14.258 14.264 14.050 14.050c0.417 0.417 0.417 1.098 0 1.515s-1.098 0.417-1.515 0l-14.807-14.807c-0.417-0.417-0.417-1.098 0-1.515l15.015-15.022c0.208-0.208 0.486-0.316 0.757-0.316z"></path>
						</svg>
					</button>
					<div class="slider-container-simple2box">
						<img
							src="<?php echo esc_url( $product_data['primary_image'] ); ?>"
							alt="Primary Image"
							class="slider-image-simple2box active"
						/>
						<?php foreach ( $product_data['additional_images'] as $image ) : ?>
							<img
								src="<?php echo esc_url( $image ); ?>"
								alt="Additional Image"
								class="slider-image-simple2box"
							/>
						<?php endforeach; ?>
					</div>
					<button class="slider-arrow-simple2box right-arrow-simple2box">
						<svg fill="#6e6c6c" viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">
    						<path d="M8.489 31.975c-0.271 0-0.549-0.107-0.757-0.316-0.417-0.417-0.417-1.098 0-1.515l14.258-14.264-14.050-14.050c-0.417-0.417-0.417-1.098 0-1.515s1.098-0.417 1.515 0l14.807 14.807c0.417 0.417 0.417 1.098 0 1.515l-15.015 15.022c-0.208 0.208-0.486 0.316-0.757 0.316z"></path>
						</svg>
					</button>
				</div>
			<?php else : ?>
				<div class="amazon-product-image-wrapper-simple1">
					<img
						src="<?php echo esc_url( $product_data['primary_image'] ); ?>"
						alt="<?php echo esc_attr( $product_title ); ?>"
						class="amazon-product-thumbnail"
					/>
				</div>
			<?php endif; ?>

			<ul class="tsprodukt-amazon-product-details">
				<div class="amazon-product-title-<?php echo esc_attr( $atts['box_template'] ); ?>">
					<?php
					// Titel ggf. trimmen.
					echo esc_html(
						mb_strimwidth( $product_title, 0, $title_length, '...' )
					);
					?>
				</div>

				<?php if ( ! empty( $atts['product_tag'] ) ) : ?>
    				<?php
    				$tags = array_map( 'trim', explode( ',', $atts['product_tag'] ) );
    				foreach ( $tags as $tag ) : ?>
        				<div class="amz-simple-label-tsbox"><?php echo esc_html( $tag ); ?></div>
    				<?php endforeach; ?>
				<?php endif; ?>

				<?php
				// Produktdetails in Liste ausgeben.
				$details   = explode( "\n", $product_data['details'] );
				$max_items = intval( $atts['max_list_items'] );
				$count     = 0;
				foreach ( $details as $detail ) {
					if ( $count >= $max_items ) {
						break;
					}
					$trimmed_detail = esc_html(
						mb_strimwidth( $detail, 0, $max_detail_length, '...' )
					);
					echo '<li>' . esc_html( $trimmed_detail ) . '</li>';
					$count++;
				}
				?>

				<?php if ( $discount_percentage > 0 ) : ?>
					<div class="tsproduct-price-reduziert-top-container">
						<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 esc_html_e( 'Angebot reduziert', 'boxyfy' ); ?>
					</div>
				<?php endif; ?>

				<div class="amazon-product-price-container">
					<span class="product-price-<?php echo esc_attr( $atts['box_template'] ); ?>">
						<?php echo esc_html( $product_data['price'] ); ?>
					</span>
					<?php if ( ! empty( $product_data['savingBasis'] ) ) : ?>
						<span class="product-saveprice-<?php echo esc_attr( $atts['box_template'] ); ?>">
							<?php esc_html_e( 'UVP', 'boxyfy' ); ?>
							<?php echo esc_html( $product_data['savingBasis'] ); ?>

							<?php if ( $discount_percentage > 0 ) : ?>
								<span style="color: #227911;">
									<?php
									printf(
										/* translators: -X,XX EUR (amount saved) */
										esc_html__( '- %s EUR', 'boxyfy' ),
										number_format( ( $saving_basis - $price ), 2, ',', '.' )
									);
									?>
								</span>
							<?php endif; ?>
						</span>
					<?php endif; ?>
				</div>

				<!-- Produktbuttons -->
				<div class="amazon-produkt-tsbuttons-zwei">
					<a
						href="<?php echo esc_url( $purchase_url ); ?>"
						target="_blank"
						rel="noopener"
						class="amazon-product-button<?php echo esc_attr( ( 'simple2' === $atts['box_template'] ) ? '2' : '1' ); ?>"
					>
						<?php echo esc_html( $atts['button_title'] ); ?>
					</a>

					<?php if ( ! empty( $atts['next_button'] ) && ! empty( $atts['next_button_link'] ) ) : ?>
						<a
							href="<?php echo esc_url( $atts['next_button_link'] ); ?>"
							target="_blank"
							rel="<?php echo esc_attr( $atts['next_button_rel'] ); ?>"
							class="amazon-product-button<?php echo esc_attr( ( 'simple2' === $atts['box_template'] ) ? '2' : '1' ); ?> extra-button"
						>
							<?php echo esc_html( $atts['next_button'] ); ?>
						</a>
					<?php endif; ?>
				</div>
				<div class="disclaimer-amz-box-simple">
					<?php echo esc_html__( 'Preis inkl. MwSt', 'boxyfy' ) . ' | '
	  	 				. esc_html__( 'Zuletzt aktualisiert:', 'boxyfy' ) . ' '
	   					. esc_html( date_i18n( 'd.m.Y H:i', current_time( 'timestamp' ) ) ) . ' | '
	   					. esc_html__( 'Preis kann sich geändert haben', 'boxyfy' ) . ' | '
	   					. esc_html__( 'Affiliate-Links enthalten', 'boxyfy' );
					?>
				</div>
			</ul>
		</div>
	</div>
</div>
<?php
// Shortcode-Ausgabe zurückgeben.
	return ob_get_clean();
}
add_shortcode( 'boxyfy_amazon_productbox', 'boxyfy_amazon_productbox_shortcode' );

/**
 * Ruft Amazon-Produktdaten über die PA-API ab.
 *
 * @param string $asin ASIN des Produkts
 * @return array|null
 */
function boxyfy_get_amazon_product_data( $asin ) {

	if ( ! boxyfy_is_license_valid() ) {
		return null;
	}

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

	$host        = $options['host'];
	$region      = $options['region'];
	$access_key  = $options['access_key'];
	$secret_key  = $options['secret_key'];
	$partner_tag = $options['partner_tag'];

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

	$uri_path = '/paapi5/getitems';
	$url      = 'https://' . $host . $uri_path;

	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( $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', $host );
	$awsv4->addHeader( 'x-amz-target', 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.GetItems' );

	$headers = $awsv4->getHeaders();

	$args = array(
		'method'  => 'POST',
		'body'    => $payload,
		'headers' => $headers,
		'timeout' => 30,
	);

	$response = wp_remote_post( $url, $args );
	if ( is_wp_error( $response ) ) {
		return null;
	}

	$body = wp_remote_retrieve_body( $response );
	if ( empty( $body ) ) {
		return null;
	}

	$response_data = json_decode( $body, true );
	if ( isset( $response_data['ItemsResult']['Items'] ) && count( $response_data['ItemsResult']['Items'] ) > 0 ) {
		$item = $response_data['ItemsResult']['Items'][0];

		$title = $item['ItemInfo']['Title']['DisplayValue'] ?? '';
		$thumbnail = $item['Images']['Primary']['Large']['URL'] ?? '';

		$additional_images = array();
		if ( isset( $item['Images']['Variants'] ) ) {
			foreach ( $item['Images']['Variants'] as $variant ) {
				if ( isset( $variant['Large']['URL'] ) ) {
					$additional_images[] = $variant['Large']['URL'];
				}
			}
		}

		$details = '';
		if ( isset( $item['ItemInfo']['Features']['DisplayValues'] ) ) {
			$details = implode( "\n", $item['ItemInfo']['Features']['DisplayValues'] );
		}

		$price        = $item['Offers']['Listings'][0]['Price']['DisplayAmount'] ?? '';
		$saving_basis = $item['Offers']['Listings'][0]['SavingBasis']['DisplayAmount'] ?? '';

		return array(
			'title'             => $title,
			'primary_image'     => $thumbnail,
			'additional_images' => $additional_images,
			'details'           => $details,
			'price'             => $price,
			'savingBasis'       => $saving_basis,
		);
	}

	return null;
}
