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

// Ejecuta el refresh programado
function easy_gpt_run_article_refresh() {
    error_log("[EasyGPT] 🔁 Starting article refresh cron...");

    global $easy_gpt_total_cost;
    $easy_gpt_total_cost = 0.0;

    $options = get_option('easy_gpt_options');
    if (empty($options['easy_gpt_refresh_enabled'])) {
        //error_log("[EasyGPT] ❌ Article refresher disabled in settings.");
        return;
    }
    //error_log("Refreshing... 1");
    $license_status = get_option('easy_gpt_license_status');
    $license_expires = get_option('easy_gpt_license_expires');
    $is_license_valid = $license_status === 'valid' && new DateTime($license_expires) > new DateTime();
    if ( ! $is_license_valid ) {
        error_log("[EasyGPT] ❌ Article refresh blocked: license invalid or expired.");
        return;
    }

    error_log("Refreshing... 2");
    $min_age_days = intval($options['easy_gpt_refresh_min_age_days'] ?? 180);
    $priority = $options['easy_gpt_refresh_priority'] ?? 'oldest_first';
    $cutoff_date = date('Y-m-d H:i:s', strtotime("-{$min_age_days} days"));

    $post_id = easy_gpt_find_post_to_refresh($cutoff_date, $priority);
    if (!$post_id) {
        error_log("[EasyGPT] 🚫 No eligible post found for refresh.");
        return;
    }
    
    error_log("Refreshing... 3");
    $post_title = get_the_title($post_id);
    $log_data = [
        'post_id'       => $post_id,
        'post_title'    => $post_title,
        'refresh_time'  => current_time('mysql'),
        'model_used'    => $options['easy_gpt_model'] ?? '',
        'status'        => 'processing'
    ];

    global $wpdb;
    $table_name = $wpdb->prefix . 'easy_gpt_refresh_log';
    $wpdb->insert($table_name, $log_data);
    $log_id = $wpdb->insert_id;
    
    error_log("Refreshing... 4");

    // Guardar imágenes originales
    $original_images = [];
    preg_match_all('/<img[^>]+src="([^">]+)"/i', get_post_field('post_content', $post_id), $matches);
    if (!empty($matches[1])) {
        $original_images = $matches[1];
    }

    // Inicializar log de resultados
    $result = [
        'updated_images'      => 0,
        'new_images_added'    => 0,
        'replaced_featured'   => 0,
        'updated_youtube'     => 0,
        'updated_seo'         => 0,
        'updated_post_date'   => 0,
        'model_used'          => $options['easy_gpt_model'] ?? '',
        'status'              => 'success',
        'error_message'       => null
    ];
    
    error_log("Refreshing... 5");

    try {
        // 1. Regenerar contenido
			
		$original_content = get_post_field('post_content', $post_id);
		
		

		$regen = easy_gpt_regenerate_content_from_post($post_id, $options, $original_images);
		
		    error_log("🧠 Regen result: " . var_export($regen, true));

			if (is_array($regen) && !empty($regen['content'])) {

				$update_images = !empty($options['easy_gpt_refresh_update_images']);
				$model = $options['easy_gpt_model'] ?? 'gpt-4o';
				$is_deepseek = strpos($model, 'deepseek-') === 0;

				if (!$update_images) {
					// ✅ Toggle OFF: no tocar imágenes con IA. Reinsertar las originales de forma determinista.
					$regen['content'] = easy_gpt_preserve_existing_images_in_position($original_content, $regen['content']);
				} else {
					// Toggle ON: ya decides si keep/replace, IA o intervalos, etc.
					if (($options['easy_gpt_refresh_image_replace_existing'] ?? 'keep') === 'keep') {
						$language = get_post_meta($post_id, '_easy_gpt_language', true) ?: ($options['easy_gpt_default_language'] ?? 'en');
						$style = $options['easy_gpt_writing_style'] ?? '';
						$tone = $options['easy_gpt_writing_tone'] ?? '';

						if (!$is_deepseek) {
							$after = easy_gpt_insert_existing_images_with_ai($original_content, $regen['content'], $language, $style, $tone);
						} else {
							$after = easy_gpt_insert_images_every_x_paragraphs($original_content, $regen['content'], 3);
						}

						// Fallback: si la IA no las insertó todas, usa el método determinista.
						$count_imgs = function($html){ preg_match_all('/<img\b[^>]*>/i', $html, $m); return count($m[0]); };
						if ($count_imgs($after) < $count_imgs($original_content)) {
							error_log("[EasyGPT] 🔁 Fallback determinista de imágenes (toggle ON, keep).");
							$after = easy_gpt_preserve_existing_images_in_position($original_content, $regen['content']);
						}
						$regen['content'] = $after;
					}
				}

				error_log("Refreshing... 6");

				wp_update_post([
					'ID' => $post_id,
					'post_content' => wp_kses_post($regen['content'])
				]);
			} else {
			    if (empty(trim(strip_tags($original_content)))) {
                    $error_msg = 'The post was empty or had no usable content.';
                } 
                else{
				    $error_msg = is_array($regen) && isset($regen['error_message']) ? $regen['error_message'] : 'Unknown error while regenerating content.';
			    }
				$result['status'] = 'failed';
				$result['error_message'] = '❌ Content regeneration failed: ' . $error_msg;
				throw new Exception($result['error_message']); // Lanzamos excepción para cortar proceso
			}


		
		error_log("Refreshing... 8");

        // 2. Actualizar imágenes
        $model = $options['easy_gpt_model'] ?? 'gpt-4o';
		
		error_log("[EasyGPT] 🔍 Content before inserting images:\n" . $content);

		
        $result = easy_gpt_refresh_images($post_id, $options, $result, $model);

		
        
        error_log("Refreshing... 7");
        // 3. Actualizar YouTube
        if (easy_gpt_refresh_youtube($post_id, $options)) {
            $result['updated_youtube'] = 1;
        }
		
		error_log("[EasyGPT] 🧾 Content after inserting YouTube:\n" . get_post_field('post_content', $post_id));


        
        error_log("Refreshing... 9");

        // 4. Actualizar SEO
        if (easy_gpt_refresh_seo($post_id, $options)) {
            $result['updated_seo'] = 1;
        }
        
        error_log("Refreshing... 10");

        // 5. Actualizar fecha
        if (!empty($options['easy_gpt_refresh_update_post_date'])) {
            $now = current_time('mysql');
            wp_update_post([
                'ID'            => $post_id,
                'post_date'     => $now,
                'post_date_gmt' => get_gmt_from_date($now)
            ]);
            $result['updated_post_date'] = 1;
        }

    } catch (Exception $e) {
        error_log('[EasyGPT] ❌ Error during article refresh: ' . $e->getMessage());
        $result['status'] = 'failed';
        $result['error_message'] = $e->getMessage();
    }
    
    error_log("Refreshing... 11");

    // Guardar en log de base de datos
    $wpdb->update($table_name, [
        'updated_images'      => $result['updated_images'],
        'new_images_added'    => $result['new_images_added'],
        'replaced_featured'   => $result['replaced_featured'],
        'updated_youtube'     => $result['updated_youtube'],
        'updated_seo'         => $result['updated_seo'],
        'updated_post_date'   => $result['updated_post_date'],
        'refresh_cost'        => floatval($easy_gpt_total_cost),
        'status'              => $result['status'],
        'error_message'       => $result['error_message']
    ], ['id' => $log_id]);

    error_log("[EasyGPT] ✅ Article refreshed (Post ID: {$post_id}) - Status: {$result['status']}");
}


