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

<style>
	#calcular-costo-btn {
		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;
	}
	
	#calcular-costo-btn:hover {
		background:#f7e7ff;
		border-color:#f1556c;
	}
	
	#calcular-costo-btn:active {
		border-color:#d174ff
	}
	
	span.aicc-status.green {
		color:#00a320 !important;
		font-weight:bold;
	}
	
	span.aicc-status.red {
		color:#e65054 !important;
		font-weight:bold;
	}
	
	#cancel-bulk-process {
		cursor: pointer;
		text-decoration: underline;
	}

	#cancel-bulk-process:hover {
		text-decoration: none;
	}
	.aicc-tooltip-a { cursor:pointer; }

	.aicc-options h2 {
	    display: flex;
	    align-items: center;
	}

	.aicc-options h2 span {
	    background: #202225;
	    color: #fff;
	    margin-left: 6px;
	}

</style>
<?php

global $wpdb;

$status = '';

$is_error = get_transient('aicc_error_bulk');

if ( $is_error ) {
	$admin_link = admin_url('admin.php?page=aicc-log');
	echo '<div class="notice notice-error is-dismissible"><p><strong>Se produjo un error</strong>. Revisa el registro de depuración del plugin para identificar la causa del problema o contacta con nuestro equipo de soporte. <a target="_blank" href="' . esc_url($admin_link) . '">Ir al registro de depuración</a></p></div>';
	delete_transient('aicc_error_bulk');
	$success_message = 'La curación en bulk terminó.';	
}
else
{
	$success_message = 'La curación en bulk se completó con éxito.';
}

$is_run = get_transient('aicc_is_bulk_running');

$is_end = get_transient('aicc_end_bulk');

$is_cancel = $wpdb->get_var("SELECT option_value FROM $wpdb->options WHERE option_name = 'aicc_cancel_bulk_process' LIMIT 1");

$is_cancel = $is_cancel === '1';

$discarded = get_transient('aicc_bulk_discarded_count');
if ($discarded === false || !$discarded ) {
	$discarded = 0;
}

if ($is_cancel) {
    $status = 'cancel';
} elseif ($is_run) {
    $status = 'run';
} elseif ($is_end) {
    $status = 'end';
} else {
    $status = '';
}


if ($status == 'cancel') {
echo '<div class="notice notice-warning is-dismissible"><p>' . __('El proceso de cancelación está en curso. Por favor, ten paciencia, este proceso puede tardar unos minutos.', "aicc") . '</p></div>';
	delete_option('aicc_bulk_total_posts');
	delete_option('aicc_bulk_processed_count');;
} elseif ($status == 'run') {
	$total_posts = get_option('aicc_bulk_total_posts');
	$processed_count = get_option('aicc_bulk_processed_count');	
    if ($processed_count === false || !$processed_count ) {
        $processed_count = 0;
    }
	$currentBulkProcessId = get_transient('aicc_current_bulk_process_id');
	if (false === $currentBulkProcessId) {
	    $currentBulkProcessId = '';
	}
	$resultado = null;
	$type = '';
	$type_ed = '';		
	if (false !== $currentBulkProcessId && $currentBulkProcessId > 0) {
	    $sql = $wpdb->prepare("SELECT type FROM " . AICC_BULK_TABLE . " WHERE id = %d", $currentBulkProcessId);
	    $resultado = $wpdb->get_row($sql);
	    if ($resultado){
	    	$type = $resultado->type;
	    }
	}
    if ($type == 'Contenido') {
    	$type_ed = 'contenidos';
    }elseif ($type == 'Imagen'){
    	$type_ed = 'imágenes';
    }elseif ($type == 'Metaetiqueta'){
    	$type_ed = 'metaetiquetas';
    }
	$message = '<strong>Curación de '.$type_ed.' en proceso</strong>';
	if ($type == 'Metaetiqueta') {
		$message .= ' · Procesados <strong>' . $processed_count . '</strong> de <strong>' . $total_posts  . '</strong>';
		if($discarded){
			$message .= ' · ' . $discarded . ' descartados';
		}
		$message .=  ' · <span id="cancel-bulk-process">Cancelar proceso</span>';
	}
	echo '<div class="notice notice-success is-dismissible"><p>'.$message.'</p></div>';
} elseif ($status == 'end') {
	delete_transient('aicc_end_bulk');
	echo '<div class="notice notice-success is-dismissible"><p><strong>'.__($success_message, "aicc").'</strong></p></div>';
}

