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

add_action('easy_gpt_run_article_translation', 'easy_gpt_run_article_translation');

function easy_gpt_run_article_translation() {
    error_log("[EasyGPT] 🌍 Starting article translation cron...");

    global $wpdb, $easy_gpt_total_cost;
    $easy_gpt_total_cost = 0;

    $options = get_option('easy_gpt_options');
    if (empty($options['easy_gpt_enable_translation'])) {
        error_log("[EasyGPT] ❌ Translation is disabled in settings.");
        return;
    }

    $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] ❌ Translation blocked: license invalid or expired.");
        return;
    }

    if (!function_exists('pll_languages_list') || !function_exists('pll_get_post')) {
        error_log("[EasyGPT] ❌ Polylang not available.");
        return;
    }

    $default_lang = pll_default_language();
    $target_langs = $options['easy_gpt_translation_languages'] ?? [];
    if (empty($target_langs)) {
        error_log("[EasyGPT] ❌ No target languages selected.");
        return;
    }

    $priority = $options['easy_gpt_translation_priority'] ?? 'oldest_first';
    $order = ($priority === 'newest_first') ? 'DESC' : 'ASC';

    $enabled_types = [];
    /*if (!empty($options['easy_gpt_translate_posts'])) {
        $enabled_types[] = 'post';
    }*/
	$enabled_types = ['post'];
	
    if (!empty($options['easy_gpt_translate_products'])) {
        //$enabled_types[] = 'product';
    }

    if (empty($enabled_types)) {
        error_log("[EasyGPT] ❌ No content types selected for translation.");
        return;
    }

    $query_args = [
        'post_type'      => $enabled_types,
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'orderby'        => 'modified',
        'order'          => $order,
        'lang'           => $default_lang,
        'fields'         => 'ids',
    ];

    $posts = get_posts($query_args);

    foreach ($posts as $post_id) {
        foreach ($target_langs as $lang) {
            if (!pll_get_post($post_id, $lang)) {
                $post = get_post($post_id);
                return easy_gpt_translate_single_post($post, $lang, $default_lang, $options);
            }
        }
    }

    error_log("[EasyGPT] ✅ No untranslated articles found.");
}

function easy_gpt_clean_output_text($text) {
    $text = trim($text);

    // Quitar comillas solo si envuelven toda la frase
    $quote_pairs = [
        ['"', '"'],
        ["'", "'"],
        ['“', '”'],
        ['‘', '’'],
        ['«', '»']
    ];

    foreach ($quote_pairs as [$open, $close]) {
        if (str_starts_with($text, $open) && str_ends_with($text, $close)) {
            $text = substr($text, 1, -1);
            break;
        }
    }

    return trim($text);
}

