<?php
/**
 * Renders the Amazon API test page.
 *
 * This function displays a form to test if the configured Amazon API credentials work.
 * It performs a price lookup for a given ASIN using the ProductAdvertisingAPI.
 *
 * @package Boxyfy
 */

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

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

	$price = '';
	$error = '';

	if ( isset( $_POST['submit'] ) ) {
		if ( ! isset( $_POST['boxyfy_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['boxyfy_nonce'] ) ), 'boxyfy_action' ) ) {
			wp_die( esc_html__( 'Sicherheitsüberprüfung fehlgeschlagen.', 'boxyfy' ) );
		}

		$asin = isset( $_POST['boxyfy_asin'] ) ? sanitize_text_field( wp_unslash( $_POST['boxyfy_asin'] ) ) : '';

		if ( empty( $asin ) ) {
			$error = 'Bitte eine ASIN eingeben.';
		} else {
			$host       = $options['host'];
			$region     = $options['region'];
			$accessKey  = $options['access_key'];
			$secretKey  = $options['secret_key'];
			$partnerTag = $options['partner_tag'];
			$uriPath    = '/paapi5/getitems';

			$payload = json_encode(
				array(
					'ItemIds'     => array( $asin ),
					'PartnerTag'  => $partnerTag,
					'PartnerType' => 'Associates',
					'Marketplace' => 'www.amazon.de',
					'Resources'   => array( 'Offers.Listings.Price' ),
				)
			);

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

				$awsv4 = new AwsV4( $accessKey, $secretKey );
				$awsv4->setRegionName( $region );
				$awsv4->setServiceName( 'ProductAdvertisingAPI' );
				$awsv4->setPath( $uriPath );
				$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();

				$response = wp_remote_post(
					'https://' . $host . $uriPath,
					array(
						'timeout'   => 30,
						'sslverify' => false,
						'headers'   => $headers,
						'body'      => $payload,
					)
				);

				if ( is_wp_error( $response ) ) {
					$error = 'Fehler bei der API-Anfrage: ' . esc_html( $response->get_error_message() );
				} else {
					$body = wp_remote_retrieve_body( $response );
					if ( empty( $body ) ) {
						$error = 'Leere API-Antwort erhalten.';
					} else {
						$response_data = json_decode( $body, true );
						if (
							isset( $response_data['ItemsResult']['Items'][0]['Offers']['Listings'][0]['Price']['DisplayAmount'] )
						) {
							$price = $response_data['ItemsResult']['Items'][0]['Offers']['Listings'][0]['Price']['DisplayAmount'];
						} else {
							$error = 'Keine Preisangabe gefunden.';
						}
					}
				}
			}
		}
	?>
	<div class="wrap">
		<h1><?php esc_html_e( 'Amazon-API-Anfrage durchführen – Teste hier Deine Zugangsdaten:', 'boxyfy' ); ?></h1>
		<form method="post" action="">
			<?php wp_nonce_field( 'boxyfy_action', 'boxyfy_nonce' ); ?>
			<table class="form-table">
				<tr valign="top">
					<th scope="row"><?php esc_html_e( 'Beispiel-Amazon-ASIN eingeben:', 'boxyfy' ); ?></th>
					<td>
						<input type="text" name="boxyfy_asin" value="<?php echo isset( $asin ) ? esc_attr( $asin ) : ''; ?>" />
					</td>
				</tr>
			</table>
			<?php submit_button( 'Preisabruf jetzt testen' ); ?>
		</form>

		<?php if ( $price ) : ?>
			<p><?php esc_html_e( 'Der Preis-Abruf funktioniert. Die Amazon-API-Anbindung war damit erfolgreich.', 'boxyfy' ); ?></p>
			<h2><?php echo sprintf( esc_html__( 'Preis für die ASIN: %s', 'boxyfy' ), esc_html( $price ) ); ?></h2>
		<?php elseif ( $error ) : ?>
			<h2><?php echo esc_html( $error ); ?></h2>
		<?php endif; ?>
	</div>
	<?php
}
