<?php if ( current_user_can('manage_options') ) : ?>

<style>
	#exportBtn {
	color: #f1556c;
    border-color: #f1556c;
    background: #fdeef0;
    vertical-align: top;	
	display: inline-block;
    text-decoration: none;
    font-size: 13px;
    line-height: 2.15384615;
    min-height: 30px;
    margin: 0;
    padding: 0 10px;
    cursor: pointer;
    border-width: 1px;
    border-style: solid;
    -webkit-appearance: none;
    border-radius: 3px;
    white-space: nowrap;
    box-sizing: border-box;
	}
	
	#exportBtn:hover {
		background:#f7e7ff;
		border-color:#f1556c;
	}
	
	#exportBtn:active {
		border-color:#d174ff
	}
	
	span.aicc-status.green {
		color:#00a320 !important;
		font-weight:bold;
	}
	
	span.aicc-status.red {
		color:#e65054 !important;
		font-weight:bold;
	}
	
	#token_cost {
		margin-left: 6px;
		font-style:italic;
	}	
	
	#unlock_type {
	    margin-right: 6px;
	}
	#aicc_unlock_process{
	    color: #f1556c;
	    border-color: #f1556c;
	    background: #fdeef0;
	    vertical-align: top;
	    display: inline-block;
	    text-decoration: none;
	    font-size: 13px;
	    line-height: 2.15384615;
	    min-height: 30px;
	    margin: 0;
	    padding: 0 10px;
	    cursor: pointer;
	    border-width: 1px;
	    border-style: solid;
	    -webkit-appearance: none;
	    border-radius: 3px;
	    white-space: nowrap;
	    box-sizing: border-box;
	}
</style>
<?php

$nonce = wp_create_nonce('export_data_nonce'); 

$is_running = get_transient('aicc_is_running');

$process_lock = get_transient('aicc_manual_process_lock');

if ( $is_running || $process_lock )
{
	$status = 'processing';
}
else
{
	$status = '';
}


?>
<script>

	jQuery(document).ready(function($) {
	    $('#aicc_unlock_process').click(function(e) {
	        e.preventDefault();

	        var _this = $(this);  // Guarda la referencia al botón que se clickeó
	        var spinner = _this.next('.spinner');
	        spinner.css({
	            'float': 'none',
	            'margin-top': '5px',
	            'margin-left': '10px'
	        });
	        spinner.show();

	        var type = $('#unlock_type').val();
	        var textp;

	        if (type == 'manual_curation') {
	            textp = 'Curación manual de contenidos';
	        } else if (type == 'masive_curation') {
	            textp = 'Curación masiva de contenidos';
	        }

	        // SweetAlert para confirmar la cancelación
	        Swal.fire({
	            html: 'Confirma que deseas desbloquear el siguiente proceso:<br><strong>' + textp + '</strong>',
	            icon: 'warning',
	            showCancelButton: true,
	            confirmButtonText: 'Sí, desbloquear',
	            cancelButtonText: 'No, cancelar'
	        }).then((result) => {
	            if (result.value) {
	                $.ajax({
	                    url: ajaxurl,
	                    type: 'POST',
	                    data: {
	                        action: 'aicc_unlock_process',
	                        type: type
	                    },
	                    success: function(response) {
	                        Swal.fire({
	                            icon: 'success',
	                            html: 'El proceso se desbloqueó correctamente.<br><br>Te recomendamos esperar unos segundos antes de ejecutar un nuevo proceso para que se limpien correctamente todos los datos temporales.',
	                            confirmButtonText: 'Aceptar'
	                        }).then((result) => {
	                            if (result.isConfirmed) {
	                                spinner.hide();
	                                location.reload();
	                            }
	                        });
	                    },
	                    error: function() {
	                        // Manejar el error adecuadamente
	                        spinner.hide();
	                        Swal.fire({
	                            icon: 'error',
	                            text: 'Hubo un error al desbloquear el proceso',
	                            confirmButtonText: 'Aceptar'
	                        });
	                    }
	                });
	            } else {
	                spinner.hide();
	            }
	        });
	    });
	});


	jQuery(document).ready(function($) {
        $('#exportBtn').on('click', function(e) {
			e.preventDefault();
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'export_data',
					security: $('#exportBtn').data('nonce')
                },
                success: function(data) {
                    const blob = new Blob([data], { type: 'text/plain' });
                    const url = URL.createObjectURL(blob);
    
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'data.txt';
                    a.click();
    
                    URL.revokeObjectURL(url);
                },
                error: function() {
                    alert('Hubo un error al obtener los datos.');
                }
            });
        });
    });
	