add_action('easy_gpt_run_article_refresh', 'easy_gpt_run_article_refresh');


// Encuentra un artículo elegible para refrescar
function easy_gpt_find_post_to_refresh($cutoff_date, $priority = 'oldest_first') {
    $order = ($priority === 'newest_first') ? 'DESC' : 'ASC';

    $options = get_option('easy_gpt_options');

    // Obtener tipos de post seleccionados (por defecto solo 'post')
    $post_types = $options['easy_gpt_refresh_post_types'] ?? ['post'];

    // Obtener lista de IDs a excluir
    $excluded_ids = array_filter(array_map('intval', explode(',', $options['easy_gpt_exclude_post_ids'] ?? '')));

    $args = [
        'post_type'      => $post_types,
        'posts_per_page' => 1,
        'orderby'        => 'modified',
        'order'          => $order,
        'date_query'     => [
            [
                'column'   => 'post_modified_gmt',
                'before'   => $cutoff_date,
                'inclusive'=> true,
            ],
        ],
        'meta_query' => [
            [
                'key'     => '_easy_gpt_last_refresh',
                'compare'=> 'NOT EXISTS',
            ]
        ],
        'post_status' => 'publish',
        'fields'      => 'ids',
        'post__not_in'=> $excluded_ids,
    ];

    $query = new WP_Query($args);
    if (!empty($query->posts)) {
        return $query->posts[0];
    }

    return false;
}


function easy_gpt_get_days_from_interval($interval) {
    switch ($interval) {
        case 'daily': return 1;
        case 'weekly': return 7;
        case 'monthly': return 30;
        default: return 7;
    }
}

function easy_gpt_get_cron_frequency_minutes() {
    $options = get_option('easy_gpt_options');
    $interval = $options['easy_gpt_refresh_interval'] ?? 'weekly';
    $posts_per_interval = intval($options['easy_gpt_refresh_limit'] ?? 5);

    if ($posts_per_interval < 1) return null;

    $days = easy_gpt_get_days_from_interval($interval);
    $total_minutes = $days * 24 * 60;
    $minutes_between = floor($total_minutes / $posts_per_interval);

    return max(5, $minutes_between); // seguridad: mínimo cada 5 minutos
}

add_filter('cron_schedules', 'easy_gpt_add_dynamic_refresh_schedule');

function easy_gpt_add_dynamic_refresh_schedule($schedules) {
    $minutes = easy_gpt_get_cron_frequency_minutes();
    if (!$minutes) return $schedules;

    $key = 'easy_gpt_custom_' . $minutes;
    if (!isset($schedules[$key])) {
        $schedules[$key] = [
            'interval' => $minutes * 60,
            'display' => __('Easy GPT Refresh every ' . $minutes . ' min')
        ];
    }
    return $schedules;
}

