<?php if ( ! defined( 'ABSPATH' ) ) exit; ?>

<?php ob_start(); ?>

<?php
$mode = sanitize_text_field( wp_unslash( $_REQUEST['mode'] ) );
$asin = sanitize_text_field( wp_unslash( $_REQUEST['asin'] ) );
$search = sanitize_text_field( wp_unslash( $_REQUEST['search'] ) );
?>

<?php if( isset( $_REQUEST['nonce'] ) ) : ?>

	<?php if( wp_verify_nonce( sanitize_text_field( wp_unslash( $_REQUEST['nonce'] ) ), 'setup' ) ) : ?>

		<?php /* Search items PAAPI5 test */ ?>
		<?php if($mode=="test_api" || $mode=="test_api_searchitems") : ?>
			<?php
				update_option( 'amazingaffiliates_api_test_successful', 0, true );

				$country		= json_decode( sanitize_text_field( get_option('amazingaffiliates_settings_api_country') ) );
				$partner_tag 	= sanitize_text_field( get_option('amazingaffiliates_settings_api_partner_tag') );
				$partner_type 	= "Associates";
				$marketplace	= $country->amazon_domain;

				$serviceName="ProductAdvertisingAPI";
				$region     = $country->region;
				$accessKey  = sanitize_text_field( get_option('amazingaffiliates_settings_api_accessKey') );
				$secretKey  = sanitize_text_field( get_option('amazingaffiliates_settings_api_secretKey') );
				$payload	=   "{"
								." \"Keywords\": \" . $search . \","
								." \"PartnerTag\": \"" . $partner_tag  . "\","
								." \"PartnerType\": \"" . $partner_type  . "\","
								." \"Marketplace\": \"" . $marketplace  . "\""
								."}";
				$host       = $country->pa_endpoint; 
				$uriPath="/paapi5/searchitems";

				// initializing class AwsV4
				require_once( AMAZINGAFFILIATES_PLUGIN_URI . '/admin/partials/PAAPI5_class_AwsV4.php' );

				$awsv4 = new AmazingAffiliates_custom_AwsV4 ($accessKey, $secretKey);  
				$awsv4->setRegionName($region);
				$awsv4->setServiceName($serviceName);
				$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.SearchItems');
				$headers = $awsv4->getHeaders();
				$headerString = "";
				foreach ( $headers as $key => $value ) {
					$headerString .= $key . ': ' . $value . "\r\n";
				}
				$params = array (
						'http' => array (
							'header' => $headerString,
							'method' => 'POST',
							'content' => $payload
						)
					);
				$stream = @stream_context_create ( $params );

				$full_response = wp_remote_post(
					'https://'.$host.$uriPath, array(
						'headers' => $headers,
						'method' => 'POST',
						'body' => $payload
				));
				$http_response =  (array) $full_response['http_response'];
				$prefix = chr( 0 ) . '*' . chr( 0 );
				$response = $http_response[ $prefix . 'response' ]->body;

				if ($response === false) {
			//        throw new Exception ( "Exception Occured" );
				}

			?>
		<?php endif; ?>

		<?php /* Get items PAAPI5 test */ ?>
		<?php if($mode=="test_api_getitems") : ?>

			<?php
			$asin_payload = $asin;
			$country		=  json_decode( sanitize_text_field( get_option('amazingaffiliates_settings_api_country') ) );

			// setting up API payload
			$partner_tag 	= sanitize_text_field( get_option('amazingaffiliates_settings_api_partner_tag') );
			$partner_type 	= "Associates";
			$marketplace	= $country->amazon_domain;
			$payload =	"{"
						." \"ItemIds\": ["
						."  \" . $asin_payload . \""
						." ],"
						." \"Resources\": ["
						."  \"ItemInfo.Features\","
						."  \"Images.Primary.Medium\","
						."  \"Images.Primary.Large\","
						."  \"ItemInfo.Title\","
						."  \"ItemInfo.ByLineInfo\","
						."  \"ItemInfo.ManufactureInfo\","
						."  \"Offers.Listings.Availability.Message\","
						."  \"Offers.Listings.Availability.Type\","
						."	\"Offers.Listings.Condition\","
						."  \"Offers.Listings.DeliveryInfo.IsAmazonFulfilled\","
						."	\"Offers.Listings.MerchantInfo\","
						."  \"Offers.Listings.Price\","
						."  \"Offers.Listings.SavingBasis\""
						." ],"
						." \"PartnerTag\": \"" . $partner_tag  . "\","
						." \"PartnerType\": \"" . $partner_type  . "\","
						." \"Marketplace\": \"" . $marketplace  . "\""
						."}";

			// setting up class AwsV4 variables 
			$serviceName = "ProductAdvertisingAPI";
			$region     = $country->region;
			$accessKey  = sanitize_text_field( get_option('amazingaffiliates_settings_api_accessKey') );
			$secretKey  = sanitize_text_field( get_option('amazingaffiliates_settings_api_secretKey') );
			$host       = $country->pa_endpoint;
			$uriPath    = "/paapi5/getitems";

			// initializing class AwsV4
			require_once( plugin_dir_path( __FILE__ ) . 'PAAPI5_class_AwsV4.php' );

			$awsv4 = new AmazingAffiliates_custom_AwsV4 ($accessKey, $secretKey);
			$awsv4->setRegionName($region);
			$awsv4->setServiceName($serviceName);
			$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 ();
			$headerString = "";
			foreach ( $headers as $key => $value ) {
				$headerString .= $key . ': ' . $value . "\r\n";
			} 
			$params = array (
				'http' => array (
					'header' => $headerString,
					'method' => 'POST',
					'content' => $payload
				)
			); 
			$stream = stream_context_create( $params ); 

			$full_response = wp_remote_post(
				'https://'.$host.$uriPath, array(
					'headers' => $headers,
					'method' => 'POST',
					'body' => $payload
			));
			$http_response =  (array) $full_response['http_response'];
			$prefix = chr( 0 ) . '*' . chr( 0 );
			$response = $http_response[ $prefix . 'response' ]->body;
			?>
		
		<?php endif; ?>

		<?php /* Creators API test */ ?>
		<?php if($mode=="test_api2" || $mode=="test_api2_searchitems" || $mode=="test_api2_getitems") : ?>
			<?php

