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

<?php
// Initializing the batch index
$b = 0;
$response_updated_product_batch = array();

// Preparing the products for the update
foreach($product_batch as $batch_asin ) {
	
	$batch_prod_id = '';
    
    $asin_to_id = new WP_Query(
        array(
            'showposts'   => 1,
            'post_type'   => $this->plugin['prefix'] . '_product',
            'meta_query'  => array(
                array(
                    'key'     => 'asin',
                    'value'   => $batch_asin,
                    'compare' => '='
                )
            )
        )
    );
    
    if( $asin_to_id->have_posts() ) {
        $batch_prod_id = $asin_to_id->posts[0]->ID;
		
   		update_post_meta( $batch_prod_id, 'last_update_attempt', time());
		update_post_meta( $batch_prod_id, 'last_update_status', 'Update failed before the API call');
    }

    // Connecting the ASIN, the Product ID and the current product index for later use
    $response_updated_product_batch[$b] = array( 'id' => $batch_prod_id , 'asin' => $batch_asin );

    wp_reset_postdata();
    
    $b++;
	
}

// API set to be used
$chosen_api = sanitize_text_field( get_option('amazingaffiliates_settings_api_apiToUse') );
if(empty($chosen_api)) $chosen_api = 'PAAPI5';

// PAAPI5 CALL
if( $chosen_api == 'PAAPI5' ) {
    require_once( AMAZINGAFFILIATES_PLUGIN_URI . '/admin/partials/product_update_call_PAAPI5.php'  );
}

// Creators API CALL
if( $chosen_api == 'CreatorsAPI' ) {
    require_once( AMAZINGAFFILIATES_PLUGIN_URI . '/admin/partials/product_update_call_CreatorsAPI.php'  );
}

// Formal analysis of the API response
if(	$response === false	) {
    $update_msg =  'ERROR, Failed to decode the PAAPI5 JSON response';
	if($is_autoupdate) update_option( 'amazingaffiliates_settings_product_pages_auto_update_lastupdatestatus', 'the APIs failed to response' );
    return;
}

// Unpacking the response
if($is_autoupdate) update_option( 'amazingaffiliates_settings_product_pages_auto_update_lastupdatestatus', 'there was an error in decoding the response' );
$itemResult = json_decode($response);

// Checking for Errors in the response
if($is_autoupdate) update_option( 'amazingaffiliates_settings_product_pages_auto_update_lastupdatestatus', 'the APIs answered with an error: ' . $response );

// Re-initializing the batch index
$b = 0;

// Update Phase 1: Recording the last API response in the products data
foreach($product_batch as $batch_asin ) {
	
	if($is_autoupdate) update_option( 'amazingaffiliates_settings_product_pages_auto_update_lastupdatestatus', 'there was an error decoding the data of the product #' . ($b+1) . ' of the ASIN payload' );
	
    $batch_prod_id = $response_updated_product_batch[$b]['id'];
    
    // Recording the last API response in the products data
    $response_json_decoded = json_decode($response);
	if(isset($response_json_decoded->Errors) OR isset($response_json_decoded->reason)) {
		
		if(isset($response_json_decoded->Errors)) {
			$has_issues_code = wp_json_encode($response_json_decoded->Errors[0]->Code);
			update_post_meta( $batch_prod_id, 'has_issues', $has_issues_code );
			update_post_meta( $batch_prod_id, 'has_issues_ext', wp_json_encode($response_json_decoded->Errors[0]->Message) );
			update_post_meta( $batch_prod_id, 'last_update_status', 'Issues found.');
		}
		elseif(isset($response_json_decoded->reason)) {
			$has_issues_code = wp_json_encode($response_json_decoded->reason);
			update_post_meta( $batch_prod_id, 'has_issues', $has_issues_code );
			update_post_meta( $batch_prod_id, 'has_issues_ext', wp_json_encode($response_json_decoded->message) );
			update_post_meta( $batch_prod_id, 'last_update_status', 'Issues found.');
		}
		
		$has_issues		= !empty($has_issues_code);
		$has_eligibility_issues = str_contains($has_issues_code, 'ligib');
		$dead_product	= ($has_issues AND !$has_eligibility_issues);
		
		if($dead_product) {				
			update_post_meta( $batch_prod_id, 'not_updateable', 1);					
			update_post_meta( $batch_prod_id, 'availability', 'Out of stock');				
			update_post_meta( $batch_prod_id, 'availability_msg', 'Probably discontinued. Check on Amazon!');			
			update_post_meta( $batch_prod_id, 'stock', false);
		}
		else {				
			update_post_meta( $batch_prod_id, 'not_updateable', 0);
			update_post_meta( $batch_prod_id, 'availability', 'Unknown');				
			update_post_meta( $batch_prod_id, 'availability_msg', 'Unable to get current availability info');						
			update_post_meta( $batch_prod_id, 'stock', true);
		}

	}
    else {
        update_post_meta( $batch_prod_id, 'has_issues', '');
        update_post_meta( $batch_prod_id, 'has_issues_ext', '' );
	    update_post_meta( $batch_prod_id, 'last_update_status', '');		
		update_post_meta( $batch_prod_id, 'not_updateable', 0);
	    
	    // Recording the time and status of this last update
   	    update_post_meta( $batch_prod_id, 'last_update', time());
    }
    
    // Recording the current API response
    update_post_meta( $batch_prod_id, 'api_response', $response );
    
    // Increasing the batch index
    $b++;
    
}

// PAAPI5 decode
if( $chosen_api == 'PAAPI5' ) {
    require_once( AMAZINGAFFILIATES_PLUGIN_URI . '/admin/partials/product_update_decode_PAAPI5.php'  );
}

// Creators API decode
if( $chosen_api == 'CreatorsAPI' ) {
    require_once( AMAZINGAFFILIATES_PLUGIN_URI . '/admin/partials/product_update_decode_CreatorsAPI.php'  );
}



if($is_autoupdate) update_option( 'amazingaffiliates_settings_product_pages_auto_update_lastupdatestatus', 'there were no issues.' );
$update_status = "Success";