function easy_gpt_translate_single_post($post, $target_lang, $original_lang, $options) {
    global $wpdb, $easy_gpt_total_cost;
	
	error_log("[EasyGPT] traduciendo...");
	
	$wpdb->insert($wpdb->prefix . 'easy_gpt_translations', [
		'original_post_id'   => $post->ID,
		'original_language'  => $original_lang,
		'target_language'    => $target_lang,
		'status'             => 'processing',
		'date_translated'    => current_time('mysql'),
	]);
	$translation_id = $wpdb->insert_id;
	
	try {

		$model       = $options['easy_gpt_model'] ?? 'gpt-4o';
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'] ?? ''; // fallback
}
		
		$temperature = floatval($options['easy_gpt_temperature'] ?? 0.7);

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

		$prompt_title = "Translate the following blog post title from {$original_lang} to {$target_lang}, preserving its meaning and tone:\n\n\"{$original_title}\". Only return the title without enclosing it in quotes. Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.";
		$title_result = easy_gpt_call_openai_api_no_session($prompt_title, $model, $temperature, $api_key);
		$translated_title = trim($title_result['text'] ?? $original_title, "\"' ");

		$sections = preg_split('/(?=<h2[^>]*>)/i', $original_content, -1, PREG_SPLIT_NO_EMPTY);
		$translated_sections = [];

		foreach ($sections as $section) {
			$prompt = "Translate the following HTML section from {$original_lang} to {$target_lang}, keeping all tags and structure intact. Return only the translated HTML section. Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.
:\n\n{$section}";
			$response = easy_gpt_call_openai_api_no_session($prompt, $model, $temperature, $api_key);
			$translated = preg_replace('/^```(?:html)?\s*|\s*```$/', '', trim($response['text'] ?? ''));
			$translated_sections[] = !empty($translated) ? $translated : $section;
		}

		$translated_content = implode("\n\n", $translated_sections);

		if (!empty($options['easy_gpt_translation_update_youtube'])) {
			$keywords = '';
			$language = $target_lang;

			// Usar título y contenido ya traducidos para extraer keywords en el nuevo idioma
			if (empty($keywords)) {
				$keywords = easy_gpt_extract_keywords_from_content($translated_title, $translated_content, $api_key, $model, $temperature);
			}

			$response = easy_gpt_get_youtube_video_url($title, $keywords, $language, '1');

			if (!empty($response['video_url'])) {
				$new_video_url = trim(strip_tags($response['video_url']));
				$new_video_url = esc_url($new_video_url);
				$youtube_pattern = '/https?:\/\/(www\.)?(youtube\.com\/watch\?v=|youtu\.be\/)[\w\-]+/i';

				// Log de depuración: mostrar contenido donde se busca
				if (preg_match($youtube_pattern, $translated_content, $matches)) {
					error_log("[EasyGPT] 🎥 YouTube match found: " . print_r($matches[0], true));
					$translated_content = preg_replace($youtube_pattern, $new_video_url, $translated_content);
					error_log("[EasyGPT] 🎥 YouTube video replaced with: {$new_video_url}");
				} else {
					error_log("[EasyGPT] ⚠️ No YouTube link found in content. Inserting at the end.");
					$translated_content .= "\n\n<p><a href=\"{$new_video_url}\" target=\"_blank\" rel=\"nofollow noopener\">{$new_video_url}</a></p>";
					error_log("[EasyGPT] 🎥 YouTube video inserted: {$new_video_url}");
				}
			}
		}

		$image_behavior = $options['easy_gpt_translation_image_behavior'] ?? 'keep';



		if ($image_behavior === 'update_metadata') {
			$translated_content = easy_gpt_duplicate_images_with_translated_meta($original_content, $translated_content, $original_lang, $target_lang, $api_key, $model, $temperature);
		} elseif ($image_behavior === 'regenerate') {
			$translated_content = easy_gpt_generate_new_images_for_translation($translated_content, $translated_title, $target_lang, $options);
		}

		$post_status = !empty($options['easy_gpt_translation_publish_status']) && $options['easy_gpt_translation_publish_status'] === 'publish' ? 'publish' : 'draft';

		$translated_post_id = wp_insert_post([
			'post_title'   => wp_slash($translated_title),
			'post_content' => wp_slash(wp_kses_post($translated_content)),
			'post_status'  => $post_status,
			'post_type'    => $post->post_type,
			'post_author'  => $post->post_author,
		]);

		if ($image_behavior === 'keep' && has_post_thumbnail($post->ID)) {
			set_post_thumbnail($translated_post_id, get_post_thumbnail_id($post->ID));
		}

		if (function_exists('pll_set_post_language')) {
			pll_set_post_language($translated_post_id, $target_lang);
		}
		if (function_exists('pll_save_post_translations')) {
			$trid = pll_get_post_translations($post->ID);
			if (!is_array($trid)) {
				$trid = [$original_lang => $post->ID];
			}

			$trid[$target_lang] = $translated_post_id;
			pll_save_post_translations($trid);
		}

		// Imagen destacada (respeta image_behavior)
		if (has_post_thumbnail($post->ID)) {
			$original_thumb_id = get_post_thumbnail_id($post->ID);

			if ($image_behavior === 'update_metadata') {
				$original_url = wp_get_attachment_url($original_thumb_id);
				$original_title = get_the_title($original_thumb_id);
				$original_alt = get_post_meta($original_thumb_id, '_wp_attachment_image_alt', true) ?? '';

				$translated_title_img = easy_gpt_call_openai_api_no_session("Translate the following image title from {$original_lang} to {$target_lang}: {$original_title}, Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.", $model, $temperature, $api_key)['text'] ?? $original_title;
				$translated_alt_img   = easy_gpt_call_openai_api_no_session("Translate the following alt text from {$original_lang} to {$target_lang}: {$original_alt}. Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.", $model, $temperature, $api_key)['text'] ?? $original_alt;

				$file_path = get_attached_file($original_thumb_id);
				$upload_dir = wp_upload_dir();
				$new_filename = wp_unique_filename($upload_dir['path'], sanitize_title($translated_title_img) . '.jpg');
				copy($file_path, $upload_dir['path'] . '/' . $new_filename);

				$filetype = wp_check_filetype($new_filename);
				$attachment = [
					'guid'           => $upload_dir['url'] . '/' . $new_filename,
					'post_mime_type' => $filetype['type'],
					'post_title'     => sanitize_text_field(trim($translated_title_img, "\"' ")),
					'post_status'    => 'inherit'
				];
				$attach_id = wp_insert_attachment($attachment, $upload_dir['path'] . '/' . $new_filename, $translated_post_id);
				require_once ABSPATH . 'wp-admin/includes/image.php';
				wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $upload_dir['path'] . '/' . $new_filename));
				update_post_meta($attach_id, '_wp_attachment_image_alt', sanitize_text_field(trim($translated_alt_img, "\"' ")));

				set_post_thumbnail($translated_post_id, $attach_id);
			}
			elseif ($image_behavior === 'regenerate') {
				// Generar nueva imagen para imagen destacada
				$prompt_title = "Generate a descriptive image title for an article titled:\n\n{$translated_title}\n\nLanguage: {$target_lang}. Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.";
				$title_resp = easy_gpt_call_openai_api_no_session($prompt_title, $model, $temperature, $api_key);
				$image_title = trim($title_resp['text'] ?? $translated_title, "\"' ");

				$prompt_alt = "Generate a short and descriptive ALT text for an image titled \"{$image_title}\" in {$target_lang}. Do not mention 'image' or 'photo'. Only return the translated alt text, without explanations, comments, formatting, triple backticks, or alternatives.
";
				$alt_resp = easy_gpt_call_openai_api_no_session($prompt_alt, $model, $temperature, $api_key);
				$alt = trim($alt_resp['text'] ?? $image_title, "\"' ");

				$style       = $options['easy_gpt_image_style'] ?? '';
				$quality     = $options['easy_gpt_image_quality'] ?? 'standard';
				$size        = $options['easy_gpt_image_size'] ?? '1024x1024';
				$image_model = $options['easy_gpt_image_model'] ?? 'dall-e-3';

				$image_prompt = "Generate an image titled '{$image_title}' in the style of {$style} with the following description: {$alt}. Quality: {$quality}. Size: {$size}.";
				$img_resp = easy_gpt_call_openai_image_api_no_session($image_prompt, $image_model, $size, $quality, $api_key);

				if (!empty($img_resp['image_url'])) {
					if (!function_exists('download_url')) require_once ABSPATH . 'wp-admin/includes/file.php';
					if (!function_exists('media_handle_sideload')) require_once ABSPATH . 'wp-admin/includes/media.php';
					if (!function_exists('wp_generate_attachment_metadata')) require_once ABSPATH . 'wp-admin/includes/image.php';

					$tmp = download_url($img_resp['image_url']);
					if (!is_wp_error($tmp)) {
						$file_array = [
							'name'     => sanitize_file_name($image_title) . '.jpg',
							'tmp_name' => $tmp,
						];
						$image_id = media_handle_sideload($file_array, $translated_post_id, $image_title);

						if (!is_wp_error($image_id)) {
							wp_update_post([
								'ID'         => $image_id,
								'post_title' => sanitize_text_field($image_title),
								'post_name'  => sanitize_title($image_title),
							]);
							update_post_meta($image_id, '_wp_attachment_image_alt', $alt);
							set_post_thumbnail($translated_post_id, $image_id);
						}
					}
				}
			}
		}

		// SEO
		$seo_title = get_post_meta($post->ID, '_yoast_wpseo_title', true);
		$seo_description = get_post_meta($post->ID, '_yoast_wpseo_metadesc', true);

		if ($seo_title) {
			$prompt = "Translate this SEO title from {$original_lang} to {$target_lang}:\n\n{$seo_title}. Only return the SEO Title, Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.";
			$translated = easy_gpt_call_openai_api_no_session($prompt, $model, $temperature, $api_key)['text'] ?? $seo_title;
			update_post_meta($translated_post_id, '_yoast_wpseo_title', sanitize_text_field(trim($translated, "\"' ")));
		}

		if ($seo_description) {
			$prompt = "Translate this SEO description from {$original_lang} to {$target_lang}:\n\n{$seo_description}. Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.";
			$translated = easy_gpt_call_openai_api_no_session($prompt, $model, $temperature, $api_key)['text'] ?? $seo_description;
			update_post_meta($translated_post_id, '_yoast_wpseo_metadesc', sanitize_textarea_field(trim($translated, "\"' ")));
		}

		if ($post->post_type === 'post') {
			// Tags
			$tags = wp_get_post_tags($post->ID, ['fields' => 'names']);
			if (!empty($tags)) {
				$tag_list = implode(', ', $tags);
				$prompt = "Translate the following blog tags from {$original_lang} to {$target_lang}. Return only a comma-separated list, no explanations or formatting:\n\n{$tag_list}";
				$response = easy_gpt_call_openai_api_no_session($prompt, $model, $temperature, $api_key);
				$translated = trim($response['text'] ?? $tag_list, "\"' ");
				$translated_tags = array_map('trim', explode(',', $translated));
				wp_set_post_tags($translated_post_id, $translated_tags);
			}

			// Categories
			$categories = wp_get_post_categories($post->ID);
			$translated_categories = [];
			foreach ($categories as $cat_id) {
				$translated_term = pll_get_term($cat_id, $target_lang);
				if ($translated_term) {
					$translated_categories[] = $translated_term;
				}
			}
			if (!empty($translated_categories)) {
				wp_set_post_categories($translated_post_id, $translated_categories);
			}

		} elseif ($post->post_type === 'product') {
			// Product Tags
			$tags = wp_get_post_terms($post->ID, 'product_tag', ['fields' => 'names']);
			if (!empty($tags)) {
				$tag_list = implode(', ', $tags);
				$prompt = "Translate the following product tags from {$original_lang} to {$target_lang}. Return only a comma-separated list, no explanations or formatting:\n\n{$tag_list}";
				$response = easy_gpt_call_openai_api_no_session($prompt, $model, $temperature, $api_key);
				$translated = trim($response['text'] ?? $tag_list, "\"' ");
				$translated_tags = array_map('trim', explode(',', $translated));
				wp_set_post_terms($translated_post_id, $translated_tags, 'product_tag');
			}

			// Product Categories
			$categories = wp_get_post_terms($post->ID, 'product_cat', ['fields' => 'ids']);
			$translated_categories = [];
			foreach ($categories as $cat_id) {
				$translated_term = pll_get_term($cat_id, $target_lang);
				if ($translated_term) {
					$translated_categories[] = $translated_term;
				}
			}
			if (!empty($translated_categories)) {
				wp_set_post_terms($translated_post_id, $translated_categories, 'product_cat');
			}

			// Product Atributes
			$product = wc_get_product($post->ID);
			$translated_product = wc_get_product($translated_post_id);

			if ($product && $translated_product) {
				$attributes = $product->get_attributes();
				$translated_attributes = [];

				foreach ($attributes as $attribute) {
					if ($attribute->is_taxonomy()) {
						// Atributos basados en taxonomías (como color, talla)
						$taxonomy = $attribute->get_name();
						$terms = wp_get_post_terms($post->ID, $taxonomy, ['fields' => 'names']);

						if (!empty($terms)) {
							$term_list = implode(', ', $terms);
							$prompt = "Translate the following product attribute values from {$original_lang} to {$target_lang}. Return only a comma-separated list:\n\n{$term_list}";
							$response = easy_gpt_call_openai_api_no_session($prompt, $model, $temperature, $api_key);
							$translated = trim($response['text'] ?? $term_list, "\"' ");
							$translated_terms = array_map('trim', explode(',', $translated));

							// Asignar términos traducidos (requiere que existan en el idioma destino)
							$term_ids = [];
							foreach ($terms as $i => $original_term) {
								$term_obj = get_term_by('name', $original_term, $taxonomy);
								if ($term_obj) {
									$translated_term_id = pll_get_term($term_obj->term_id, $target_lang);
									if ($translated_term_id) {
										$term_ids[] = $translated_term_id;
									}
								}
							}

							if (!empty($term_ids)) {
								wp_set_post_terms($translated_post_id, $term_ids, $taxonomy);
							}
						}

					} else {
						// Atributos personalizados (no taxonómicos)
						$name = $attribute->get_name();
						$options = $attribute->get_options();

						// Traducir nombre del atributo
						$prompt_label = "Translate this product attribute name from {$original_lang} to {$target_lang}:\n\n{$name}";
						$label_response = easy_gpt_call_openai_api_no_session($prompt_label, $model, $temperature, $api_key);
						$translated_name = trim($label_response['text'] ?? $name, "\"' ");

						// Traducir valores
						$value_prompt = "Translate the following product attribute values from {$original_lang} to {$target_lang}. Return a comma-separated list:\n\n" . implode(', ', $options);
						$value_response = easy_gpt_call_openai_api_no_session($value_prompt, $model, $temperature, $api_key);
						$translated_values = array_map('trim', explode(',', trim($value_response['text'] ?? implode(', ', $options), "\"' ")));

						$translated_attributes[] = new WC_Product_Attribute([
							'name'         => $translated_name,
							'options'      => $translated_values,
							'position'     => $attribute->get_position(),
							'visible'      => $attribute->get_visible(),
							'variation'    => $attribute->get_variation(),
						]);
					}
				}

				if (!empty($translated_attributes)) {
					$translated_product->set_attributes($translated_attributes);
					$translated_product->save();
				}
			}

			// Galery

			$gallery_image_ids = $product->get_gallery_image_ids();
			$translated_gallery_ids = [];

			foreach ($gallery_image_ids as $image_id) {
				if ($image_behavior === 'keep') {
					$translated_gallery_ids[] = $image_id;
				}

				elseif ($image_behavior === 'update_metadata') {
					$title = get_the_title($image_id);
					$alt   = get_post_meta($image_id, '_wp_attachment_image_alt', true) ?? '';

					$translated_title = $title;
					$translated_alt = $alt;

					if ($title) {
						$translated_title = trim(easy_gpt_call_openai_api_no_session("Translate image title from {$original_lang} to {$target_lang}:\n\n{$title}", $model, $temperature, $api_key)['text'] ?? $title, "\"' ");
					}

					if ($alt) {
						$translated_alt = trim(easy_gpt_call_openai_api_no_session("Translate image alt from {$original_lang} to {$target_lang}:\n\n{$alt}", $model, $temperature, $api_key)['text'] ?? $alt, "\"' ");
					}

					$file_path = get_attached_file($image_id);
					$upload_dir = wp_upload_dir();
					$new_filename = wp_unique_filename($upload_dir['path'], sanitize_title($translated_title) . '.jpg');
					if (!copy($file_path, $upload_dir['path'] . '/' . $new_filename)) continue;

					$filetype = wp_check_filetype($new_filename);
					$attachment = [
						'guid'           => $upload_dir['url'] . '/' . $new_filename,
						'post_mime_type' => $filetype['type'],
						'post_title'     => sanitize_text_field($translated_title),
						'post_status'    => 'inherit',
					];

					$attachment_id = wp_insert_attachment($attachment, $upload_dir['path'] . '/' . $new_filename);
					require_once ABSPATH . 'wp-admin/includes/image.php';
					wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $upload_dir['path'] . '/' . $new_filename));
					update_post_meta($attachment_id, '_wp_attachment_image_alt', sanitize_text_field($translated_alt));

					$translated_gallery_ids[] = $attachment_id;
				}

				elseif ($image_behavior === 'regenerate') {
					$original_title = get_the_title($image_id);
					$prompt_title = "Generate a descriptive image title for a product titled:\n\n{$translated_title}\n\nLanguage: {$target_lang}. Do not add explanations, comments, preambles, markdown syntax, triple back";
					$title_resp = easy_gpt_call_openai_api_no_session($prompt_title, $model, $temperature, $api_key);
					$image_title = trim($title_resp['text'] ?? $translated_title, "\"' ");

					$prompt_alt = "Generate a short and descriptive ALT text for an image titled \"{$image_title}\" in {$target_lang}. Do not mention 'image' or 'photo'. Do not add explanations, comments, preambles, markdown syntax, triple back";
					$alt_resp = easy_gpt_call_openai_api_no_session($prompt_alt, $model, $temperature, $api_key);
					$alt = trim($alt_resp['text'] ?? $image_title, "\"' ");

					$style       = $options['easy_gpt_image_style'] ?? '';
					$quality     = $options['easy_gpt_image_quality'] ?? 'standard';
					$size        = $options['easy_gpt_image_size'] ?? '1024x1024';
					$image_model = $options['easy_gpt_image_model'] ?? 'dall-e-3';

					$image_prompt = "Generate an image titled '{$image_title}' in the style of {$style} with the following description: {$alt}. Quality: {$quality}. Size: {$size}.";
					$img_resp = easy_gpt_call_openai_image_api_no_session($image_prompt, $image_model, $size, $quality, $api_key);

					if (!empty($img_resp['image_url'])) {
						if (!function_exists('download_url')) require_once ABSPATH . 'wp-admin/includes/file.php';
						if (!function_exists('media_handle_sideload')) require_once ABSPATH . 'wp-admin/includes/media.php';
						if (!function_exists('wp_generate_attachment_metadata')) require_once ABSPATH . 'wp-admin/includes/image.php';

						$tmp = download_url($img_resp['image_url']);
						if (!is_wp_error($tmp)) {
							$file_array = [
								'name'     => sanitize_file_name($image_title) . '.jpg',
								'tmp_name' => $tmp,
							];
							$attachment_id = media_handle_sideload($file_array, $translated_post_id, $image_title);

							if (!is_wp_error($attachment_id)) {
								wp_update_post([
									'ID'         => $attachment_id,
									'post_title' => sanitize_text_field($image_title),
									'post_name'  => sanitize_title($image_title),
								]);
								update_post_meta($attachment_id, '_wp_attachment_image_alt', $alt);
								$translated_gallery_ids[] = $attachment_id;
							}
						}
					}
				}
			}

			if (!empty($translated_gallery_ids)) {
				update_post_meta($translated_post_id, '_product_image_gallery', implode(',', $translated_gallery_ids));
			}
		}


		$wpdb->update($wpdb->prefix . 'easy_gpt_translations', [
			'translated_post_id' => $translated_post_id,
			'translated_title'   => $translated_title,
			'cost_usd'           => floatval($easy_gpt_total_cost),
			'status'             => 'success',
			'date_translated'    => current_time('mysql'),
		], ['id' => $translation_id]);

		error_log("[EasyGPT] ✅ Article translated (Post ID: {$post->ID}) → {$target_lang} ✔");

	} catch (Throwable $e) {
		$wpdb->update($wpdb->prefix . 'easy_gpt_translations', [
			'status'             => 'error',
			'translated_title'   => '[ERROR] ' . substr($e->getMessage(), 0, 250),
			'date_translated'    => current_time('mysql'),
		], ['id' => $translation_id]);

		error_log("[EasyGPT] ❌ Error translating Post ID {$post->ID} to {$target_lang}: " . $e->getMessage());
	}
}


