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

<?php

// Avoiding a NULL call
if(count($product_batch)==0) return;

// Getting the Token
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') );

// Setting the header
$headers = array(
	'Authorization' => 'Bearer ' . $access_token . ', Version ' . $version,
	'Content-Type' => 'application/json',
	'x-marketplace' => $marketplace
);

$url = 'https://creatorsapi.amazon/catalog/v1/getItems';

// Setting the payload
$payload = json_encode(array(
	'itemIds' => $product_batch,
	'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
));

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

$full_response = wp_remote_post($url, array(
	'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;