function easy_gpt_schedule_refresher_cron() {
    $minutes = easy_gpt_get_cron_frequency_minutes();
    if (!$minutes) return;

    $hook = 'easy_gpt_run_article_refresh';
    $interval_key = 'easy_gpt_custom_' . $minutes;

    if (!wp_next_scheduled($hook)) {
        wp_schedule_event(time(), $interval_key, $hook);
    }
}

function easy_gpt_regenerate_content_from_post($post_id) {
    $options = get_option('easy_gpt_options');
	$model = $options['easy_gpt_model'] ?? 'gpt-4o';
	
	error_log("Regenerating... 1");
	// Elegir API key en función del modelo
	if (strpos($model, 'gpt-') === 0 || strpos($model, 'text-') === 0) {
		$api_key = $options['easy_gpt_api_key'] ?? '';
	} elseif (strpos($model, 'gemini-') === 0) {
		$api_key = $options['easy_gpt_google_api_key'] ?? '';
	} elseif (strpos($model, 'deepseek-') === 0) {
		$api_key = $options['easy_gpt_deepseek_api_key'] ?? '';
	} else {
		$api_key = $options['easy_gpt_api_key'] ?? '';
	}
	
	error_log("Regenerating... 2");
	
    $temperature = floatval($options['easy_gpt_temperature'] ?? 0.7);
    $language = $options['easy_gpt_default_language'] ?? 'en';
    $style = $options['easy_gpt_writing_style'] ?? 'Informative';
    $tone = $options['easy_gpt_writing_tone'] ?? 'Neutral';

	$is_deepseek = strpos($model, 'deepseek-') === 0;
	
	$preserve_video_instruction = $is_deepseek ? "If there is a YouTube video link (e.g., a <p> with a https://www.youtube.com URL), do NOT remove or alter it. Keep it in its original form and position." : "";

	
    $post = get_post($post_id);
    if (!$post) return false;

    $original_title = $post->post_title;
    $original_content = $post->post_content;

    $include_links = get_post_meta($post->ID, '_easy_gpt_include_links', true);
    if ($include_links === '') {
        $include_links = isset($options['easy_gpt_include_links']) ? $options['easy_gpt_include_links'] : '0';
    }

    $links_instruction = '';
    if ($include_links === '1') {
        $links_instruction = " You can insert links using <a> </a> tags to justify data or claims, recommendations in the middle of the text. For example, 'according to a study made by <a>...'</a>. If possible, use the name for the link, but do not say 'for more information'";
    }

    // Dividir el contenido por secciones (por <h2>)
    $sections = preg_split('/(?=<h2[^>]*>)/i', $original_content, -1, PREG_SPLIT_NO_EMPTY);

    $revised_sections = [];

    foreach ($sections as $i => $section) {
        error_log("Regenerating... 3");
        $prompt = "You are helping improve an article section-by-section. Below is one section of the article titled \"{$original_title}\".

Instructions:
- Fix grammar, redundancy, and unclear expressions.
- Improve flow and engagement.
- Add complementary information, details, or examples if useful.
- Expand the section to add value, don't skip or simplify.
- Keep HTML structure and tags: <p>, <h2>, <ul>, <li>, <b>, <i>.
- Do NOT repeat the title or add <h1> or <html> tags.
- Return only the improved HTML for this section (no backticks or markdown). Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes. {$preserve_video_instruction}

Language: {$language}
Style: {$style}
Tone: {$tone}
{$links_instruction}

Section content:
\"\"\"{$section}\"\"\"";

        $response = easy_gpt_call_openai_api_no_session($prompt, $model, $temperature, $api_key);
        $cleaned = trim($response['text'] ?? '');
        $cleaned = preg_replace('/^```(?:html)?\s*|\s*```$/', '', $cleaned);
        $revised_sections[] = !empty($cleaned) ? $cleaned : $section;
    }

    // Unir todas las secciones
    $revised_full = implode("\n\n", $revised_sections);

    // Añadir introducción si empieza con <h2>
    if (preg_match('/^\s*<h2[^>]*>/', $revised_full)) {
        $intro_prompt = "This article titled \"{$original_title}\" is missing an introductory paragraph.

Instructions:
- Write a short and engaging introduction (<p>...</p>) based on the topic.
- Do NOT mention that this is an introduction.
- Do NOT include a <h1> or repeat the title.
- Return only one paragraph with <p> tags.

Language: {$language}
Style: {$style}
Tone: {$tone}";

        $intro_response = easy_gpt_call_openai_api_no_session($intro_prompt, $model, $temperature, $api_key);
        $intro_cleaned = preg_replace('/^```(?:html)?\s*|\s*```$/', '', trim($intro_response['text'] ?? ''));
        if (!empty($intro_cleaned)) {
            $revised_full = $intro_cleaned . "\n\n" . $revised_full;
        }
    }
    
    error_log("Regenerating... 4");

    // Revisión final de estructura completa
    $final_prompt = "We now have an updated version of the article titled \"{$original_title}\".

Please revise the overall structure, clarity, flow and logic of the full article.

Instructions:
- Merge or rearrange sections if needed for coherence.
- Add at least one new <h2> section if relevant
- Keep all meaningful content, do NOT shorten.
- Fix transitions and improve overall readability.
- Do NOT start the article with a <h2>, begin with one or more <p> paragraphs.
- Return only the final HTML. No markdown, triple backticks or <html> tags Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes..

Language: {$language}
Style: {$style}
Tone: {$tone}

Updated article content:
\"\"\"{$revised_full}\"\"\"";
	
	$is_deepseek = strpos($model, 'deepseek-') === 0;

	if (!$is_deepseek) {

		$final_response = easy_gpt_call_openai_api_no_session($final_prompt, $model, $temperature, $api_key);
		$final_cleaned = preg_replace('/^```(?:html)?\s*|\s*```$/', '', trim($final_response['text'] ?? ''));
	}
	else{
		$final_cleaned = preg_replace('/^```(?:html)?\s*|\s*```$/', '', trim($revised_full ?? ''));
	}
    
    error_log("Regenerating... 5");

    return [
        'content' => !empty($final_cleaned) ? $final_cleaned : $revised_full,
        'outline' => null,
    ];
}


