<?php

namespace Blazemedia\Affiliation\Inventory;

use Blazemedia\Affiliation\AdminUserInterface\Settings;
use Blazemedia\Affiliation\Utils\HttpRequest;


class InventoryItemSender {
    
    
    protected InventoryItemData $itemData;
    

    public function __construct() {
    
        add_action( 'save_post', [ $this, 'sendInventoryData'], 10, 3 );
    }


    function sendInventoryData( $post_id, $post, $update ) {

        if(BLAZE_AFFILIATION_INVENTORY_SENDER == false) return;
        // Controlla se si tratta di un salvataggio automatico
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
        
        /// verifica che il post type corrente sia abilitato
		/// per funzionare deve essre già pronta la query
		if ( !Settings\PostTypes::isPostTypeEnabled($post->post_type) ) return;
        
        // Controlla lo stato del post
        if ( !in_array( $post->post_status, [ 'publish', 'future' ] ) ) return;
        
        
        $this->itemData = new InventoryItemData( $post );

        $url = BLZ_API_RENDERING_MANAGER . 'content-render';
        
        $response = HttpRequest::post( $url, $this->itemData->toJson(), true );

        $content = json_decode($response, true);
        
        //  Gestisci l'errore
         if ($content->status == 'failure') { 
             echo "Problemi con la chiamata:\n";
             echo BLZ_API_RENDERING_MANAGER . "create-inventory-item\n";
             print_r($content);
             echo "\n";
             die();
         }

    }


}
