<script type="text/javascript">
		function aicc_validate_form() {
			var campoBusqueda = document.getElementsByName("s")[0].value.trim();

			if (campoBusqueda === "") {
				alert("Introduce un título para buscar.");
				return false;
			}
			return true;
		}
	</script>

	<style>
		.aicc-options table.widefat th,
		.aicc-options table.widefat td {
			padding-top: 1rem !important;
			padding-bottom: 1rem !important;
		}

		.wrapper-aicc-options .widefat th a {
			display: block;
			overflow: hidden;
			padding: 0;
		}

		th.sorted.asc .sorting-indicator.asc,
		th.sorted.desc .sorting-indicator.desc {
			color: black; 
		}

		.sorting-indicator + .sorting-indicator {
			margin-top: 2px !important;
		}

		.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: #f5f5f5;
		}

		.aicc-options .widefat .icon-tabler-alert-circle {
			position: absolute;
		}

		.aicc-options .widefat .icon-tabler-alert-circle + span {
			margin-left: 24px;
			display: block;
		}

		.filter-main-wrap {
			display: flex;
			justify-content: space-between;
			width: 100%;
			margin-top: 1rem;
		}

		.wrapper-aicc-options input:not([type='number'], [type='submit'], [type='button'], [type='checkbox'], [type='color']) {
			width: 180px;
			padding: 0 8px !important;
			border-radius: 3px !important;
		}

		.wrapper-aicc-options select {
			width: 230px;
			padding: 0px 6px !important;
			border-radius: 3px !important;
			margin-bottom: 8px !important;
		}

		.aicc-options h2 {
	      display: flex;
	      align-items: center;
	      justify-content: space-between;
	    }

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

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

	    .aicc-options h2 input {
		 font-weight: normal !important;
	    }
	</style>

	<h2>
		<div>
		<?php _e('List of posts', 'aicc'); ?> <span class="aicc-tooltip">?<span class="tooltiptext">En esta sección se muestran todos los contenidos posicionados en Search Console, ya sean entradas, páginas, categorías o etiquetas. Puedes ordenar por título, impresiones, clics, posición o fecha de última actualización.</span></span> 				
		</div>

		<form action="<?php echo esc_url(admin_url('admin-post.php')); ?>" method="post">
			<input type="hidden" name="action" value="aicc_export_urls_csv">
			<input type="hidden" name="apply_filter" value="0">
			<input class="button" type="submit" value="Exportar datos">
		</form> 
	</h2>

	<?php

	$transient_data = get_transient('aicc_all_urls_metrics');

	if(empty($transient_data))
	{
		$admin_link = admin_url('admin.php?page=aicc');
		echo '<div class="notice notice-warning"><p>Parece que los datos de Search Console expiraron. Es necesario borrar la caché del plugin para cargar los nuevos datos actualizados. <a target="_blank" href="' . esc_url($admin_link) . '">Ir a la configuración del plugin</a>.</p></div>';
		return;
	}


	$base_url = admin_url('admin.php');

	$parameters = array(
		'page' => 'aicc',
		'tab'  => 'list_settings'
	);

	$clear_url = add_query_arg($parameters, $base_url);

	$search_term = isset($_GET['s']) ? $_GET['s'] : '';
	$position_term = isset($_GET['position']) ? $_GET['position'] : null;
	?>

	<div class="row filter-main-wrap">
		<div class="col-item search-by-date">
			<div class="frm-filter-wrap">
				<form method="GET">
					<input type="hidden" name="page" value="aicc">
					<input type="hidden" name="tab" value="list_settings">
					<select id="position_filter" name="position">
						<option value="all" <?php echo ($position_term === null) ? 'selected' : ''; ?>>Mostrar todos los resultados</option>
						<option value="second_page" <?php echo ($position_term === 'second_page') ? 'selected' : ''; ?>>Mostrar solo segunda página</option>
					</select>
					<input class="button" type="submit" value="Buscar">
				</form>
			</div>
			<?php if ($search_term || $position_term == 'second_page') : ?>
				<a class="button" href="<?php echo esc_url($clear_url); ?>">Limpiar búsquedas</a>
			<?php endif; ?>
		</div>
		<div class="col-item search">
			<div class="clr-filt-wrap">
				<form method="GET" onsubmit="return aicc_validate_form();">
					<input type="hidden" name="page" value="aicc">
					<input type="hidden" name="tab" value="list_settings">
					<input type="text" name="s" value="<?php echo isset($_GET['s']) ? esc_attr($_GET['s']) : ''; ?>" placeholder="Buscar por título">
					<input class="button" type="submit" value="Buscar">
				</form>
			</div>
		</div>
	</div>

	<?php



	foreach ($transient_data as $url => &$data) {
		
		$post_id = url_to_postid($url);

	    if ($post_id) {
	        $post_type = get_post_type($post_id);
	    } else {
	        if (is_category()) {
	            $category = get_category_by_path($url, false);
	            if ($category) {
	                $post_id = $category->term_id;
	                $post_type = 'category';
	            }
	        } elseif (is_tag()) {
	            $tag = get_term_by('slug', get_query_var('tag'), 'post_tag');
	            if ($tag) {
	                $post_id = $tag->term_id;
	                $post_type = 'post_tag';
	            }
	        } else {
	            $post_type = false;
	        }
	    }

	    switch ($post_type) {
	        case 'post':
	        case 'page':
	        case 'product':	        
	            $data['title'] = get_the_title($post_id);
	            $data['modified_date'] = get_the_modified_date('Y-m-d', $post_id);
	            $data['edit_url'] = admin_url("post.php?post={$post_id}&action=edit");
	            break;

	        case 'category':
	            $category = get_category($post_id);
	            $data['title'] = $category->name;
	            $data['modified_date'] = '';
	            $data['edit_url'] = admin_url("edit-tags.php?action=edit&taxonomy=category&tag_ID={$post_id}");
	            break;

	        case 'post_tag':
	            $tag = get_tag($post_id);
	            $data['title'] = $tag->name;
	            $data['modified_date'] = '';
	            $data['edit_url'] = admin_url("edit-tags.php?action=edit&taxonomy=post_tag&tag_ID={$post_id}");
	            break;

	        default:
	            if ($url == home_url('/')) {
	                $data['title'] = get_bloginfo('name');
	                $data['modified_date'] = '';
	            	$data['edit_url'] = '';
	      		} elseif (is_singular()) {
		            $data['title'] = get_the_title($post_id);
		            $data['modified_date'] = get_the_modified_date('Y-m-d', $post_id);
		            $data['edit_url'] = admin_url("post.php?post={$post_id}&action=edit");	      			
	            } else {
       				$data['title'] = "Posible error 404";
       				$data['modified_date'] = '';
	            	$data['edit_url'] = '';
	            }
	            break;
	    }
	}


	$orderby = isset($_GET['orderby']) ? $_GET['orderby'] : 'impressions';
	$order = isset($_GET['order']) && strtolower($_GET['order']) == 'asc' ? 'asc' : 'desc';

	if ($search_term) {
		$transient_data = array_filter($transient_data, function ($data) use ($search_term) {
			return strpos(strtolower($data['title']), strtolower($search_term)) !== false;
		});
	}

	if ($position_term == 'second_page') {
		$transient_data = array_filter($transient_data, function ($data) {
			return $data['average_position'] > 10 && $data['average_position'] <= 20;
		});
	}

	uasort($transient_data, function ($a, $b) use ($orderby, $order) {
		switch ($orderby) {
			case 'clicks':
				$result = $a['clicks'] <=> $b['clicks'];
				break;
			case 'ctr':
				$ctr_a = ($a['impressions'] != 0) ? $a['clicks'] / $a['impressions'] : 0;
				$ctr_b = ($b['impressions'] != 0) ? $b['clicks'] / $b['impressions'] : 0;
				$result = $ctr_a <=> $ctr_b;
				break;
			case 'position':
				$result = $a['average_position'] <=> $b['average_position'];
				break;
			case 'title':
				$result = strcmp($a['title'], $b['title']);
				break;
			case 'modified_date':
				$result = strcmp($a['modified_date'], $b['modified_date']);
				break;
			case 'impressions':
			default:
				$result = $a['impressions'] <=> $b['impressions'];
				break;
		}

		return $order == 'desc' ? -$result : $result;
	});

	$click_threshold = 25;
	$impression_threshold = 500;
	$position_threshold = 10;
	$low_ctr_threshold = 0.05;

	$total_items = count($transient_data);
	$items_per_page = 10;
	$current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
	$offset = ($current_page - 1) * $items_per_page;

	$current_data = array_slice($transient_data, $offset, $items_per_page, true);

	$thin_content_urls = [];

	$classTitle = ($orderby == 'title') ? 'sorted ' . $order : '';
	$classImpressions = ($orderby == 'impressions' || !isset($_GET['orderby'])) ? 'sorted ' . $order : '';
	$classClicks = ($orderby == 'clicks') ? 'sorted ' . $order : '';
	$classCtr = ($orderby == 'ctr') ? 'sorted ' . $order : '';
	$classPosition = ($orderby == 'position') ? 'sorted ' . $order : '';
	$classModifiedDate = ($orderby == 'modified_date') ? 'sorted ' . $order : '';

	echo '<div style="margin-bottom:-.75rem;"><p style="text-align:right;font-size:13px;margin-bottom:0;">'.$total_items.' elementos</p></div>';
	echo '<table class="widefat">';
	echo "<thead>";
	echo "<tr>";

	echo '<th  class="' . $classTitle . '" style="text-align:left; width:50%"><a style="display:inline-flex;" href="' . $this->get_order_link('title', $orderby, $order, $search_term, $position_term) . '">Título<span class="sorting-indicators"><span class="sorting-indicator asc" aria-hidden="true"></span><span class="sorting-indicator desc" aria-hidden="true"></span></span></a></th>';

	echo '<th class="' . $classImpressions . '" style="text-align:center; width:10%"><a style="display:inline-flex;" href="' . $this->get_order_link('impressions', $orderby, $order, $search_term, $position_term) . '">Impresiones<span class="sorting-indicators"><span class="sorting-indicator asc" aria-hidden="true"></span><span class="sorting-indicator desc" aria-hidden="true"></span></span></a></th>';

	echo '<th class="' . $classClicks . '" style="text-align:center; width:10%"><a style="display:inline-flex;" href="' . $this->get_order_link('clicks', $orderby, $order, $search_term, $position_term) . '">Clics<span class="sorting-indicators"><span class="sorting-indicator asc" aria-hidden="true"></span><span class="sorting-indicator desc" aria-hidden="true"></span></span></a></th>';

	echo '<th  class="' . $classPosition . '"  style="text-align:center;width:10%"><a style="display:inline-flex;" href="' . $this->get_order_link('position', $orderby, $order, $search_term, $position_term) . '" title="Posición promedio">Posición<span class="sorting-indicators"><span class="sorting-indicator asc" aria-hidden="true"></span><span class="sorting-indicator desc" aria-hidden="true"></span></span></a></th>';

	echo '<th class="' . $classModifiedDate . '" style="text-align:center; width:10%"><a style="display:inline-flex;" href="' . $this->get_order_link('modified_date', $orderby, $order, $search_term, $position_term) . '">Actualizado<span class="sorting-indicators"><span class="sorting-indicator asc" aria-hidden="true"></span><span class="sorting-indicator desc" aria-hidden="true"></span></span></a></th>';

	echo "</tr>";
	echo "</thead>";
	echo "<tbody>";

	foreach ($current_data as $url => $metrics) {
		$average_position = 0;

		$average_position = $metrics['average_position'];

		$ctr = ($metrics['impressions'] != 0) ? $metrics['clicks'] / $metrics['impressions'] : 0;

		$ctr_ed = number_format($ctr * 100, 1) . '%';

		$edit_url = $metrics['edit_url'];

		$modified_date = new DateTime($metrics['modified_date']);

		$current_date = new DateTime(date('Y-m-d'));

		$interval = $modified_date->diff($current_date);

		$last_modified_date = "Hace " . $interval->days . " días";

		echo "<tr>";
		
		echo "<td style=\"text-align:left;\">";
		
		if (strpos($metrics['title'], 'error 404') === false) { 
			echo "<a href='{$edit_url}' target='_blank' rel='noopener'><strong>{$metrics['title']}</strong></a>";
			echo '<div class="row-actions">';
			echo "<span class='edit'><a href='{$edit_url}' target='_blank' rel='noopener'>Editar</a> | </span>";
			echo "<span class='view'><a href='{$url}' target='_blank' rel='noopener'>Vista previa</a>";
			echo "</div>";
		} else {
			
			echo "<strong>{$metrics['title']}</strong>";
			echo '<div class="row-actions">';
			echo "<span class='view'><a href='{$url}' target='_blank' rel='noopener'>Vista previa</a>";
			echo "</div>";
			
		}
		
		echo "</td>";
		
		echo "<td style=\"text-align:center;\">{$metrics['impressions']}</td>";
		echo "<td style=\"text-align:center;\">{$metrics['clicks']}</td>";
		echo "<td style=\"text-align:center;\">{$average_position}</td>";
		echo "<td style=\"text-align:center;\"><span style=\"cursor:help;\" title=\"{$metrics['modified_date']}\">{$last_modified_date}</span></td>";
		echo "</tr>";
	}

	echo "</tbody>";
	echo "</table>";

	$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>';

	?>