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

<?php 
$token = get_transient('amazingaffiliates_api_token_cache');
if( $token !== false ) return $token;

$credential_id = get_option('amazingaffiliates_settings_api_accessKey2');
$credential_secret = get_option('amazingaffiliates_settings_api_secretKey2');
$version = get_option('amazingaffiliates_settings_api_version2');
if( empty($version) ) $version = '3.2';
$token_endpoints = array(
    '2.1' => 'https://creatorsapi.auth.us-east-1.amazoncognito.com/oauth2/token',
    '2.2' => 'https://creatorsapi.auth.eu-south-2.amazoncognito.com/oauth2/token',
    '2.3' => 'https://creatorsapi.auth.us-west-2.amazoncognito.com/oauth2/token',
	'3.1' => 'https://api.amazon.com/auth/o2/token',
    '3.2' => 'https://api.amazon.co.uk/auth/o2/token',
    '3.3' => 'https://api.amazon.co.jp/auth/o2/token'
);
$token_endpoint = $token_endpoints[$version];
$scopes = array(
	'2.1' => 'creatorsapi/default',
    '2.2' => 'creatorsapi/default',
    '2.3' => 'creatorsapi/default',
	'3.1' => 'creatorsapi::default',
    '3.2' => 'creatorsapi::default',
    '3.3' => 'creatorsapi::default'
);
$scope = $scopes[$version];

$response = wp_remote_post($token_endpoint, [
    'headers' => [
        'Content-Type' => 'application/x-www-form-urlencoded'
    ],
    'body' => [
        'grant_type' => 'client_credentials',
        'client_id' => $credential_id,
        'client_secret' => $credential_secret,
        'scope' => $scope
    ],
    'timeout' => 15
]);

if (is_wp_error($response)) return 'no';

if (200 !== wp_remote_retrieve_response_code($response)) return 'no';

$body_json = wp_remote_retrieve_body($response);
$body = json_decode($body_json, true);
    
if (empty($body['access_token'])) return 'no';
    
$new_token = $body['access_token'];
$token_ttl = ( (int) $body['expires_in'] ) - 60 ;
$token_expiry = (int) current_time('timestamp') + $token_ttl + 60;
    
set_transient('amazingaffiliates_api_token_cache_expires', $token_expiry , $token_ttl );
set_transient('amazingaffiliates_api_token_cache', $new_token, $token_ttl );

echo $new_token;

return 'no';

