<?php

if (!has_post_thumbnail($post->ID)) {


    self::aicc_log_register($post->ID, 'error', 'Generando imagen destacada (stock) para "'.$post->post_title.'"', 'aicc_bulk_curation_image');

    /*
     * Obtenemos la entidad @var $entity
     */
    include(AICC_PLUGIN_DIR . 'functions/obtainEntity.php');

    if (!$entity) {
        $discarded++;
        update_option('aicc_bulk_discarded_count', $discarded);
        $error_message = 'Error al obtener la entidad.';
        self::aicc_log_register($post->ID, 'error', $error_message, 'aicc_bulk_curation_image');
        return false;
    }



    /*
     * Obtenemos las imágenes @var $featured_image $post_images
     */
    $stock_images = self::aicc_get_images($entity, $post_title, $source);
    $featured_image = $stock_images['featured_image'];

    if (!$featured_image) {
        $discarded++;
        update_option('aicc_bulk_discarded_count', $discarded);
        $error_message = 'Error al obtener imágenes para "'.$post->post_title.'" con entidad "'.$entity.'"';
        self::aicc_log_register($post->ID, 'error', $error_message, 'aicc_bulk_curation_image');
        return false;
    }



    /*
     * Agregamos la imagen destacada si corresponde
     */
    $processed_count++;
    update_option('aicc_bulk_processed_count', $processed_count);
    try {
        $temp_image_path = self::aicc_download_image_to_temp($featured_image);
        $processed_image_path = self::aicc_process_image($temp_image_path, '');
        if ($processed_image_path) {
            $attachment_id = self::aicc_move_image_to_media($processed_image_path, $post_id, $post_title);
            if ($attachment_id) {
                set_post_thumbnail($post_id, $attachment_id);
                $ids_processed[$post_id] = '';
                update_option('aicc_bulk_ids_processed', $ids_processed);
            }
            unlink($temp_image_path);
            sleep(1);
        } else {
            $discarded++;
            update_option('aicc_bulk_discarded_count', $discarded);
            $error_message = 'Error caraiccdo la imagen en la biblioteca de medios.';
            self::aicc_log_register($post_id, 'error', $error_message, 'aicc_GenerateContent');
        }
    } catch (Exception $e) {
        $discarded++;
        update_option('aicc_bulk_discarded_count', $discarded);
        $error_message = 'Error al crear la imagen: ' . $e->getMessage();
        self::aicc_log_register($post->ID, 'error', $error_message, 'aicc_bulk_curation_image');
    }

    $totalCost = $costPromptImage;
    update_option('aicc_bulk_total_cost', $totalCost);

}


?>