$option_bulkt_budget = get_option('aicc_bulkt_budget', '');

$plugin_seo_activo = $this->aicc_detect_seo_plugin();

if (!$plugin_seo_activo) :

?>

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

	<h2><?php _e('Metatags Bulk Curation', 'aicc'); ?> <span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('In this section you can create metatitles and meta tags for all your articles in bulk and automatically. This feature integrates with the most popular SEO plugins: Yoast SEO, Rank Math and AIOSEO.', 'aicc'); ?></span></span></h2>
	<br>
	<div class="notice notice-warning inline active-plugin-edit-warning" ><p>Parece que no tienes ninguno de los plugins de SEO compatibles con esta función de Content Curator.</p><p>Los plugins compatibles, por ahora, son Yoast SEO, Rank Math y AIOSEO.</p></div>

	</table>

<?php else: ?>

	<form method="post" id="form-bulk-content">

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

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

		<h2><?php _e('Metatags Bulk Curation', 'aicc'); ?> <span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('In this section you can create metatitles and meta tags for all your articles in bulk and automatically. This feature integrates with the most popular SEO plugins: Yoast SEO, Rank Math and AIOSEO.', 'aicc'); ?></span></span></h2>

		<tbody>
		    <?php
		        $post_types = get_post_types(array('public' => true), 'names');
		        $excluded_post_types = array('attachment', 'product'); // Se añadió 'product' aquí
		        $post_types = array_diff($post_types, $excluded_post_types);

				// Recuperar las opciones guardadas o establecer valores predeterminados
				$saved_post_type = get_option('aicc_bulkt_post_type', 'post');
				$saved_overwrite = get_option('aicc_bulkt_overwrite', '0');
				$saved_budget = get_option('aicc_bulkt_budget', 0);
				$saved_include = get_option('aicc_bulkt_include', '');
				$saved_exclude = get_option('aicc_bulkt_exclude', '');
				$saved_seo_plugin = get_option('aicc_bulkt_seo_plugin', '');
				$saved_exclude_already = get_option('aicc_bulkt_exclude_already', '0');
		    ?>
		    <tr>
		        <th>
		            <label for="aicc_bulkt_post_type"><?php _e('Run on', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('Select the type of content where bulk curation will run.', 'aicc'); ?></span></span>
		        </th>
		        <td>
		           <select name="aicc_bulkt_post_type" id="aicc_bulkt_post_type">
		            <?php foreach ($post_types as $post_type): ?>
		                <?php 
		                    $post_type_object = get_post_type_object($post_type);
		                    $post_type_label = $post_type_object->labels->singular_name;
		                ?>
		                <option value="<?php echo $post_type; ?>" <?php selected($saved_post_type, $post_type); ?>><?php echo $post_type_label; ?></option>
		            <?php endforeach; ?>
		            </select>
		        </td>
		    </tr>

				<tr>
				    <th>
				        <label for="aicc_bulkt_seo_plugin"><?php _e('SEO Plugin Used', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('The SEO plugin that you have active.', 'aicc'); ?></span></span>
				    </th>
				    <td>
				        <select disabled name="aicc_bulkt_seo_plugin" id="aicc_bulkt_seo_plugin">
				            <option value="<?php echo esc_attr($plugin_seo_activo); ?>" selected="selected"><?php echo esc_html($plugin_seo_activo); ?></option>
				        </select>
				    </td>
				</tr>

		    <tr>
		        <th>
		            <label for="aicc_bulkt_overwrite"><?php _e('Overwrite metatags with data', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('Enabling this feature will replace existing data in all meta tags. Otherwise, only those meta tags that are without information will be filled in.', 'aicc'); ?></span></span>
		        </th>
		        <td>
		            <input name="aicc_bulkt_overwrite" id="aicc_bulkt_overwrite" type="checkbox" value="1" <?php checked($saved_overwrite, '1'); ?>>
		        </td>
		    </tr>

		    <tr>
		        <th>
		            <label for="aicc_bulkt_exclude_already"><?php _e('Descartar contenido ya procesado', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('By activating this feature, items that have already been previously curated will be excluded from processing.', 'aicc'); ?></span></span>
		        </th>
		        <td>
		            <input name="aicc_bulkt_exclude_already" id="aicc_bulkt_exclude_already" type="checkbox" value="1" <?php checked($saved_exclude_already, '1'); ?>>
		        </td>
		    </tr>

		    <tr>
		        <th>
		            <label for="aicc_bulkt_budget"><?php _e('Presupuesto máximo', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('Esta función te permite establecer un presupuesto máximo estimado para la curación masiva. La curación finalizará automáticamente una vez que se consuma el presupuesto especificado. Si estableces el presupuesto en 0, este será considerado ilimitado, permitiendo que la curación continúe hasta que decidas finalizarla manualmente.', 'aicc'); ?></span></span>
		        </th>
		        <td>
		            <input style="width:60px" step="1" name="aicc_bulkt_budget" id="aicc_bulkt_budget" type="number" value="<?php echo esc_attr($saved_budget); ?>" min="0" max="100"/> <span> dólares</span>
		        </td>
		    </tr>

		    <tr>
		        <th>
		            <label for="aicc_bulkt_include"><?php _e('Seleccionar contenidos', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('Utiliza esta opción para seleccionar específicamente las publicaciones o páginas que desea curar en masa. Al activar esta funcionalidad, solo se seleccionarán los elementos seleccionados manualmente, excluyendo automáticamente cualquier otro contenido no marcado. Si no seleccionas ninguno, el proceso procesará todos los contenidos.', 'aicc'); ?></span></span>
		        </th>
		        <td>
		            <input style="width:250px" name="aicc_bulkt_include" id="aicc_bulkt_include" type="text" value="<?php echo esc_attr($saved_include); ?>"/> 
		        </td>
		    </tr>

		    <tr>
		        <th>
		            <label for="aicc_bulkt_exclude"><?php _e('Exclude content', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('Select the posts or pages you want to exclude from mass content curation.', 'aicc'); ?></span></span>
		        </th>
		        <td>
		            <input style="width:250px" name="aicc_bulkt_exclude" id="aicc_bulkt_exclude" type="text" value="<?php echo esc_attr($saved_exclude); ?>"/> 
		        </td>
		    </tr>

		    <tr>
		        <th>
		            <label for="calcular-costo-btn"><?php _e('Calculate cost', 'aicc'); ?></label><span class="aicc-tooltip">?<span class="tooltiptext"><?php _e('Find out the approximate cost of the cure. Please note that this value is an estimate and may vary based on OpenAI responses.', 'aicc'); ?></span></span>
		        </th>
		        <td style="display: flex;align-items: center; margin-top:6px">
		            <button id="calcular-costo-btn" class="button"><?php _e('Calculate', 'aicc'); ?></button>
		            <span class="spinner is-active" style="display:none;"></span>
		            <span id="resultado-costo" style="margin-left:10px"></span>
		        </td>
		    </tr>

		    <tr>
		        <th>
		            <input type="hidden" name="aicc_from" id="aicc_from" value="general-settings" />
		            <div style="display:flex; align-items: center"><?php submit_button('Empezar'); ?><span class="spinner is-active" style="display:none;"></span></div>
		        </th>
		    </tr>
		</tbody>


	</table>

	</form>

	<script>

		jQuery(document).ready(function($) {

			var allSuggestions = {
			    <?php
			    $post_types = get_post_types(array('public' => true), 'names');
			    $excluded_post_types = array('attachment', 'product');
			    $post_types = array_diff($post_types, $excluded_post_types);

			    foreach ($post_types as $post_type) {
			        echo "'$post_type': [";

			        $args = array('post_type' => $post_type, 'posts_per_page' => -1);
			        $posts = get_posts($args);
			        foreach ($posts as $post) {

			            $title = addslashes($post->post_title);
		    			$special_chars = array(".", "-", "'", "'", "\"", "\n", "\r", "\t", "&", "<", ">");
					    $title = str_replace($special_chars, " ", $title);	            
			            echo "{tag: '$title', value: '{$post->ID}'},";
			        }

			        echo "],";
			    }
			    ?>
			};

			jQuery(document).ready(function($) {
			    // Función para inicializar/reinicializar Amsify Suggestags
			    function initializeSuggestags(postType, inputName) {
			        var suggestionsElement = $('input[name="' + inputName + '"]');
			        
			        // Asegurarse de destruir la instancia anterior si existe
			        if (suggestionsElement.data('amsifySuggestags')) {
			            suggestionsElement.suggestags('destroy');
			        }
			        
			        // Filtrar sugerencias basadas en el tipo de publicación seleccionado
			        var filteredSuggestions = allSuggestions[postType] || [];
			        
			        // Inicializar Amsify Suggestags con las nuevas sugerencias
			        suggestionsElement.amsifySuggestags({
			            showAllSuggestions: true,
			            keepLastOnHoverTag: false,
			            suggestions: filteredSuggestions,
			            whiteList: true
			        });
			    }

			    // Escuchar cambios en el selector de tipo de publicación
			    $('#aicc_bulkt_post_type').change(function() {
			        var selectedPostType = $(this).val();
			        // Inicializar para ambos campos de entrada
			        initializeSuggestags(selectedPostType, "aicc_bulkt_include");
			        initializeSuggestags(selectedPostType, "aicc_bulkt_exclude");
			    });

			    // Inicializar Amsify Suggestags con el tipo de publicación inicial para ambos campos
			    var initialPostType = $('#aicc_bulkt_post_type').val();
			    initializeSuggestags(initialPostType, "aicc_bulkt_include");
			    initializeSuggestags(initialPostType, "aicc_bulkt_exclude");
			});

		    $('#calcular-costo-btn').click(function(e) {
		    	e.preventDefault();
		        var postType = $('#aicc_bulkt_post_type').val();
				var include = jQuery('#aicc_bulkt_include').val();		        

		        $('#resultado-costo').html('');

		        var spinner = $(this).next('.spinner'); 
							
				spinner.css({
					'float': 'none',          
					'margin-top': '5px',     
					'margin-left': '10px'    
				});
							
				spinner.show();

		        $.ajax({
		            url: ajaxurl,
		            type: 'POST',
		            data: {
		                action: 'aicc_return_total_cost',
		                postType: postType,
		                include: include,
		               	type: 'metatags',
		            },
		            success: function(response) {
		            		spinner.hide();
		                $('#resultado-costo').html('Costo estimado: $' + response);
		            },
		            error: function() {
		                $('#resultado-costo').html('Error al calcular el costo.');
		            }
		        });
		    });

		    $('#cancel-bulk-process').click(function(e) {
			    e.preventDefault();
			    var spinner = $(this).next('.spinner'); 

			    // SweetAlert para confirmar la cancelación
			    Swal.fire({
			        text: "¿Estás seguro de que quieres cancelar la curación en curso?",
			        icon: 'warning',
			        showCancelButton: true,
			      	confirmButtonText: 'Sí, cancelar',
	        		cancelButtonText: 'No, continuar'
			    }).then((result) => {
			        if (result.value) {
			            $.ajax({
			                url: ajaxurl,
			                type: 'POST',
			                data: {
			                    action: 'aicc_cancel_bulk_process'
			                },
			                success: function(response) {
			                       Swal.fire({
								        icon: 'success',
								        text: 'El proceso se está cancelando',
								        confirmButtonText: 'Aceptar'
									}).then((result) => {
									    if (result.isConfirmed) {
									        location.reload();
									    }
								   });
			                },
			                error: function() {
			                    // Manejar el error adecuadamente
			                    Swal.fire({
			                        icon: 'error',
			                        text: 'Hubo un error al cancelar el proceso',
			                        confirmButtonText: 'Aceptar'
			                    });
			                }
			            });
			        } else {
			            // Usuario canceló la cancelación
			            Swal.fire({
			                icon: 'success',
			                text: 'La curación sigue su curso',
			                confirmButtonText: 'Aceptar'
			            });
			        }
			    });
			});


	    function checkBulkRunning(callback) {
	      jQuery.ajax({
	        url: ajaxurl,
	        type: "POST",
	        data: {
	          action: "aicc_check_bulk_running"
	        },
	        dataType: "json",
	        success: function (response) {
	          if (response.check_status === 'processing' || response.check_status === 'missing') {
	            Swal.fire({
	              icon: 'error',
	              text: response.message,
	              confirmButtonText: 'Aceptar'
	            });
	            callback(false);
	            spinner.hide();
	          } else {
	            callback(true);
	          }
	        },
	        error: function (xhr, status, error) {
	          alert("Error: " + error);
	          callback(false);
	        }
	      });
	    }

	    $("#form-bulk-content").off("click", "#submit").on("click", "#submit", function(e) {
	     
	     e.preventDefault();

		// Verificar si la opción de OpenAI está configurada
	    var openaiKey = '<?php echo esc_js(get_option('aicc_options_openai')); ?>';
	    if (!openaiKey) {
	        Swal.fire({
	            icon: 'warning',
	            text: 'Para continuar, es necesario ingresar tu clave API de OpenAI en las opciones del plugin.',
	            confirmButtonText: 'Aceptar'
	        });
	        return; 
	    }	      

		var spinner = $(this).parent().next('.spinner');
							
		spinner.css({
			'float': 'none',          
			'margin-top': '10px',     
			'margin-left': '10px'    
		});
							
		spinner.show();

	    checkBulkRunning(function (canContinue) {
	        if (canContinue) {
	          Swal.fire({
	            text: "¿Deseas empezar la curación masiva de metaetiquetas?",
	            icon: 'warning',
	            showCancelButton: true,
	            confirmButtonText: 'Empezar',
	            cancelButtonText: 'Cancelar'
	          }).then((result) => {
	            if (result.value) {
	              var nonce = '<?php echo esc_js(wp_create_nonce("aicc_process_bulkt_content")); ?>';
	              var postType = jQuery('#aicc_bulkt_post_type').val();
         		  var overwrite = jQuery('#aicc_bulkt_overwrite').prop('checked') ? '1' : '0';
	              var budget = jQuery('#aicc_bulkt_budget').val();	             
	              var include = jQuery('#aicc_bulkt_include').val();
	              var exclude = jQuery('#aicc_bulkt_exclude').val();
	              var seo_plugin = jQuery('#aicc_bulkt_seo_plugin').val();
	              var excludeAlready = jQuery('#aicc_bulkt_exclude_already').prop('checked') ? '1' : '0';

	              jQuery.ajax({
	                url: ajaxurl,
	                type: "POST",
	                data: {
	                  action: "aicc_process_bulkt_content",
	                  aicc_bulkt_post_type: postType,
	                  aicc_bulkt_overwrite: overwrite,
	                  aicc_bulkt_budget: budget,	                  
	                  aicc_bulkt_include: include,
	                  aicc_bulkt_exclude: exclude,
	                  aicc_bulkt_seo_plugin: seo_plugin,
	                  aicc_bulkt_exclude_already: excludeAlready,	                  
	                  nonce: nonce
	                },
	                success: function (response) {
	                  console.log(response);
	                  Swal.fire({
	                    icon: 'success',
	                    text: '¡La curación masiva de metaetiquetas ha iniciado!',
	                    confirmButtonText: 'Aceptar'
	                  }).then((result) => {
	                  	spinner.hide();
	                    if (result.value) {
	                      location.reload();
	                    }
	                  });
	                },
	                error: function (xhr, status, error) {
	                  alert("Error: " + error);
	                }
	              });
	            } else {
	              spinner.hide();
	            }
	          });
	        }
	        else
	        {
	        	spinner.hide();
	        }
	      });
	    });
	  });
	</script>

	<?php endif; ?>

<?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; ?>