function easy_gpt_duplicate_images_with_translated_meta($original_content, $translated_content, $original_lang, $target_lang, $api_key, $model, $temperature) {
    preg_match_all('/<img[^>]+src="([^">]+)"/i', $original_content, $matches);
    if (empty($matches[1])) return $translated_content;

    foreach ($matches[1] as $original_url) {
        $attachment_id = attachment_url_to_postid($original_url);
        if (!$attachment_id) continue;

        $image_path = get_attached_file($attachment_id);
        if (!file_exists($image_path)) continue;

        $title = get_the_title($attachment_id);
        $alt   = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);

        // Traducciones
        $translated_title = $title;
        $translated_alt   = $alt;

        if ($title) {
            $prompt = "Translate the following image title from {$original_lang} to {$target_lang}:\n\n\"{$title}\" . Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.";
            $res = easy_gpt_call_openai_api_no_session($prompt, $model, $temperature, $api_key);
            $translated_title = trim($res['text'] ?? $title, "\"' ");
        }

        if ($alt) {
            $prompt = "Translate the following alt text from {$original_lang} to {$target_lang}:\n\n\"{$alt}\" . Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.";
            $res = easy_gpt_call_openai_api_no_session($prompt, $model, $temperature, $api_key);
            $translated_alt = trim($res['text'] ?? $alt, "\"' ");
        }

        // Copia física del archivo
        $upload_dir = wp_upload_dir();
        $new_filename = wp_unique_filename($upload_dir['path'], sanitize_title($translated_title) . '.jpg');
        $new_path = $upload_dir['path'] . '/' . $new_filename;
        if (!copy($image_path, $new_path)) continue;

        $filetype = wp_check_filetype($new_filename);
        $attachment = [
            'guid'           => $upload_dir['url'] . '/' . $new_filename,
            'post_mime_type' => $filetype['type'],
            'post_title'     => sanitize_text_field($translated_title),
            'post_status'    => 'inherit'
        ];

        $attachment_id = wp_insert_attachment($attachment, $new_path);
        require_once ABSPATH . 'wp-admin/includes/image.php';
        wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $new_path));
        update_post_meta($attachment_id, '_wp_attachment_image_alt', sanitize_text_field($translated_alt));

        $new_url = wp_get_attachment_url($attachment_id);
        if ($new_url) {
            $translated_content = str_replace($original_url, $new_url, $translated_content);
        }
    }

    return $translated_content;
}