function easy_gpt_preserve_existing_images_in_position($original_content, $new_content) {
    $images_with_position = [];

    // 1. Dividir el contenido original en bloques visibles (párrafos y títulos)
    $original_blocks = preg_split('/(<h[1-6][^>]*>.*?<\/h[1-6]>|<p[^>]*>.*?<\/p>)/i', $original_content, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

    $visible_block_count = 0;

    foreach ($original_blocks as $block) {
        if (preg_match('/<figure[^>]*>.*?<img[^>]+>.*?<\/figure>/is', $block, $match)) {
            $images_with_position[] = ['html' => $match[0], 'after_block' => $visible_block_count];
        } elseif (preg_match('/<img[^>]+>/i', $block, $match)) {
            $images_with_position[] = ['html' => $match[0], 'after_block' => $visible_block_count];
        } else {
            $visible_block_count++;
        }
    }

    if (empty($images_with_position)) return $new_content;

    // 2. Dividir el nuevo contenido también en bloques visibles
    $new_blocks = preg_split('/(<h[1-6][^>]*>.*?<\/h[1-6]>|<p[^>]*>.*?<\/p>)/i', $new_content, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

    $result_blocks = [];
    $current_visible = 0;
    $image_index = 0;

    foreach ($new_blocks as $block) {
        $result_blocks[] = $block;

        // Si es visible, comprobamos si toca insertar una imagen
        if (preg_match('/^<(p|h[1-6])\b[^>]*>/', $block)) {
            while (
                isset($images_with_position[$image_index]) &&
                $images_with_position[$image_index]['after_block'] === $current_visible
            ) {
                $result_blocks[] = $images_with_position[$image_index]['html'];
                $image_index++;
            }
            $current_visible++;
        }
    }

    // Si quedan imágenes por insertar (por si el nuevo contenido tiene menos bloques)
    while (isset($images_with_position[$image_index])) {
        $result_blocks[] = $images_with_position[$image_index]['html'];
        $image_index++;
    }

    return implode("\n", $result_blocks);
}


function easy_gpt_refresh_images($post_id, $params, $log, $model) {
    if (empty($params['easy_gpt_refresh_update_images'])) return $log;

    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/media.php';
    require_once ABSPATH . 'wp-admin/includes/image.php';

    $replace_existing = $params['easy_gpt_refresh_image_replace_existing'] ?? 'keep';
    $add_new = intval($params['easy_gpt_refresh_image_add_new'] ?? 0);
    $featured_behavior = $params['easy_gpt_refresh_image_featured_behavior'] ?? 'set_if_none';

    if ($replace_existing === 'replace') {
        easy_gpt_remove_images_from_content($post_id);
        $log['replaced_existing_images'] = true;
    }

    $generated_images = [];
    for ($i = 0; $i < $add_new; $i++) {
        $image_data = easy_gpt_generate_image_data_for_refresh($post_id, $i + 1, $add_new);
        if ($image_data) {
            $generated_images[] = $image_data;
        }
    }

    if (empty($generated_images)) return $log;

    $image_ids = [];
    $image_urls = [];

    foreach ($generated_images as $image_data) {
        $image_url = esc_url_raw($image_data['image_url']);
        $image_title = sanitize_text_field($image_data['title']);
        $image_alt = sanitize_text_field($image_data['alt']);
        $filename = sanitize_title($image_title) . '.jpg';

        $tmp = download_url($image_url);
        if (is_wp_error($tmp)) continue;

        $file_array = [
            'name' => $filename,
            'tmp_name' => $tmp,
        ];

        $image_id = media_handle_sideload($file_array, $post_id, $image_title);
        if (is_wp_error($image_id)) {
            @unlink($file_array['tmp_name']);
            continue;
        }

        wp_update_post([
            'ID' => $image_id,
            'post_title' => $image_title,
            'post_name' => sanitize_title($image_title),
        ]);

        update_post_meta($image_id, '_wp_attachment_image_alt', $image_alt);

        $image_ids[] = $image_id;
        $image_urls[] = [
            'url' => wp_get_attachment_url($image_id),
            'title' => $image_title,
            'alt' => $image_alt
        ];
    }

    // Featured image logic
    if ($featured_behavior === 'always_replace' || ($featured_behavior === 'set_if_none' && !has_post_thumbnail($post_id))) {
        set_post_thumbnail($post_id, $image_ids[0]);
        $log['replaced_featured'] = true;
        array_shift($image_urls); // remove first for content insertion
    }

    if (!empty($image_urls)) {
        $title = get_the_title($post_id);
        $language = $params['easy_gpt_default_language'] ?? 'en';
        $style = $params['easy_gpt_writing_style'] ?? '';
        $tone = $params['easy_gpt_writing_tone'] ?? '';
        $content = get_post_field('post_content', $post_id);
		error_log("insertando imagenes con ia...");
		
			
		$is_deepseek = strpos($model, 'deepseek-') === 0;

		if (!$is_deepseek){
			$new_content = easy_gpt_insert_images_with_ai($content, $image_urls, $title, $language, $style, $tone);
		}
		else{
			$new_content = easy_gpt_insert_new_images_every_x_paragraphs($content, $image_urls, 3);
		}
		
		error_log("[EasyGPT] 🧾 Content after inserting images with DeepSeek:\n" . $new_content);

		
		// Restaurar video de YouTube si se perdió
		if (preg_match('/<p>\s*(https?:\/\/(www\.)?youtube\.com\/watch\?v=[\w-]+|https?:\/\/youtu\.be\/[\w-]+)\s*<\/p>/', $content, $match)) {
			$video_block = $match[0];
			error_log("[EasyGPT] 🎯 Video block detected: $video_block");
			if (strpos($new_content, $video_block) === false) {
				error_log("[EasyGPT] ⚠️ Re-inserting missing YouTube block...");
				$new_content .= "\n\n" . $video_block;
			} else {
				error_log("[EasyGPT] ✅ YouTube block still present, no reinsertion needed.");
			}
		} else {
			error_log("[EasyGPT] ❌ No YouTube block found in original content before image insertion.");
		}	
        
		error_log("insertadas imagenes con ia...");
        wp_update_post(['ID' => $post_id, 'post_content' => $new_content]);
    }

    $log['new_images_added'] = count($image_urls) + ($log['replaced_featured'] ?? 0);

    return $log;
}

function easy_gpt_generate_image_data_for_refresh($post_id, $image_index, $total_images) {
    $title = get_the_title($post_id);
    $content = wp_strip_all_tags(get_post_field('post_content', $post_id));
    $options = get_option('easy_gpt_options');

    $language = $options['easy_gpt_default_language'] ?? 'en';
    $style = $options['easy_gpt_writing_style'] ?? 'Informative';
    $tone = $options['easy_gpt_writing_tone'] ?? 'Neutral';
    $model = $options['easy_gpt_image_model'] ?? 'dall-e-3';
    $text_model = $options['easy_gpt_model'] ?? 'gpt-4o';
    $temperature = floatval($options['easy_gpt_temperature'] ?? 0.7);
    $image_size = $options['easy_gpt_image_size'] ?? '1024x1024';
    $image_quality = $options['easy_gpt_image_quality'] ?? 'standard';
    $image_style = $options['easy_gpt_image_style'] ?? '';
    $api_key = $options['easy_gpt_api_key'] ?? '';

    // 🖼️ Prompt para el título de la imagen
    $title_prompt = "Based on the following article content, generate a unique and descriptive image title that reflects a specific visual aspect or theme of the article. " .
                    "Avoid repeating the article title. Be creative and specific. Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.\n\n" .
                    "Article Title: {$title}\n\n" .
                    "Article Content: {$content}\n\n" .
					"Return the title in {$language}\n" .
                    "Writing Style: {$style}\n" .
                    "Writing Tone: {$tone}";
    $title_resp = easy_gpt_call_openai_api_no_session($title_prompt, $text_model, $temperature, $api_key);
    $image_title = trim($title_resp['text'] ?? $title);
	$image_title = trim($title_resp['text'] ?? $title, "\"' ");

    // 🔤 Prompt para el alt
    $alt_prompt = "Based on the image title and article content below, generate a short alt text that accurately describes the image. " .
                  "Do not mention 'image' or 'photo'. Just return the alt text. Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.\n\n" .
                  "Image Title: {$image_title}\n\n" .
					"Return the alt in {$language}\n" .
                  "Writing Style: {$style}\n" .
                  "Writing Tone: {$tone}";
    $alt_resp = easy_gpt_call_openai_api_no_session($alt_prompt, $text_model, $temperature, $api_key);
    $alt = trim($alt_resp['text'] ?? $image_title);
	$alt = trim($alt_resp['text'] ?? $title, "\"' ");

	
    // 🧠 Prompt para la imagen final
    $image_prompt = "Generate an image titled '{$image_title}' with the following details." .
                    "Description: '{$alt}'. Focus on the main theme or concept presented.\n\n" .
                    "Style: {$image_style}. Quality: {$image_quality}. Size: {$image_size}. ";
    $image_response = easy_gpt_call_openai_image_api_no_session($image_prompt, $model, $image_size, $image_quality, $api_key);

    if (empty($image_response['image_url'])) return false;

// Registrar resultado de generación de imagen
error_log("[EasyGPT - Image Generation] ✅ Resultado para post ID {$post_id} (Imagen {$image_index}/{$total_images}):");
error_log("  • Título de imagen: {$image_title}");
error_log("  • Texto ALT: {$alt}");
error_log("  • URL imagen: " . ($image_response['image_url'] ?? '❌ No se generó'));
	
	
    return [
        'image_url' => esc_url_raw($image_response['image_url']),
        'title'     => sanitize_text_field($image_title),
        'alt'       => sanitize_text_field($alt)
    ];
}

function easy_gpt_insert_images_with_ai($content, $images_data, $title, $language, $style = '', $tone = '') {
    $api_key = get_option('easy_gpt_options')['easy_gpt_api_key'];
    $model = get_option('easy_gpt_options')['easy_gpt_model'] ?? 'gpt-4o';
    $temperature = floatval(get_option('easy_gpt_options')['easy_gpt_temperature'] ?? 0.7);

    $image_descriptions = [];
    foreach ($images_data as $img) {
        $image_descriptions[] = "- Title: {$img['title']}, Alt: {$img['alt']}, URL: {$img['url']}";
    }
    $image_list = implode("\n", $image_descriptions);
	
	error_log("Contenido antes de imagenes:");
	error_log($content);

    $prompt = "You are an assistant that enhances HTML articles by inserting images appropriately.

Here is the article content:
--------------------
{$content}
--------------------

Images to insert:
{$image_list}

Instructions:
- Insert the <img> tags inside the article in appropriate and natural positions.
- Avoid placing new images immediately before or after existing images. Left at least 3 paragraph between and if is posible do place in the same H2.
- Prioritize sections without images to maintain a balanced visual layout.
- Use the given title and alt attributes.
- Do NOT insert all images together or at the very end.
- Do NOT modify the existing content.
- Return only the updated HTML content. Do not return <html> tags.
- Do NOT use triple backticks (``` or ```html). Just return the pure HTML content. Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.

Language: {$language}
Writing Style: {$style}
Tone: {$tone}";

	$response = easy_gpt_call_openai_api_no_session($prompt, $model, $temperature, $api_key);

	// 🧼 Limpieza automática de triple backticks
	$cleaned = preg_replace('/^```(?:html)?\s*|\s*```$/', '', trim($response['text'] ?? ''));

	return !empty($cleaned) ? $cleaned : $content;
}

function easy_gpt_remove_images_from_content($post_id) {
    $content = get_post_field('post_content', $post_id);
    $content = preg_replace('/<img[^>]+\>/i', '', $content);
    wp_update_post(['ID' => $post_id, 'post_content' => $content]);
}

function easy_gpt_refresh_youtube($post_id, $options) {
	if (empty($options['easy_gpt_refresh_youtube_enabled'])) {
		error_log("[EasyGPT] 🔇 YouTube refresh disabled.");
		return false;
	}

	$behavior = $options['easy_gpt_refresh_youtube_behavior'] ?? 'skip_if_exists';
	$current_content = get_post_field('post_content', $post_id);

	// Ver si ya hay una URL de YouTube en el contenido
	preg_match_all('/https?:\/\/(www\.)?youtube\.com\/watch\?v=[\w-]+|https?:\/\/youtu\.be\/[\w-]+/', $current_content, $matches);
	$existing_youtube_urls = $matches[0] ?? [];

	if (!empty($existing_youtube_urls)) {
		error_log("[EasyGPT] 🎬 Existing YouTube URL(s) found: " . implode(', ', $existing_youtube_urls));
		if ($behavior === 'skip_if_exists') {
			error_log("[EasyGPT] 🚫 Skipping YouTube insertion (behavior: skip_if_exists).");
			return false;
		}
		if ($behavior === 'replace_existing') {
			foreach ($existing_youtube_urls as $url) {
				$current_content = str_replace($url, '', $current_content);
			}
			error_log("[EasyGPT] ♻️ Removed existing YouTube URLs (behavior: replace_existing).");
		}
	}

	// Obtener datos del artículo
	$title = get_the_title($post_id);
	$keywords = get_post_meta($post_id, '_easy_gpt_keywords', true);

	if (empty($keywords)) {
		$api_key = $options['easy_gpt_api_key'] ?? '';
		$model = $options['easy_gpt_model'] ?? 'gpt-4o';
		$temperature = floatval($options['easy_gpt_temperature'] ?? 0.7);
		$content = get_post_field('post_content', $post_id);

		error_log("[EasyGPT] 🔍 Extracting keywords from content...");
		$keywords = easy_gpt_extract_keywords_from_content($title, $content, $api_key, $model, $temperature);
		error_log("[EasyGPT] 🧠 Keywords extracted: " . $keywords);
	}

	$language = get_post_meta($post_id, '_easy_gpt_language', true) ?: 'en';
	$position = $options['easy_gpt_video_position'] ?? 'end';
	$after_paragraph = max(1, intval($options['easy_gpt_video_paragraph'] ?? 3));

	error_log("[EasyGPT] 🔎 Searching for YouTube video (title: {$title}, lang: {$language})...");
	$response = easy_gpt_get_youtube_video_url($title, $keywords, $language, '1');

	if (!$response || empty($response['video_url'])) {
		error_log("[EasyGPT] ❌ No YouTube video found.");
		return false;
	}

	$new_video_url = esc_url($response['video_url']);
	error_log("[EasyGPT] ✅ YouTube video selected: {$new_video_url}");

	// Insertar video según la posición
	if ($position === 'start') {
		$paragraphs = preg_split('/(<p\b[^>]*>.*?<\/p>)/i', $current_content, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

		$insert_index = 3;
		foreach ($paragraphs as $i => $p) {
			if (stripos($p, '<h2') !== false) {
				$insert_index = min($insert_index, $i);
				break;
			}
		}

		error_log("[EasyGPT] ⬆️ Inserting video at the start (index: $insert_index)");
		array_splice($paragraphs, $insert_index, 0, "\n<p>{$new_video_url}</p>\n");
		$current_content = implode("", $paragraphs);
	}
	elseif ($position === 'after_paragraph') {
		$paragraphs = preg_split('/(<p\b[^>]*>.*?<\/p>)/i', $current_content, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

		$insert_index = $after_paragraph;
		error_log("[EasyGPT] 🔢 Inserting video after paragraph #{$after_paragraph}");

		if (isset($paragraphs[$insert_index])) {
			array_splice($paragraphs, $insert_index, 0, "\n<p>{$new_video_url}</p>\n");
		} else {
			$paragraphs[] = "\n<p>{$new_video_url}</p>\n";
		}

		$current_content = implode("", $paragraphs);
	}
	elseif ($position === 'random') {
		$paragraphs = preg_split('/(<p\b[^>]*>.*?<\/p>)/i', $current_content, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
		$insert_index = rand(1, count($paragraphs) - 1);
		error_log("[EasyGPT] 🎲 Inserting video at random position: $insert_index");
		array_splice($paragraphs, $insert_index, 0, "\n<p>{$new_video_url}</p>\n");
		$current_content = implode("", $paragraphs);
	}
	else { // end
		error_log("[EasyGPT] ⬇️ Appending video at the end.");
		$current_content .= "\n<p>{$new_video_url}</p>\n";
	}

	wp_update_post([
		'ID' => $post_id,
		'post_content' => wp_kses_post($current_content)
	]);

	error_log("[EasyGPT] ✅ Video inserted into post ID {$post_id}");
	return true;
}


function easy_gpt_refresh_seo($post_id, $options) {
	if (empty($options['easy_gpt_refresh_update_seo'])) return false;

	$title         = get_the_title($post_id);
	$content       = get_post_field('post_content', $post_id);
	$prompt_text   = get_post_meta($post_id, '_easy_gpt_prompt', true) ?: $title;
	$keywords      = get_post_meta($post_id, '_easy_gpt_keywords', true) ?: '';
	$language      = get_post_meta($post_id, '_easy_gpt_language', true) ?: 'en';
	$writing_style = $options['easy_gpt_writing_style'] ?? 'Standard';
	$writing_tone  = $options['easy_gpt_writing_tone'] ?? 'Informative';
	$model         = $options['easy_gpt_model'] ?? 'gpt-4o';
	$temperature   = floatval($options['easy_gpt_temperature'] ?? 0.7);
	$api_key       = $options['easy_gpt_api_key'];

	// Prompt para el metatitle
	$seo_title_prompt = "You are an expert in SEO writing.

Based on the following article, generate a compelling and SEO-optimized metatitle:
- It must not exceed 60 characters.
- It must be unique and relevant.
- It must be written in the same language as the article.
- Do NOT include quotes or any formatting, just the plain title. Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.

Article Title: {$title}
Prompt: {$prompt_text}
Keywords: {$keywords}

--- Article content ---
{$content}
----------------------";

	// Prompt para la metadescription
	$seo_description_prompt = "You are an expert in SEO writing.

Based on the following article, write a persuasive SEO-friendly metadescription:
- It must not exceed 155 characters.
- It should attract clicks.
- It must be written in the same language as the article.
- Do NOT include quotes or any formatting, just the plain description. Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.

Article Title: {$title}
Prompt: {$prompt_text}
Keywords: {$keywords}

--- Article content ---
{$content}
----------------------";

	// Llamadas a la API
	$seo_title = easy_gpt_call_openai_api_no_session($seo_title_prompt, $model, $temperature, $api_key)['text'] ?? '';
	$seo_description = easy_gpt_call_openai_api_no_session($seo_description_prompt, $model, $temperature, $api_key)['text'] ?? '';

	// Limpieza final
	$seo_title = trim($seo_title, "\"' ");
	$seo_description = trim($seo_description, "\"' ");

	// Guardar en los campos SEO (Yoast)
	if (!empty($seo_title)) {
		update_post_meta($post_id, '_yoast_wpseo_title', sanitize_text_field($seo_title));
	}
	if (!empty($seo_description)) {
		update_post_meta($post_id, '_yoast_wpseo_metadesc', sanitize_textarea_field($seo_description));
	}

	return true;
}

function easy_gpt_extract_keywords_from_content($title, $content, $api_key, $model = 'gpt-4o', $temperature = 0.5) {
    $prompt = "Extract 3 relevant keywords (single words or short phrases) of an article title {$title}. Return them as a comma-separated list.Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes. \n\n{$content}";

    $response = easy_gpt_call_openai_api_no_session($prompt, $model, $temperature, $api_key);
    $keywords = $response['text'] ?? '';

    // Limpiar: eliminar espacios innecesarios y asegurar formato CSV
    return trim(preg_replace('/\s*,\s*/', ', ', strip_tags($keywords)));
}

function easy_gpt_insert_existing_images_with_ai($original_content, $new_content, $language, $style = '', $tone = '') {
    $api_key = get_option('easy_gpt_options')['easy_gpt_api_key'];
    $model = get_option('easy_gpt_options')['easy_gpt_model'] ?? 'gpt-4o';
    $temperature = floatval(get_option('easy_gpt_options')['easy_gpt_temperature'] ?? 0.7);

    $prompt = "You are an assistant that enhances HTML articles by reinserting the original image blocks from the source content.

Here is the original article content (with images):
--------------------
{$original_content}
--------------------

Here is the new rewritten version of the article (without images):
--------------------
{$new_content}
--------------------

Instructions:
- Extract all original <figure> blocks (including <figcaption>) or <img> tags from the original content.
- Reinsert them into the new content in positions that match their approximate original location.
- Maintain the exact HTML for each <figure> block: do NOT edit, simplify, or recreate the image or its caption.
- Avoid placing multiple images together or placing any directly before or after a <h2> or another image.
- Keep a visually balanced layout, spreading images naturally through the content.
- Return only the updated HTML. Do NOT include <html> or <body> tags.
- Do NOT use markdown or triple backticks. Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.

Language: {$language}
Style: {$style}
Tone: {$tone}";


    $response = easy_gpt_call_openai_api_no_session($prompt, $model, $temperature, $api_key);

    // Limpiar backticks si los hubiera
    $cleaned = preg_replace('/^```(?:html)?\s*|\s*```$/', '', trim($response['text'] ?? ''));

    return !empty($cleaned) ? $cleaned : $new_content;
}

function easy_gpt_insert_images_every_x_paragraphs($original_content, $new_content, $interval = 3) {
    // Extraer <figure> o <img>
    preg_match_all('/<figure.*?<\/figure>|<img[^>]+>/i', $original_content, $matches);
    $images = $matches[0] ?? [];

    if (empty($images)) return $new_content;

    // Dividir en párrafos
    $paragraphs = preg_split('/(<\/p>)/i', $new_content, -1, PREG_SPLIT_DELIM_CAPTURE);
    if (count($paragraphs) < 3) return $new_content;

    $result = '';
    $image_index = 0;
    $paragraph_count = 0;

    for ($i = 0; $i < count($paragraphs); $i += 2) {
        $result .= $paragraphs[$i] ?? '';
        $result .= $paragraphs[$i + 1] ?? '';
        $paragraph_count++;

        if ($paragraph_count % $interval === 0 && isset($images[$image_index])) {
            $result .= "\n\n" . $images[$image_index];
            $image_index++;
        }

        if ($image_index >= count($images)) break;
    }

    // Agregar el resto
    for ($j = $i + 2; $j < count($paragraphs); $j++) {
        $result .= $paragraphs[$j];
    }

    return $result;
}

function easy_gpt_insert_new_images_every_x_paragraphs($content, $image_urls, $interval = 3) {
    if (empty($image_urls)) return $content;

    // Dividir en párrafos
    $paragraphs = preg_split('/(<\/p>)/i', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
    if (count($paragraphs) < 3) return $content;

    // Buscar el índice del último <img> o <figure>
    $last_image_index = -1;
    $joined_content = implode('', $paragraphs);
    preg_match_all('/<img[^>]*>|<figure.*?<\/figure>/is', $joined_content, $matches, PREG_OFFSET_CAPTURE);

    if (!empty($matches[0])) {
        $last_img = end($matches[0]);
        $last_pos = $last_img[1];
        // Calcular a qué párrafo corresponde esa posición
        $current_pos = 0;
        for ($i = 0; $i < count($paragraphs); $i++) {
            $current_pos += strlen($paragraphs[$i]);
            if ($current_pos >= $last_pos) {
                $last_image_index = $i;
                break;
            }
        }
    }

    $result = '';
    $image_index = 0;
    $paragraph_count = 0;
    $started = false;

    for ($i = 0; $i < count($paragraphs); $i += 2) {
        $result .= $paragraphs[$i] ?? '';
        $result .= $paragraphs[$i + 1] ?? '';
        if ($i > $last_image_index) {
            $paragraph_count++;
            $started = true;

            if ($paragraph_count % $interval === 0 && isset($image_urls[$image_index])) {
                $img = $image_urls[$image_index];
                $html = "<figure><img src=\"" . esc_url($img['url']) . "\" alt=\"" . esc_attr($img['alt']) . "\" style=\"max-width:100%;height:auto;\" />";
                if (!empty($img['title'])) {
                    $html .= "<figcaption>" . esc_html($img['title']) . "</figcaption>";
                }
                $html .= "</figure>\n\n";
                $result .= $html;
                $image_index++;
            }

            if ($image_index >= count($image_urls)) break;
        }
    }

    // Agregar cualquier resto
    for ($j = $i + 2; $j < count($paragraphs); $j++) {
        $result .= $paragraphs[$j];
    }

    return $result;
}


