<script type="text/javascript">

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

        var nonce = '<?php echo wp_create_nonce('aicc_canibal_nonce'); ?>'; // Crear el nonce en PHP y pasarlo a JavaScript

        $('.mark-resolved a').on('click', function(e) {  // Seleccionamos directamente el enlace <a>
            e.preventDefault();

            var keyword = $(this).data('keyword');  // Aquí $(this) se refiere al propio enlace <a>

            $.ajax({
                url: ajaxurl,  
                type: 'POST',
                data: {
                    action: 'aicc_mark_canibal_as_resolved',
                    keyword: keyword,
                    nonce: nonce
                },
                success: function(response) {
                    if(response.success) {
                        // Esta línea selecciona el tr con el data-keyword que coincide y lo desvanece/remueve.
                        $("tr[data-keyword='" + keyword + "']").fadeOut('slow', function() { 
                            $(this).remove(); 
                        });
                    } else {
                        alert(response.data); 
                    }
                }
            });
        });
    });

    function aicc_validate_form() {
      var campoBusqueda = document.getElementsByName("s")[0].value.trim();

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

  <style>

    .filter-main-wrap input[type="submit"] {

      }

    .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;
    }
  
    .widefat tbody tr td.with-border {
    border-bottom: 1px dashed #ddd;
    }

    .aicc-options table.widefat td[rowspan] {
    vertical-align: middle;
    }

    .aicc-options table.widefat tr.rowspanned:last-of-type {
    border-bottom: 1px solid #e2e4e7;
    }

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

    .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;
        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('Cannibalizations', 'aicc'); ?> <span class="aicc-tooltip">?<span class="tooltiptext">Una canibalización SEO se produce cuando dos o más URLS se están posicionando para la misma palabra clave. Como consecuencia, ninguna de esas URLS mejora su posicionamiento ya que Google no sabe cual posicionar para esa palabra clave.</span></span>        
    </div>

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

  <?php

  $urls_by_keyword = get_transient("aicc_urls_by_keywords");

  $resolved_keywords_set = array_flip(get_option('aicc_canibal_resolved_keywords', array()));

  $cannibalizing_keywords = [];

  foreach ($urls_by_keyword as $keyword => $data) {
    if (count($data) > 1) {

      // Si está marcada como resuelta, la descartamos
      if (isset($resolved_keywords_set[$keyword])) {
        continue;
      }

      $percentage_threshold = 20; // Define el umbral del porcentaje

      // Obtenemos todas las impresiones
      $impressions = [];
      foreach ($data as $url_data) {
        if (isset($url_data["impressions"])) {
          $impressions[] = $url_data["impressions"];
        }
      }

      if (empty($impressions)) continue;

      $max_impressions = max($impressions);
      $threshold_impressions = ($percentage_threshold / 100) * $max_impressions;

      $cannibalizing_data = [];

      // Ahora comparamos cada conjunto de impresiones con el umbral
      foreach ($data as $url_data) {
        $impression = $url_data["impressions"];

        // Si la impresión es mayor o igual al umbral, agregamos a un array temporal
        if ($impression >= $threshold_impressions) {
          $cannibalizing_data[] = $url_data;
        }
      }

      // Si detectamos dos o más URLs en el array temporal, las transferimos al resultado
      if (count($cannibalizing_data) >= 2) {
        $cannibalizing_keywords[$keyword] = $cannibalizing_data;
      }
    }
  }

  if (empty($cannibalizing_keywords)) {
    echo '<div class="notice notice-warning"><p>No se detectaron canibalizaciones.</p></div>';
    return;
  }

  $search_term = isset($_GET['s']) ? sanitize_text_field($_GET['s']) : '';
  $position_term = isset($_GET['position']) ? sanitize_text_field($_GET['position']) : null;
  
  $base_url = admin_url('admin.php');

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

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

  ?>

  <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="canibal_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="canibal_settings">
            <input type="text" name="s" value="<?php echo isset($_GET['s']) ? esc_attr($_GET['s']) : ''; ?>" placeholder="Buscar por palabra clave">
            <input class="button" type="submit" value="Buscar">
          </form>
        </div>
      </div>
    </div>
  <?php
  
  // Calcular suma de impresiones para cada palabra clave y ordenar por eso
  uasort($cannibalizing_keywords, function($a, $b) {
    $sum_a = array_sum(array_map(function($item) {
      return $item["impressions"];
    }, $a));

    $sum_b = array_sum(array_map(function($item) {
      return $item["impressions"];
    }, $b));

    return $sum_b - $sum_a; // Orden descendente
  });


  // Si la búsqueda por posición es 'second_page', filtrar las canibalizaciones por posición.
  if ($position_term === 'second_page') {
    $cannibalizing_keywords = array_filter($cannibalizing_keywords, function ($data) {
      foreach ($data as $url_data) {
        if (number_format($url_data["position"], 1) > 10 && number_format($url_data["position"], 1) <= 20) {
          return true;
        }
      }
      return false;
    });
  }

  // Si hay término de búsqueda, filtrar las canibalizaciones por palabra clave.
  if (!empty($search_term)) {
    $cannibalizing_keywords = array_filter($cannibalizing_keywords, function ($keyword) use ($search_term) {
      return strpos(strtolower($keyword), strtolower($search_term)) !== false;
    }, ARRAY_FILTER_USE_KEY);
  }


  // Variables de paginación
  $items_per_page = 10;
  $current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
  $total_items = count($cannibalizing_keywords);
  $offset = ($current_page - 1) * $items_per_page;

  // Tomar solo los keywords de la página actual
  $current_keywords = array_slice($cannibalizing_keywords, $offset, $items_per_page, true);

  echo '<div style="margin-bottom:-.75rem;"><p style="text-align:right;font-size:13px;margin-bottom:0;">'.$total_items.' elementos</p></div>';
  // Mostramos la tabla
  echo '<table class="widefat">';
  echo "<thead>";
  echo "<tr>";
  echo '<th style="text-align:left;width:30%;">Palabra clave</th>';
  echo '<th style="text-align:left;width:30%;">Está posicionando en</th>';
  echo '<th style="text-align:center;width:10%;">Impresiones</th>';
  echo '<th style="text-align:center;width:10%;">Clics</th>';
  echo '<th style="text-align:center;width:10%;">Posición</th>';
  echo "</tr>";
  echo "</thead>";

  $background_toggle = false; // Flag para alternar el fondo
  $count = 0; // Inicializa el contador

  // Rellenamos la tabla con los datos de canibalización
  foreach ($current_keywords as $keyword => $data) {
    $dataCount = 0; // Contador de datos para cada palabra clave

    $rowspan = count($data); // Usamos rowspan para que la palabra clave abarque todas las URLs relacionadas
    $first = true; // Flag para controlar el rowspan solo en la primera fila

    $background_color = $background_toggle ? '#f5f5f5' : 'white';

    foreach ($data as $url_data) {
      
      $dataCount++; // Incrementamos el contador de datos

      $metrics = $url_data;

      echo "<tr class='data-row' data-keyword='{$keyword}' style=\"background-color: {$background_color}\">"; 

      if ($first) {
        echo "<td rowspan=\"$rowspan\" data-keyword='{$keyword}'>";
        echo "<strong>{$keyword}</strong>";
        echo '<div class="row-actions">';
        echo "<span class='trash mark-resolved'><a data-keyword='{$keyword}' style='cursor:pointer;' rel='noopener'>Marcar como resuelta</a>";
        echo "</div>"; 
        echo "</td>";
        $first = false;
      }

      $position = number_format($metrics["position"], 1);

      $url = $url_data["url"];

      $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':
              $title = get_the_title($post_id);
              $edit_url = admin_url("post.php?post={$post_id}&action=edit");
              break;

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

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

          default:
              if ($url == home_url('/')) {
                  $title = get_bloginfo('name');
              } else {
                  $title = "Posible error 404";
              }
              $edit_url = ''; 
              break;
      }

      $borderClass = ($dataCount < $rowspan) ? "with-border" : "";

      echo "<td class='{$borderClass}'>";


      if (strpos($title, 'error 404') === false) { 

      echo "<a href='{$edit_url}' target='_blank' rel='noopener'><strong>{$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></span>";
      echo "</div>";

      } else {
        
      echo "<strong>{$title}</strong>";
      echo '<div class="row-actions">';
      echo "<span class='view'><a href='{$url}' target='_blank' rel='noopener'>Vista previa</a></span>";
      echo "</div>";
        
      }

      echo "</td>";

      echo "<td style=\"text-align:center;\" class='{$borderClass}'>{$metrics["impressions"]}</td>";
      echo "<td style=\"text-align:center;\" class='{$borderClass}'>{$metrics["clicks"]}</td>";
      echo "<td style=\"text-align:center;\" class='{$borderClass}'>{$position}</td>";
    }

    $background_toggle = !$background_toggle;
  }

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

  // Mostrar paginación
  $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>';
  ?>