function easy_gpt_generate_new_images_for_translation($content, $title, $language, $options) {
    $model         = $options['easy_gpt_model'] ?? 'gpt-4o';
    $image_model   = $options['easy_gpt_image_model'] ?? 'dall-e-3';
    $style         = $options['easy_gpt_image_style'] ?? '';
    $quality       = $options['easy_gpt_image_quality'] ?? 'standard';
    $size          = $options['easy_gpt_image_size'] ?? '1024x1024';
    $api_key       = $options['easy_gpt_api_key'];
    $temperature   = floatval($options['easy_gpt_temperature'] ?? 0.7);

    if (!function_exists('download_url')) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
    }
    if (!function_exists('media_handle_sideload')) {
        require_once ABSPATH . 'wp-admin/includes/media.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';
    }

    preg_match_all('/<img[^>]+src="([^">]+)"[^>]*>/i', $content, $matches);
    $original_img_tags = $matches[0] ?? [];
    $original_urls = $matches[1] ?? [];

    foreach ($original_urls as $index => $url) {
        $prompt_title = "Generate a descriptive image title for an article titled:\n\n{$title}\n\nLanguage: {$language} . Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.";
        $title_resp = easy_gpt_call_openai_api_no_session($prompt_title, $model, $temperature, $api_key);
        $image_title = trim($title_resp['text'] ?? $title, "\"' ");

        $prompt_alt = "Generate a short and descriptive ALT text for an image titled \"{$image_title}\" in {$language}. Do not mention 'image' or 'photo'. . Do not add explanations, comments, preambles, markdown syntax, triple backticks, or any extra notes.";
        $alt_resp = easy_gpt_call_openai_api_no_session($prompt_alt, $model, $temperature, $api_key);
        $alt = trim($alt_resp['text'] ?? $image_title, "\"' ");

        $image_prompt = "Generate an image titled '{$image_title}' in the style of {$style} with the following description: {$alt}. Quality: {$quality}. Size: {$size}.";
        $img_resp = easy_gpt_call_openai_image_api_no_session($image_prompt, $image_model, $size, $quality, $api_key);

        if (empty($img_resp['image_url'])) {
            error_log("[EasyGPT] ⚠️ Failed to generate image for translation.");
            continue;
        }

        $tmp = download_url($img_resp['image_url']);
        if (is_wp_error($tmp)) continue;

        $file_array = [
            'name'     => sanitize_file_name($image_title) . '-' . $index . '.jpg',
            'tmp_name' => $tmp,
        ];

        $attach_id = media_handle_sideload($file_array, 0);
        if (is_wp_error($attach_id)) {
            @unlink($file_array['tmp_name']);
            continue;
        }

        wp_update_post([
            'ID' => $attach_id,
            'post_title' => $image_title,
            'post_name'  => sanitize_title($image_title),
        ]);
        update_post_meta($attach_id, '_wp_attachment_image_alt', $alt);

        $new_url = wp_get_attachment_url($attach_id);
        if (!$new_url) continue;

        $new_img_tag = '<img src="' . esc_url($new_url) . '" alt="' . esc_attr($alt) . '" style="max-width:100%;height:auto" />';
        $content = str_replace($original_img_tags[$index], $new_img_tag, $content);
    }

    return $content;
}