function aiccCopyToClipboard(event) {
    event.stopPropagation();
    event.preventDefault();
    const el = document.getElementById('aiccCopyContent');
    const range = document.createRange();
    const selection = window.getSelection();

    selection.removeAllRanges();

    range.selectNodeContents(el);
    selection.addRange(range);

    try {
        document.execCommand('copy');
        alert('Texto copiado al portapapeles');
    } catch (err) {
        console.log('Failed to copy text: ', err);
    }

    selection.removeAllRanges();
}</script>

<form method="post">

<?php wp_nonce_field('devlog_nonce_action', 'devlog_nonce_field'); ?>

<table class="form-table" id="aicc-fieldset-one">

		<h2><?php _e('General Options', 'aicc'); ?></h2>

		<?php

		if ( ( isset( $_POST['devlog_nonce_field'] ) && wp_verify_nonce($_POST['devlog_nonce_field'], 'devlog_nonce_action') ) && ( current_user_can('manage_options') ) )
		{
			
			$error = false;

			$post_types = get_post_types(array('public' => true), 'names');

			foreach ($post_types as $post_type) {
			    $option_name = "aicc_enable_{$post_type}";
			    if (isset($_POST[$option_name]) && $_POST[$option_name] == 1) {
			        update_option($option_name, '1', '', 'yes');
			    } else {
			        delete_option($option_name);
			    }
			}

			if (isset($_POST['aicc_include_context']) && $_POST['aicc_include_context'] == 1) {
				update_option('aicc_include_context', '1', '', 'yes');
			}
			else {
				delete_option('aicc_include_context');
			}	

			update_option('aicc_ajust_model', isset($_POST['aicc_ajust_model']) ? 1 : 0);

			if (isset($_POST['aicc_model'])) {
				update_option('aicc_model', $_POST['aicc_model'], '', 'yes');
			}
			else {
				delete_option('aicc_model');
			}	


			
			if (isset($_POST['aicc_custom_days']) && !empty($_POST['aicc_custom_days'])) {
				update_option('aicc_custom_days', $_POST['aicc_custom_days'], 'yes');
			}

			if (isset($_POST['aicc_schedule_sc'])) {
				update_option('aicc_schedule_sc', $_POST['aicc_schedule_sc'], '', 'yes');
				 if (!wp_next_scheduled('aicc_cron_sc')) {
			        wp_schedule_event(time(), 'daily', 'aicc_cron_sc');
			    }
			}
			else {
				delete_option('aicc_schedule_sc');
				wp_clear_scheduled_hook('aicc_cron_sc');
			}	

			if (isset($_POST['aicc_enable_autoindex'])) {
				update_option('aicc_enable_autoindex', $_POST['aicc_enable_autoindex'], '', 'yes');
			}
			else {
				delete_option('aicc_enable_autoindex');
			}		
			
			if (isset($_POST['aicc_language'])) {
				update_option('aicc_language', $_POST['aicc_language'], '', 'yes');
			}
			else {
				delete_option('aicc_language');
			}	

			
			if (isset($_POST['aicc_delete_cache']) && $_POST['aicc_delete_cache'] == 1) 
			{
						
				$success = $this->aicc_search_console_first();

				if ($success) 
				{
					echo '<div class="notice notice-success is-dismissible"><p><strong>'.__("Se obtuvieron los datos actualizados de Search Console correctamente", "aicc").'.</strong></p></div>';
					
				} else
				{
					$error = true;
					echo '<div class="notice notice-error is-dismissible"><p><strong>'.__("Hubo un error al conectarse con Search Console. Verifica los permisos de tu clave API de Search Console o prueba cambiando de tipo de propiedad en las opciones del plugin", "aicc").'.</strong></p></div>';
				}

			}

			if (isset($_POST['aicc_force_ssl'])) {
				update_option('aicc_force_ssl', $_POST['aicc_force_ssl'], '', 'yes');
			}
			else {
				delete_option('aicc_force_ssl');
			}	

			if (isset($_POST['aicc_enable_basic_auth'])) {
				update_option('aicc_enable_basic_auth', $_POST['aicc_enable_basic_auth'], '', 'yes');
			}
			else {
				delete_option('aicc_enable_basic_auth');
			}	

			if (isset($_POST['aicc_force_cancel']) && $_POST['aicc_force_cancel'] == 1) 
			{
				wp_clear_scheduled_hook( 'aicc_manual_cron' );
			
				delete_transient('aicc_is_running');					
				
				delete_site_transient('aicc_manual_process_lock');			
								
				$this->manual->cancel();
				
				echo '<div class="notice notice-success is-dismissible"><p><strong>'.__("Proceso en ejecución cancelado.", "aicc").'</strong></p></div>';
				
			}
			
			if (!$error)
			{
				echo '<div class="notice notice-success is-dismissible"><p><strong>'.__("Saved Settings", "aicc").'.</strong></p></div>';
			}

			update_option('aicc_enable_schema_faq', $_POST['aicc_enable_schema_faq'], '', 'yes');
			update_option('aicc_enable_schema_video', $_POST['aicc_enable_schema_video'], '', 'yes');


		}

		$include_context = get_option('aicc_include_context');

		$ajust_model = get_option('aicc_ajust_model', 1);

		$model = get_option('aicc_model', 'gpt-4o-mini');

		// Actualiza modelos antiguos del plugin a los nuevos modelos
		$models = [
		    'gpt-3.5-turbo' => 'gpt-3.5-turbo-0125',
		    'gpt-4' => 'gpt-4-1106-preview',
		    'gpt-4-0125-preview' => 'gpt-4-1106-preview'
		];

		$model = $models[$model] ?? $model;

		$custom_days = get_option('aicc_custom_days') ? : '90';

		$schedule_sc = get_option('aicc_schedule_sc');

		$enable_autoindex = get_option('aicc_enable_autoindex');

		$language = get_option('aicc_language', 'es');

		$languageMap = [
		    'es' => 'Español',
		    'en' => 'Inglés',
		    'ar' => 'Árabe',
		    'bg' => 'Búlgaro',
		    'cs' => 'Checo',
		    'da' => 'Danés',
		    'de' => 'Alemán',
		    'el' => 'Griego',
		    'fi' => 'Finlandés',
		    'fr' => 'Francés',
		    'he' => 'Hebreo',
		    'hi' => 'Hindi',
		    'hu' => 'Húngaro',
		    'id' => 'Indonesio',
		    'it' => 'Italiano',
		    'ja' => 'Japonés',
		    'ko' => 'Coreano',
		    'ms' => 'Malayo',
		    'nl' => 'Holandés',
		    'no' => 'Noruego',
		    'pl' => 'Polaco',
		    'pt' => 'Portugués',
		    'ro' => 'Rumano',
		    'ru' => 'Ruso',
		    'sv' => 'Sueco',
		    'th' => 'Tailandés',
		    'tr' => 'Turco',
		    'uk' => 'Ucraniano',
		    'vi' => 'Vietnamita',
		    'zh' => 'Chino',
		];

		$force_ssl = get_option('aicc_force_ssl');

		$enable_basic_auth = get_option('aicc_enable_basic_auth');

		$enable_schema_faq = get_option('aicc_enable_schema_faq', true);
		$enable_schema_video = get_option('aicc_enable_schema_video', true);

		?>

		<tbody>
			
			<?php

			$post_types = get_post_types(array('public' => true), 'names');

			$excluded_post_types = array('attachment');

			$post_types = array_diff($post_types, $excluded_post_types);

			foreach ($post_types as $post_type) {
		    $enable_option = get_option("aicc_enable_{$post_type}");
		 	$post_type_object = get_post_type_object($post_type);
    		$post_type_label = $post_type_object->labels->singular_name;
		    ?>
		    <tr>
		        <th>
		            <label for="aicc_enable_<?php echo $post_type; ?>"><?php echo sprintf(__('Enable on %s', 'aicc'), $post_type_label); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php printf(__('Enable content curation in %s. If you activate this option, the corresponding metabox will appear.', 'aicc'), $post_type); ?></span></span>
		        </th>
		        <td>
		            <input name="aicc_enable_<?php echo $post_type; ?>" id="aicc_enable_<?php echo $post_type; ?>" type="checkbox" value="1" <?php checked($enable_option, 1); ?>>
		        </td>
		    </tr>
		    <?php

			}

			?>

			<tr>
				<th>
					<label for="aicc_include_context"><?php _e('Include content as context', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('By enabling this option, existing post content will be included in the message sent to OpenAI to provide additional context. This helps generate more coherent and relevant responses. Please note that this option will consume more tokens and therefore may increase the associated costs. It is ideal for situations where accuracy and relevance of context are critical to the quality of the content generated.', 'aicc'); ?></span></span>
				</th>
				<td>
					<input name="aicc_include_context" id="aicc_include_context" type="checkbox" value="1" <?php checked( $include_context, 1 ); ?>>
				</td>
			</tr>	

			<tr>
			    <th>
			        <label for="aicc_ajust_model"><?php _e('Usar modelo recomendado', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('Al activar esta opción, el plugin ajustará automáticamente el modelo de inteligencia artificial utilizado en función del tipo de curación seleccionada. Esto permite optimizar la relación entre calidad y costo, eligiendo el modelo ideal para cada tarea, como curaciones masivas de contenido, imágenes, videos o metaetiquetas. Activar esta opción es útil para obtener resultados precisos en cada curación, sin necesidad de cambiar el modelo manualmente.', 'aicc'); ?></span></span>
			    </th>
			    <td>
			        <input name="aicc_ajust_model" id="aicc_ajust_model" type="checkbox" value="1" <?php checked( $ajust_model, 1 ); ?>>
			    </td>
			</tr>
			
			<tr id="campo_model" <?php if ($ajust_model):?>style="display: none;"<?php endif;?>>
				<th>
					<label for="aicc_model"><?php _e('Processing model', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('El modelo GPT 4 Turbo es más potente y genera mejores resultados que GPT 3.5 Turbo. GPT 4o y GPT4o mini son muy potentes pero a veces no respetan las negritas.', 'aicc'); ?></span></span>
				</th>
				<td>
					
<select name="aicc_model" id="aicc_model">
    <option value="gpt-4o-mini" <?php selected($model, 'gpt-4o-mini'); ?>><?php _e('GPT 4o mini', 'aicc'); ?></option>
    <option value="gpt-4o" <?php selected($model, 'gpt-4o'); ?>><?php _e('GPT 4o', 'aicc'); ?></option>
    <option value="gpt-4-1106-preview" <?php selected($model, 'gpt-4-1106-preview'); ?>><?php _e('GPT 4 Turbo', 'aicc'); ?></option>
    <option value="gpt-4.1-mini" <?php selected($model, 'gpt-4.1-mini'); ?>><?php _e('GPT 4.1 Mini', 'aicc'); ?></option>
    <option value="gpt-4.1-nano" <?php selected($model, 'gpt-4.1-nano'); ?>><?php _e('GPT 4.1 Nano', 'aicc'); ?></option>
    <option value="gpt-3.5-turbo-0125" <?php selected($model, 'gpt-3.5-turbo-0125'); ?>><?php _e('GPT 3.5 Turbo', 'aicc'); ?></option>
</select>

		        	<?php echo '<span id="token_cost">' . $this->aicc_get_token_cost($model) . '</span>'; ?>
				</td>
			</tr>
			
			<tr>
				<th>
					<label for="aicc_language"><?php _e('Language', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('The language you select here will be set as the default for each post or page when you curate content. However, you can modify it manually on each post or page if you wish.', 'aicc'); ?></span></span>
				</th>
				<td>
					<select name="aicc_language" id="aicc_language">
		                <?php
							foreach ($languageMap as $code => $name) {
							        echo '<option value="' . $code . '" ' . selected($language, $code, false) . '>' . __($name, 'aicc') . '</option>';

							}
						?>
		        	</select>
				</td>
			</tr>	

			<tr>
				<th>
					<label for="aicc_custom_days"><?php _e('Custom days', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('By default, the plugin captures the last 90 days of data from Search Console. You can change the number of days with this option. Keep in mind that the last days will always be captured based on the selected number.', 'aicc'); ?></span></span>
				</th>
				<td>
					<input style="width:60px; padding: 2px 8px !important;"  name="aicc_custom_days" id="aicc_custom_days" type="number"  value="<?php echo $custom_days ; ?>"/> días
				</td>
			</tr>
			
			<tr>
				<th>
					<label for="aicc_schedule_sc"><?php _e('Actualizar datos diariamente', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('If you activate this option, the plugin will automatically connect with Search Console once a day to get all the updated data.', 'aicc'); ?></span></span>
				</th>
				<td>
					<input name="aicc_schedule_sc" id="aicc_schedule_sc" type="checkbox" value="1" <?php checked( $schedule_sc, 1 ); ?>>
				</td>
			</tr>				
			
			<tr>
				<th>
					<label for="aicc_enable_autoindex"><?php _e('Automatically reindex', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('Every time you update content, it will automatically be sent to the Google Indexing API so it can be crawled faster. You must enable the Indexing API in your Google Cloud account and grant the user owner permissions in Search Console.', 'aicc'); ?></span></span>
				</th>
				<td>
					<input name="aicc_enable_autoindex" id="aicc_enable_autoindex" type="checkbox" value="1" <?php checked( $enable_autoindex, 1 ); ?>>
					<span style="display:block;margin-top: 8px; font-style: italic;">Para reindexar automáticamente los contenidos es necesario darle permisos de propietario al usuario en Search Console y habilitar la <a href="https://developers.google.com/search/apis/indexing-api/v3/quickstart?hl=es-419" target="_blank" rel="nofollow noopener">API de indexación de Google</a>.</span>
				</td>
			</tr>		

			<tr>
				<th>
					<label for="aicc_enable_schema_faq"><?php _e('Activar schema FAQ', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('Marca esta opción para mostrar automáticamente los datos estructurados de FAQ en el contenido de tus artículos, siempre que haya sido generado previamente, mejorando la visibilidad en motores de búsqueda.', 'aicc'); ?></span></span>
				</th>
				<td>
					<input name="aicc_enable_schema_faq" id="aicc_enable_schema_faq" type="checkbox" value="1" <?php checked( $enable_schema_faq, 1 ); ?>>
				</td>
			</tr>

			<tr>
				<th>
					<label for="aicc_enable_schema_video"><?php _e('Activar schema video', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('Marca esta opción para mostrar automáticamente los datos estructurados de Video en el contenido de tus artículos, siempre que haya sido generado previamente, mejorando la visibilidad en motores de búsqueda.', 'aicc'); ?></span></span>
				</th>
				<td>
					<input name="aicc_enable_schema_video" id="aicc_enable_schema_video" type="checkbox" value="1" <?php checked( $enable_schema_video, 1 ); ?>>
				</td>
			</tr>
			<tr>
				<th>
					<label for="aicc_delete_cache"><?php _e('Delete caché', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('The plugin caches Search Console data for 7 days to improve performance. Clear the cache if you want to get the data updated to today.', 'aicc'); ?></span></span>
				</th>
				<td>
					<input name="aicc_delete_cache" id="aicc_delete_cache" type="checkbox" value="1">
				</td>
			</tr>

			
            <tr>
                <th>
                    <label for="aicc_unlock_process"><?php _e('Desbloquear proceso', 'aicc'); ?></label>
                    <span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('Si una tarea, ya sea un procesamiento individual o una operación de curación masiva, se demora excesivamente o impide iniciar nuevas operaciones debido a que está en curso, es probable que se haya bloqueado. Utiliza esta opción para desbloquear el proceso y luego podrás reanudar el trabajo normalmente.', 'aicc'); ?></span></span>
                </th>
                <td style="display: flex; width: 100%;">
                    <select id="unlock_type">
                        <option value="manual_curation"><?php _e('Curación manual', 'aicc'); ?></option>
                        <option value="masive_curation"><?php _e('Curación masiva', 'aicc'); ?></option>
                    </select>
                    <button id="aicc_unlock_process" class="button"><?php _e('Desbloquear', 'aicc'); ?></button>
                    <span class="spinner is-active" style="display:none;"></span>
                </td>
            </tr>

			<tr>
				<th>
					<input type="hidden" name="aicc_from" id="aicc_from" value="general-settings" />
					<?php submit_button(); ?>
				</th>
			</tr>
			
			
		</tbody>

	</table>

</form>
	
<?php else: ?>

<div class="notice notice-warning inline active-plugin-edit-warning" style="margin:10px !important;"><p>Parece que no tienes los permisos suficientes para ver esta página.</p></div>

<?php endif; ?>

<script type="text/javascript">
	jQuery(document).ready(function() {
	    jQuery('#aicc_model').change(function() {
	        var selectedModel = jQuery(this).val();
	        var cost;
		        
			switch(selectedModel) {
			    case 'gpt-3.5-turbo-0125':
			        cost = '0.0015$ cada 750 palabras';
			        break;
			    case 'gpt-4-1106-preview':
			        cost = '0.03$ cada 750 palabras';
			        break;
			    case 'gpt-4o':
			        cost = '0.01$ cada 750 palabras';
			        break;
			    case 'gpt-4o-mini':
			        cost = '0.0006$ cada 750 palabras';
			        break;
			    case 'gpt-4.1-mini':
			        cost = '0.0016$ cada 750 palabras';
			        break;
			    case 'gpt-4.1-nano':
			        cost = '0.0004$ cada 750 palabras';
			        break;
			}


	        jQuery('#token_cost').text(cost);
	    });

	    // Función para mostrar/ocultar el campo
	    function toggleCampoModel() {
	        if (jQuery('#aicc_ajust_model').is(':checked')) {
	            jQuery('#campo_model').fadeOut();
	        } else {
	            jQuery('#campo_model').fadeIn();
	        }
	    }

	    // Evento de cambio para el checkbox
	    jQuery('#aicc_ajust_model').on('change', function() {
	        toggleCampoModel();
	    });
    

	});
</script>