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

<?php

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

// Update Phase 2: Decoding and recording the updated data fields in the products
foreach($response_updated_product_batch as $response_updated_product ) {
	
	$response_json_decoded = json_decode($response);
	
	if(isset($response_json_decoded->Errors) OR isset($response_json_decoded->reason)) {
		continue;
	}
	
	if($is_autoupdate) update_option( 'amazingaffiliates_settings_product_pages_auto_update_lastupdatestatus', 'there was an error updating product #' . ($b+1) . ' of the ASIN payload' );
    
    $batch_asin = $response_updated_product['asin'];
    $batch_prod_id = $response_updated_product['id'];
    $batch_title = '';
    $batch_img_url = '';
    $batch_url = '';
    $batch_current_price = '';
    $batch_list_price = '';
    $batch_availability = '';
    $batch_availability_msg = '';
    $batch_condition = '';
    $batch_brand = '';
    $batch_oem = '';
    $batch_model_number = '';
    $batch_model = '';
	
    // image upload and binding
    if( isset( $itemResult->ItemsResult->Items[$b]->Images->Primary->Large->URL )  ) {
        
        $batch_img_url = $itemResult->ItemsResult->Items[$b]->Images->Primary->Large->URL;
        
        $img_unique_title = '[DONT TOUCH THIS FIELD] image for ASIN ' . $batch_asin;
        
        $doubles = new WP_Query(
            array(
                'showposts' => 1,
                'post_type' => 'attachment',
                'post_mime_type' =>'image',
                'post_status' => 'inherit',
                'title' => $img_unique_title
            )
        ); 
        
        if( count( $doubles->posts ) < 1 ) {
            require_once(ABSPATH . 'wp-admin/includes/media.php');
            require_once(ABSPATH . 'wp-admin/includes/file.php');
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $thumbnail_id = media_sideload_image( $batch_img_url, intval($batch_prod_id), $img_unique_title, 'id' );
        }
        else {
            $thumbnail_id = $doubles->posts[0]->ID;
        }
        
        wp_reset_postdata();
        
        if( empty( get_post_meta( $thumbnail_id, '_wp_attachment_image_alt', true ) ) ) {
            update_post_meta( $thumbnail_id, '_wp_attachment_image_alt', $batch_title );
        }
        
        if( is_numeric($thumbnail_id) ) {
            
            update_post_meta( $batch_prod_id, 'primary_img', $thumbnail_id );
            
            if( empty( get_the_post_thumbnail( $batch_prod_id ) ) ) {
                set_post_thumbnail( $batch_prod_id, $thumbnail_id );
            }
            
        }
        
    }
    if( isset( $itemResult->ItemsResult->Items[$b]->Images->Primary->Large->URL )  ) {
        
        $batch_img_large_url = $itemResult->ItemsResult->Items[$b]->Images->Primary->Large->URL;
        
        update_post_meta( $batch_prod_id, 'primary_img_url', $batch_img_large_url );
        
    }
 
    // updating product title and custom title     
    if( isset( $itemResult->ItemsResult->Items[$b]->ItemInfo->Title->DisplayValue )  ) {
        
        $batch_title = $itemResult->ItemsResult->Items[$b]->ItemInfo->Title->DisplayValue;
        
       	wp_update_post( 
            array(
                'ID'            => $batch_prod_id ,
                'post_title'    => $batch_title
            ),
            true
       	);
       	
       	update_post_meta( $batch_prod_id, 'asin', $batch_asin );
       	
       	$custom_title = get_post_meta( $batch_prod_id, 'custom_title', true);
        if( $custom_title == '' ) {
            update_post_meta( $batch_prod_id, 'custom_title', $batch_title);
        }
       	
    }
    
    // updating product affiliate link
    if( isset( $itemResult->ItemsResult->Items[$b]->DetailPageURL )  ) {
        
        $batch_affiliate_link = $itemResult->ItemsResult->Items[$b]->DetailPageURL;
        
       	if($batch_affiliate_link != '') {
            update_post_meta( $batch_prod_id, 'affiliate_link', $batch_affiliate_link);
       	}
        
    }
	
	// OFFERSV2 FIX

		// Current Price
		if( isset( $itemResult->ItemsResult->Items[$b]->OffersV2->Listings[0]->Price->Money->Amount )  )	{

			$batch_current_price = $itemResult->ItemsResult->Items[$b]->OffersV2->Listings[0]->Price->Money->Amount;
			$batch_current_price_purified = intval($batch_current_price*100)/100;
			
			if($batch_current_price != '') {
				update_post_meta( $batch_prod_id, 'current_price', $batch_current_price_purified);
			}

		}
	
		// Currency
		if( isset( $itemResult->ItemsResult->Items[$b]->OffersV2->Listings[0]->Price->Money->Currency )  )	{

			$amazonCurrencies = array(
				'USD' => '$',     // Dollaro Statunitense (USA, Canada, Australia, etc.)
				'EUR' => '€',     // Euro (Eurozona: Italia, Germania, Francia, Spagna, etc.)
				'GBP' => '£',     // Sterlina Britannica (Regno Unito)
				'JPY' => '¥',     // Yen Giapponese (Giappone)
				'CAD' => '$',     // Dollaro Canadese (Canada)
				'AUD' => '$',     // Dollaro Australiano (Australia)
				'INR' => '₹',     // Rupia Indiana (India)
				'CNY' => '¥',     // Yuan Cinese (Cina)
				'MXN' => '$',     // Peso Messicano (Messico)
				'BRL' => 'R$',    // Real Brasiliano (Brasile)
				'AED' => 'AED',   // Dirham EAU (Emirati Arabi Uniti)
				'SGD' => '$',     // Dollaro di Singapore (Singapore)
				'SEK' => 'kr',    // Corona Svedese (Svezia)
				'PLN' => 'zł',    // Złoty Polacco (Polonia)
				'TWD' => 'NT$',   // Nuovo Dollaro Taiwanese (Taiwan)
				'TRY' => '₺',     // Lira Turca (Turchia)
				'ZAR' => 'R',     // Rand Sudafricano (Sudafrica)
				'DKK' => 'kr.',   // Corona Danese (Danimarca)
				'HUF' => 'Ft',    // Fiorino Ungherese (Ungheria)
				'ILS' => '₪',     // Nuovo Shekel Israeliano (Israele)
				'HKD' => '$',     // Dollaro di Hong Kong (Hong Kong)
				'CHF' => 'CHF',   // Franco Svizzero (Svizzera)
				'PHP' => '₱',     // Peso Filippino (Filippine)
				'THB' => '฿',     // Baht Thailandese (Thailandia)
				'KRW' => '₩',     // Won Sudcoreano (Corea del Sud)
				'SAR' => 'SAR',   // Riyal Saudita (Arabia Saudita)
				'CZK' => 'Kč',    // Corona Ceca (Repubblica Ceca)
				'NZD' => '$',     // Dollaro Neozelandese (Nuova Zelanda)
				'NOK' => 'kr',    // Corona Norvegese (Norvegia)
				'RON' => 'lei'   // Leu Rumeno (Romania)
			);

			$batch_currency_code = $itemResult->ItemsResult->Items[$b]->OffersV2->Listings[0]->Price->Money->Currency;
			$batch_currency = $amazonCurrencies[$batch_currency_code];

			if($batch_currency != '') {
				update_post_meta( $batch_prod_id, 'currency', $batch_currency);
			}

		}
	
		// List Price
		if( isset( $itemResult->ItemsResult->Items[$b]->OffersV2->Listings[0]->Price->SavingBasis->Money->Amount )  ) {
        
			$batch_list_price = $itemResult->ItemsResult->Items[$b]->OffersV2->Listings[0]->Price->SavingBasis->Money->Amount;
			$batch_list_price_purified = intval($batch_list_price*100)/100;

			if( empty( $batch_list_price_purified) OR $batch_list_price_purified < $batch_current_price_purified )	{
				$batch_list_price_purified = $batch_current_price_purified; 
			}

			if($batch_list_price_purified != '') {
				update_post_meta( $batch_prod_id, 'list_price', $batch_list_price_purified);
			}

		}
		else {

			if($batch_current_price != '') {
			   update_post_meta( $batch_prod_id, 'list_price', $batch_current_price_purified);
			}

		}
	
		// Discount
		if(intval($batch_list_price_purified) > intval($batch_current_price_purified)) {
			$batch_discount = round(
				( ( floatval($batch_list_price_purified) - floatval($batch_current_price_purified) ) / floatval($batch_list_price_purified) ) * 100,
				0
			);
		}
		else {
			$batch_discount = 0;
		}
		update_post_meta( $batch_prod_id, 'discount', $batch_discount);

		// Offer Status
		if( $batch_discount > 0 ) {
			$batch_offer = 1;
		}
		else {
			$batch_offer = 0;
		}
		update_post_meta( $batch_prod_id, 'offer', $batch_offer);
	
		// Availability Type
	    if( isset( $itemResult->ItemsResult->Items[$b]->OffersV2->Listings[0]->Availability->Type )  )	{
        
			$batch_availability = $itemResult->ItemsResult->Items[$b]->OffersV2->Listings[0]->Availability->Type;

			if($batch_availability != '') {
				update_post_meta( $batch_prod_id, 'availability', $batch_availability);
			}

		}
		
		// Availability Message
	    if( isset( $itemResult->ItemsResult->Items[$b]->OffersV2->Listings[0]->Availability->Message )  )	{
        
			$batch_availability_msg = $itemResult->ItemsResult->Items[$b]->OffersV2->Listings[0]->Availability->Message;

			if($batch_availability_msg != '') {
				update_post_meta( $batch_prod_id, 'availability_msg', $batch_availability_msg);
			}
			else {
				$batch_availability_msg = get_post_meta( $batch_prod_id, 'availability_msg', true);
			}

		}

		// Condition
		if( isset( $itemResult->ItemsResult->Items[$b]->OffersV2->Listings[0]->Condition->Value )  )	{

			$batch_condition = $itemResult->ItemsResult->Items[$b]->OffersV2->Listings[0]->Condition->Value;

			if($batch_condition != '') {
				update_post_meta( $batch_prod_id, 'condition-value', $batch_condition);
			}

		}
    
		// Stock Status
		if( str_contains(strtolower($batch_availability), 'in_stock') AND str_contains(strtolower($batch_condition), 'new') ) {
			$stock = 1;
		}
		elseif( str_contains(strtolower($batch_availability), 'out') OR $batch_availability == '' ) {
			$stock = 0;
		}
		else {
			$stock = 0.5;
		}  
		update_post_meta( $batch_prod_id, 'stock', $stock );
 
		// Merchant Name
		if( isset( $itemResult->ItemsResult->Items[$b]->OffersV2->Listings[0]->MerchantInfo->Name )  ) {

			$batch_merchantinfo = $itemResult->ItemsResult->Items[$b]->OffersV2->Listings[0]->MerchantInfo->Name;

			if($batch_merchantinfo != '') {
				update_post_meta( $batch_prod_id, 'merchant_info-name', $batch_merchantinfo );
			}

		}
    
    // updating branding info
    if( isset( $itemResult->ItemsResult->Items[$b]->ItemInfo->ByLineInfo->Brand->DisplayValue )  )	{
        
        $batch_brand = $itemResult->ItemsResult->Items[$b]->ItemInfo->ByLineInfo->Brand->DisplayValue;
      	
    }
    
    if( isset( $itemResult->ItemsResult->Items[$b]->ItemInfo->ByLineInfo->Manufacturer->DisplayValue )  )	{
        
      	$batch_oem = $itemResult->ItemsResult->Items[$b]->ItemInfo->ByLineInfo->Manufacturer->DisplayValue;
      	
    }
    
    if( empty( get_post_meta( $batch_prod_id, 'custom_brand', true) ) ) {
        
        if( ! empty( $batch_brand ) ) {
            $batch_custom_brand = $batch_brand;
        }
        else {
            $batch_custom_brand = $batch_oem;
        }
        
    }
    else {
        
        $batch_custom_brand = get_post_meta( $batch_prod_id, 'custom_brand', true);
        
    }
    
    if( isset( $itemResult->ItemsResult->Items[$b]->ItemInfo->ManufactureInfo->ItemPartNumber->DisplayValue )  ) {
        
        $batch_model_number = $itemResult->ItemsResult->Items[$b]->ItemInfo->ManufactureInfo->ItemPartNumber->DisplayValue;
      	
    }
    
    if( isset( $itemResult->ItemsResult->Items[$b]->ItemInfo->ManufactureInfo->Model->DisplayValue )  )	{
        
      	$batch_model = $itemResult->ItemsResult->Items[$b]->ItemInfo->ManufactureInfo->Model->DisplayValue;
        
    }
    
    if( empty( get_post_meta( $batch_prod_id, 'custom_model', true) ) ) {
        
        $batch_custom_model = $batch_model;
        
        if( ! empty( $batch_model ) ) {
            $batch_custom_model = $batch_model;
        }
        else {
            $batch_custom_model = $batch_model_number;
        }
        
    }
    else {
        
        $batch_custom_model = get_post_meta( $batch_prod_id, 'custom_model', true);
        
    }
    
    $branding = array(
        "brand"             => $batch_brand,
        "oem"               => $batch_oem,
        "custom_brand"      => $batch_custom_brand,
        "model_number"      => $batch_model_number,
        "model"             => $batch_model,
        "custom_model"      => $batch_custom_model
    );
    
    if ( ! empty($branding["brand"]) ) {
        update_post_meta( $batch_prod_id, 'brand', $branding["brand"]);
  	}
  	
  	if ( ! empty($branding["oem"]) ) {
      	    update_post_meta( $batch_prod_id, 'oem', $branding["oem"]);
    }
    
    if ( ! empty($branding["custom_brand"]) ) {
      	    update_post_meta( $batch_prod_id, 'custom_brand', $branding["custom_brand"]);
    }
    
    if ( ! empty($branding["model_number"]) ) {
        update_post_meta( $batch_prod_id, 'model_number', $branding["model_number"]);
  	}
  	
	if ( ! empty($branding["model"]) ) {
        update_post_meta( $batch_prod_id, 'model', $branding["model"]);
  	}
  	
  	if ( ! empty($branding["custom_model"]) ) {
        update_post_meta( $batch_prod_id, 'custom_model', $branding["custom_model"]);
    }
    
    // updating details
    if( isset( $itemResult->ItemsResult->Items[$b]->ItemInfo->Features->DisplayValues )  )	{
        
        $batch_details_raw = $itemResult->ItemsResult->Items[$b]->ItemInfo->Features->DisplayValues;
        
      	if ( ! empty($batch_details_raw) ) {
              
            if ( is_array($batch_details_raw) ) {
                
              $batch_details = '<ul>';
              foreach($batch_details_raw as $batch_detail){
                  $batch_details .= '<li>' . $batch_detail . '</li>';
              }
              $batch_details .= '</ul>';
              
            }
            else{
                
              $batch_details = strval($itemResult->ItemsResult->Items[$b]->ItemInfo->Features->DisplayValues);
              
            }
            
            update_post_meta( $batch_prod_id, 'details', $batch_details);
            
      	}
    }
    
    // signing the complete update with timestamps
    $update_time = time();
   	update_post_meta( $batch_prod_id, 'last_update', $update_time);
    
    // increase the index
    $b++;
    
}

?>