<?php
/**
 * Metabox: Set Amazon Image as Featured Image.
 *
 * Allows retrieving and setting an Amazon product image as the featured image
 * using an ASIN input and AJAX.
 *
 * - Fetches the product image via AJAX.
 * - Automatically sets the featured image.
 * - Includes security verification with Nonce.
 *
 * @package Boxyfy
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

/**
 * Callback function for the Amazon Image Metabox.
 *
 * Outputs the HTML for setting an Amazon product image as the featured image.
 * All CSS and JavaScript are loaded via external files.
 *
 * @param WP_Post $post The current post object.
 */
function boxyfy_amazon_image_metabox_callback( $post ) {
    // Retrieve the Amazon ASIN from post meta (if available)
    $asin  = get_post_meta( $post->ID, 'tsprodukt_asin2', true );
    $nonce = wp_create_nonce( 'boxyfy_fetch_amazon_image_nonce' );
    ?>
    <p>
        <?php esc_html_e( 'Das Hauptbild des Amazon-Produkts wird als Beitragsbild gesetzt.', 'boxyfy' ); ?>
        <span class="note"><?php esc_html_e( '(Vorher bitte das Produkt veröffentlichen!)', 'boxyfy' ); ?></span>
    </p>
    <label for="tsprodukt_asin2"><?php esc_html_e( 'Amazon-ASIN eingeben:', 'boxyfy' ); ?></label>
    <input type="text" id="tsprodukt_asin2" name="tsprodukt_asin2" value="<?php echo esc_attr( $asin ); ?>" />
    <button type="button" class="button" id="fetch-amazon-image">
        <?php esc_html_e( 'Bild abrufen', 'boxyfy' ); ?>
    </button>
    <div id="error-message" class="error-message"></div>
    <div id="success-message" class="success-message"></div>
    <div id="amazon-image-result"></div>
    <?php
}

/**
 * AJAX Handler for fetching the Amazon image and setting it as the featured image.
 */
function boxyfy_fetch_amazon_image() {
    // Security check: verify the nonce.
    if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'boxyfy_fetch_amazon_image_nonce' ) ) {
        wp_send_json_error( array( 'message' => esc_html__( 'Ungültige Anfrage.', 'boxyfy' ) ) );
    }

    if ( isset( $_POST['asin'], $_POST['post_id'] ) ) {
        $asin    = sanitize_text_field( wp_unslash( $_POST['asin'] ) );
        $post_id = absint( $_POST['post_id'] );
        $image_url = boxyfy_get_amazon_image( $asin );

        if ( $image_url ) {
            // Download the image from the URL and save as attachment.
            $image_id = boxyfy_save_image_as_attachment( $image_url, $post_id );

            if ( $image_id ) {
                // Set the image as the featured image.
                set_post_thumbnail( $post_id, $image_id );
                // Save the new ASIN in post meta.
                update_post_meta( $post_id, 'tsprodukt_asin2', $asin );
                wp_send_json_success( array( 'image_id' => $image_id ) );
            } else {
                wp_send_json_error( array( 'message' => esc_html__( 'Bild konnte nicht gespeichert werden.', 'boxyfy' ) ) );
            }
        } else {
            wp_send_json_error( array( 'message' => sprintf( esc_html__( 'Kein Bild gefunden für die ASIN: %s', 'boxyfy' ), esc_html( $asin ) ) ) );
        }
    } else {
        wp_send_json_error( array( 'message' => esc_html__( 'Keine ASIN oder Post-ID übergeben.', 'boxyfy' ) ) );
    }
}
add_action( 'wp_ajax_boxyfy_fetch_amazon_image', 'boxyfy_fetch_amazon_image' );

/**
 * Retrieves the Amazon image URL based on the given ASIN.
 *
 * @param string $asin The Amazon ASIN.
 * @return string|null The URL of the image if found, otherwise null.
 */
function boxyfy_get_amazon_image( $asin ) {
    $options = get_option(
        'boxyfy_amazon_settings',
        array(
            'access_key'  => '',
            'secret_key'  => '',
            'partner_tag' => '',
            'host'        => 'webservices.amazon.de',
            'region'      => 'eu-west-1',
        )
    );

    $host        = $options['host'];
    $region      = $options['region'];
    $access_key  = $options['access_key'];
    $secret_key  = $options['secret_key'];
    $partner_tag = $options['partner_tag'];

    $payload = wp_json_encode(
        array(
            "ItemIds"     => array( $asin ),
            "Resources"   => array( "Images.Primary.Large" ),
            "PartnerTag"  => $partner_tag,
            "PartnerType" => "Associates",
            "Marketplace" => "www.amazon.de",
        )
    );

    $uri_path = "/paapi5/getitems";
    $url      = 'https://' . $host . $uri_path;
	
	// Instanziiere und konfiguriere AwsV4 für PA-API.
	if ( ! class_exists( 'AwsV4' ) ) {
			require_once plugin_dir_path( BOXYFY_PLUGIN_FILE ) . 'assets/vendor/amazon/boxyfy-class-aws-v4.php';
}

    // Initialize the AwsV4 class.
    $awsv4 = new AwsV4( $access_key, $secret_key );
    $awsv4->setRegionName( $region );
    $awsv4->setServiceName( "ProductAdvertisingAPI" );
    $awsv4->setPath( $uri_path );
    $awsv4->setPayload( $payload );
    $awsv4->setRequestMethod( "POST" );
    $awsv4->addHeader( 'content-encoding', 'amz-1.0' );
    $awsv4->addHeader( 'content-type', 'application/json; charset=utf-8' );
    $awsv4->addHeader( 'host', $host );
    $awsv4->addHeader( 'x-amz-target', 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.GetItems' );

    $headers = $awsv4->getHeaders();
    $args = array(
        'method'  => 'POST',
        'body'    => $payload,
        'headers' => $headers,
        'timeout' => 30,
    );

    $response = wp_remote_post( $url, $args );

    if ( is_wp_error( $response ) ) {
        return null;
    }

    $body = wp_remote_retrieve_body( $response );
    if ( empty( $body ) ) {
        return null;
    }

    $response_data = json_decode( $body, true );
    if ( isset( $response_data['ItemsResult']['Items'] ) && count( $response_data['ItemsResult']['Items'] ) > 0 ) {
        return $response_data['ItemsResult']['Items'][0]['Images']['Primary']['Large']['URL'];
    }

    return null;
}

/**
 * Saves an image from the given URL as an attachment and attaches it to the specified post.
 *
 * @param string $image_url The URL of the image.
 * @param int    $post_id   The post ID to attach the image to.
 * @return int|bool The attachment ID on success, false on failure.
 */
function boxyfy_save_image_as_attachment( $image_url, $post_id ) {
    $tmp = download_url( $image_url );
    if ( is_wp_error( $tmp ) ) {
        return false;
    }
    $file_array = array(
        'name'     => basename( $image_url ),
        'tmp_name' => $tmp,
    );

    if ( is_wp_error( $tmp ) ) {
        wp_delete_file( $file_array['tmp_name'] );
        return false;
    }

    $image_id = media_handle_sideload( $file_array, $post_id );
    if ( is_wp_error( $image_id ) ) {
        wp_delete_file( $file_array['tmp_name'] );
        return false;
    }

    return $image_id;
}