//			do_action('amazingaffiliates_api_get_the_token');
			$access_token = get_transient('amazingaffiliates_api_token_cache');
			$marketplace = json_decode( sanitize_text_field( get_option('amazingaffiliates_settings_api_country') ) )->amazon_domain;
			$version = sanitize_text_field( get_option('amazingaffiliates_settings_api_version2') );
			$partner_tag = sanitize_text_field( get_option('amazingaffiliates_settings_api_partner_tag') );

			$headers = [
				'Authorization' => 'Bearer ' . $access_token . ', Version ' . $version,
				'Content-Type' => 'application/json',
				'x-marketplace' => $marketplace
			];

			if($mode=="test_api2_getitems") {
				
				$url = 'https://creatorsapi.amazon/catalog/v1/getItems';

				$payload = json_encode(array(
					'itemIds' => array( $asin ),
					'resources' => array(
						'images.primary.large',
      					'images.primary.small',
						'itemInfo.byLineInfo',
						'itemInfo.features',
						'itemInfo.manufactureInfo',
						'itemInfo.title',
						'offersV2.listings.availability',
						'offersV2.listings.condition',
						'offersV2.listings.merchantInfo',
						'offersV2.listings.price'
					),
					'partnerTag' => $partner_tag,
					'marketplace' => $marketplace
				));
			}

			if($mode=="test_api2" || $mode=="test_api2_searchitems")  {
				
				$url = 'https://creatorsapi.amazon/catalog/v1/searchItems';
				
				if(empty($search)) $search = 'test';
				$payload = json_encode(array(
					'keywords' => $search,
					'resources' => array(
						'images.primary.large',
      					'images.primary.small',
						'itemInfo.byLineInfo',
						'itemInfo.features',
						'itemInfo.manufactureInfo',
						'itemInfo.title',
						'offersV2.listings.availability',
						'offersV2.listings.condition',
						'offersV2.listings.merchantInfo',
						'offersV2.listings.price'
					),
					'searchIndex' => 'All',
					'partnerTag' => $partner_tag,
					'marketplace' => $marketplace,
					'itemCount' => 1
				));
				
			}

			$url = add_query_arg(['marketplace' => $marketplace], $url);

			$full_response = wp_remote_post($url, [
				'headers' => $headers,
				'body'    => $payload,
				'timeout' => 15,
				'method'  => 'POST',
			]);

			$http_response =  (array) $full_response['http_response'];
			$prefix = chr( 0 ) . '*' . chr( 0 );
			$response = $http_response[ $prefix . 'response' ]->body;
			?>
		<?php endif; ?>

		<?php if(!empty($response)) update_option( 'amazingaffiliates_api_test_successful', 1, true ); ?>

		<?php if(empty($response)) $response = '{
		  "Errors": [
				{
				  "Code": "No Answer",
				  "Message": "Failed to fetch the API answer"
				}
			  ]
			}';
		?>

		<?php echo esc_html( base64_encode($asin . '#' . $response) ); ?>	

	<?php endif; ?>

<?php endif; ?>

<?php 

$response = ob_get_clean();

echo wp_json_encode($response);