	<style>

	.aicc-options table.widefat {
		margin-top:1.5rem;
		font-size:14px;
		border:1px solid #e2e4e7;
	}
				
	.aicc-options .widefat td
	{
		font-size:14px;			
	}
				
	.aicc-options table.widefat th,
	.aicc-options table.widefat td {
		padding:1rem 1.1rem;	
	}
				
	.widefat thead th {
		background:#fff;
		border-bottom:1px solid #e2e4e7;
		background:#fff;
	}
				
	.widefat tbody tr:nth-child(even) {
		background-color: #fff;
	}

	.widefat tbody tr:nth-child(odd) {
	  	background-color: #f6f7f7;
	}
				
	.aicc-options .widefat .icon-tabler-alert-circle {
		position:absolute;
	}
				
	.aicc-options .widefat .icon-tabler-alert-circle  + span {
		margin-left:24px;
		display:block;
	}
		
	.aicc-options h2 {
	    display: flex;
	    align-items: center;
	}

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

	.view-content-btn {
		cursor: pointer
	}	

	.aicc-cancel-btn {
		font-size: 13px !important;
	}

	span.aicc-badge {
		margin-left: 6px;
    	padding: 2px 6px 4px 6px !important;
    	cursor: help;
    }
    ul.aicc-list-processed>li {
    	margin-bottom: .75rem;
        }	
    ul.aicc-list-processed li ul li {
    	margin-bottom: 0;
    }
    ul.aicc-list-processed li ul li span {
    	cursor: pointer;
    	display: flex;
    	margin-left: 6px;
    }

    ul.aicc-list-processed li ul li span:hover {
    	opacity: .5;
    }

    ul.aicc-list-processed li ul {
    	margin-left: 0 !important;
    }
	</style>

	<?php

   	global $wpdb;

    $items_per_page = 10;

    $current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;

    $offset = ($current_page - 1) * $items_per_page;
 
 	$sql = $wpdb->prepare("SELECT id, type, amount, tokens, cost, budget, model, ids_processed, date FROM " . AICC_BULK_TABLE . " ORDER BY id DESC LIMIT %d OFFSET %d", $items_per_page, $offset);
     
    $resultados = $wpdb->get_results($sql);

    $total_query = "SELECT COUNT(*) FROM " . AICC_BULK_TABLE;

    $total_items = $wpdb->get_var($total_query);

    $total_cost_sql = "SELECT SUM(cost) as total_cost FROM " . AICC_BULK_TABLE;

    $total_cost = $wpdb->get_var($total_cost_sql);

	$currentBulkProcessId = get_transient('aicc_current_bulk_process_id');

	if (false === $currentBulkProcessId) {
		$currentBulkProcessId = '';
	}
					
	?>

  	<h2><?php _e('List of curations', 'aicc'); ?> <span class="aicc-tooltip">?<span class="tooltiptext">En esta sección aparecen todas las ejecuciones masivas realizadas y sus gastos asociados. De momento, llevas gastado un total de $<?php echo rtrim(rtrim(sprintf('%.2f', $total_cost), '0'), '.'); ?></span></span></h2>
			
	<?php if (!$resultados): ?>
				
	<div class="notice notice-warning"><p><?php _e('Todavía no hay curaciones en lote realizadas.', 'aicc'); ?></p></div>

	<?php else: ?>

	<table class="widefat">
		<thead>
			 <tr>
				<th><?php _e('Tipo', 'aicc'); ?></th>
				<th style="text-align:center;"><?php _e('Cantidad', 'aicc'); ?></th>
				<th style="text-align:center;"><?php _e('Tokens', 'aicc'); ?></th>
				<th style="text-align:center;"><?php _e('Cost', 'aicc'); ?></th>		
				<th style="text-align:center;"><?php _e('Presupuesto', 'aicc'); ?></th>		
				<th style="text-align:center;"><?php _e('Fecha', 'aicc'); ?></th>			
				<th style="text-align:center;"><?php _e('Modelo', 'aicc'); ?></th>		
			</tr>
		</thead>
		<tbody>
			<?php foreach ($resultados as $resultado) : ?>
			
			<?php 

			    $content = '';

				$isCurrentProcess = (int) $resultado->id === (int) $currentBulkProcessId;

				$dateObject = new DateTime($resultado->date);
				$date = $dateObject->format('d/m/Y');
				$cost = rtrim(rtrim(sprintf('%.5f', $resultado->cost), '0'), '.');
				$type = $resultado->type;

				if (isset($resultado->budget) && $resultado->budget != 0) {
				    $budget = '$'.rtrim(rtrim(sprintf('%.5f', $resultado->budget), '0'), '.');
				} else {
				    $budget = "Sin límite";
				}

				$ids_processed = $resultado->ids_processed;
				$ids_processed = unserialize($ids_processed);
				if ($ids_processed === false) {
					$ids_processed = [];
				}


				if(!empty($ids_processed)){
					$cantidad = count($ids_processed);
					$content .= '<p>Se procesaron <strong>'.$cantidad.'</strong> contenido(s) en esta ejecución:</p>';
					$content .= '<ul class="aicc-list-processed">';
					foreach ($ids_processed as $post_id => $keywords) {
					    $post = get_post($post_id); 
					    if ($post) { 
					        $title = get_the_title($post_id); 
					        $url = get_permalink($post_id);
						    if ($keywords){
						        $keywordsArray = explode(',', $keywords);
						        $content .= "<li><a href='{$url}' target='_blank'><strong>{$title}</strong></a><ul>";
						        foreach($keywordsArray as $keyword) {
									$content .= "<li style='display:flex;align-items:center;'>" . trim($keyword) . "<span class='copy-icon' data-keyword='" . htmlspecialchars(trim($keyword), ENT_QUOTES) . "'><svg xmlns='http://www.w3.org/2000/svg' class='icon icon-tabler icon-tabler-copy' width='16' height='16' viewBox='0 0 24 24' stroke-width='1.25' stroke='#282828' fill='none' stroke-linecap='round' stroke-linejoin='round'><path stroke='none' d='M0 0h24v24H0z' fill='none'/><path d='M7 7m0 2.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667z' /><path d='M4.012 16.737a2.005 2.005 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1' /></svg></span></li>";
								}
						        $content .= "</ul></li>";
						    } else {
						        // Imágenes y metaetiquetas
						        $content .= "<li><a href='{$url}' target='_blank'>{$title}</a></li>";
						    }
					    }
					}
					$content .= '</ul>';
				}else{
					$content = '<p>Esta ejecución no procesó ningún contenido. Para entender qué ocurrió, te sugerimos revisar el registro de procesamiento del plugin. Encuéntralo en la sección \'<a href="' . admin_url('admin.php?page=aicc-log') . '" target="_blank"><strong>Opciones</strong></a>\'.</p>';
				}

				$content = htmlspecialchars($content, ENT_QUOTES, 'UTF-8');

			?>
			
			<tr>
				<td width="25%">						
				<?php
				echo "<strong>{$type}" . ($isCurrentProcess ? "<span class='aicc-badge aicc-green' title='Hay un proceso ejecutándose'>En ejecución</span>" : "") . "</strong>";
				//echo "<strong>{$type}</strong>";
				echo '<div class="row-actions">';
				echo "<span class='view'><a class='view-content-btn' data-content='{$content}' target='_blank' rel='noopener'>Ver contenido actualizado</a></span>";
				echo "</div>";
				?>
				</td>			  
				<td width="10%" style="text-align:center;"><?php echo $resultado->amount; ?></td>
				<td width="10%" style="text-align:center;"><?php echo $resultado->tokens; ?></td>
				<td width="10%" style="text-align:center;">$<?php echo $cost;  ?></td>
				<td width="10%" style="text-align:center;"><?php echo $budget;  ?></td>
				<td width="10%" style="text-align:center;" title="<?php echo $resultado->date; ?>"><?php echo $date; ?></td>
				<td width="25%" style="text-align:center;"><?php echo $resultado->model; ?></td>
			</tr>
			<?php endforeach; ?>
			
		</tbody>
	
	</table>
			
	<?php
				
 		$pagination_args = array(
            'base' => add_query_arg('paged', '%#%'),
             'format' => '?paged=%#%',
             'total' => ceil($total_items / $items_per_page),
             'current' => $current_page,
             'prev_text' => __('«'),
             'next_text' => __('»'),
		);

		echo '<div class="tablenav"><div class="tablenav-pages">' . paginate_links($pagination_args) . '</div></div>';
				
	?>
			
	<div id="aicc-modal" class="aicc-modal" style="display: none;">
		<div class="aicc-modal-content">
			<div class="loader" style="display: none;"></div>
			<div class="aicc-modal-content-scroll"></div>
			<div id="modal-actions">
				<button class="aicc-cancel-btn">
					<span>Cerrar ventana</span>
				</button>	
			</div>
		</div>
	</div>

	<script>
	jQuery(document).ready(function($) {

		var modal = document.querySelector('.aicc-modal');

		function openModal() {
			setTimeout(function() {
				$('#aicc-modal .aicc-modal-content-scroll').scrollTop(0);
			}, 1); 
			modal.style.display = 'flex';
			
		}

		$('.view-content-btn').on('click', function() {
		    var contentEscaped = $(this).data('content');
		    var content = $("<textarea/>").html(contentEscaped).text(); // Esta línea decodifica las entidades HTML

		    $('#aicc-modal .aicc-modal-content-scroll').html(content);
		    openModal();
		});

		$('.aicc-cancel-btn').on('click', function() {
			$('#aicc-modal').hide();
		});
	});

    jQuery(document).on('click', '.copy-icon', function() {
        var tempInput = jQuery('<input>');
        jQuery('body').append(tempInput);
        tempInput.val(jQuery(this).data('keyword')).select();
        document.execCommand('copy');
        tempInput.remove();
     
       	Swal.fire({
            icon: 'success',
            text: '"' + jQuery(this).data('keyword') + '" copiada al portapapeles',
            confirmButtonText: 'Aceptar'
        });

    });

	</script>		

	<?php endif; ?>