<?php
require_once __DIR__ . "/_commons.php";

$pdo = pdo_m();
$GF  = get_global_filters();

if (!require_filters_guard($GF)) {
  echo '<div class="warn">Sin filtros aplicados.</div>
        <div class="table-scroll"><table class="simple">
          <thead><tr><th>URL</th><th>Sesiones</th><th>Visitas</th></tr></thead>
          <tbody><tr><td colspan="3"><span class="muted">Aplica un rango y sitio en el filtro global</span></td></tr></tbody>
        </table></div>';
  return;
}

/* ===== RANGO + CONDICIONES ===== */
[$from,$to] = build_range($GF['range'] ?? 'month', $GF['fromUi'] ?? '', $GF['toUi'] ?? '');

/* Limitación por URL de ENTRADA permitida (landing/UTM) — alias ain */
$entryCond = entry_condition_sql();

/* Parámetros base */
$params = [':site'=>$GF['site'], ':from'=>$from, ':to'=>$to] + allowed_url_params();

/* Filtro campaña/fuente global (g_src) — alias v */
list($campWhere, $campParams) = campaign_source_condition($GF, 'v');

/* Si es Directo, excluir UTM en la URL de ENTRADA (coherente con cards/usuarios) */
list($nonCampGuard,) = non_campaign_guard_sql($GF, 'ain', false);

/* Búsqueda avanzada (idvisit, idvisitor HEX, URL de ENTRADA) — alias v/ain */
list($advWhere, $advParams/*,$needAin*/) = build_advanced_where($GF, 'v', 'ain');

/* ===== Modo de tabla: pages (default) o entry ===== */
$mode = (isset($_GET['tp_mode']) && $_GET['tp_mode'] === 'entry') ? 'entry' : 'pages';

if ($mode === 'pages') {
  /* Top PÁGINAS: agrupa por URL de página (a_url.name) */
  $sql = "
    SELECT
      a_url.name AS url,
      COUNT(DISTINCT lva.idvisit) AS sesiones,
      COUNT(*)                    AS visitas
    FROM matomo_log_link_visit_action lva
    JOIN matomo_log_visit v
      ON v.idvisit = lva.idvisit
    LEFT JOIN matomo_log_action ain
      ON ain.idaction = v.visit_entry_idaction_url
    JOIN matomo_log_action a_url
      ON a_url.idaction = lva.idaction_url
     AND a_url.type = 1
    WHERE v.idsite = :site
      AND v.visit_last_action_time BETWEEN :from AND :to
      AND $entryCond
      $campWhere
      $nonCampGuard
      $advWhere
      AND a_url.name NOT LIKE '%elementor-preview%'
      AND a_url.name NOT LIKE '%/checkout%'
    GROUP BY a_url.name
    ORDER BY visitas DESC
    LIMIT 500
  ";
} else {
  /* Top ENTRADAS: agrupa por URL de ENTRADA (ain.name) — siempre verás la landing con UTM completos */
  $sql = "
    SELECT
      ain.name AS url,
      COUNT(DISTINCT v.idvisit) AS sesiones,
      COUNT(*)                  AS visitas
    FROM matomo_log_visit v
    LEFT JOIN matomo_log_action ain
      ON ain.idaction = v.visit_entry_idaction_url
    /* Para contar pageviews de la landing, solo enlazamos LVA a la misma URL de entrada */
    LEFT JOIN matomo_log_link_visit_action lva
      ON lva.idvisit = v.idvisit
     AND lva.idaction_url = v.visit_entry_idaction_url
    WHERE v.idsite = :site
      AND v.visit_last_action_time BETWEEN :from AND :to
      AND $entryCond
      $campWhere
      $nonCampGuard
      $advWhere
    GROUP BY ain.name
    ORDER BY sesiones DESC
    LIMIT 500
  ";
}

$rows = [];
try {
  $st = $pdo->prepare($sql);
  $st->execute($params + $campParams + $advParams);
  $rows = $st->fetchAll() ?: [];
} catch (Throwable $e) {
  echo '<div class="warn">Error al consultar Top '.($mode==='entry'?'entradas':'páginas').'.</div>';
  $rows = [];
}
?>

<style>
  /* Mostrar URL completa sin recortes */
  #tp_table td.tp-url {
    white-space: normal;
    word-break: break-all;
    overflow-wrap: anywhere;
  }
  .tp-mode{display:flex;gap:10px;align-items:center}
  .tp-mode a{padding:6px 10px;border:1px solid #e5e5e5;border-radius:6px;text-decoration:none;color:#111}
  .tp-mode a[aria-current="true"]{background:#f5f5f5;font-weight:600}
</style>

<div class="filters" style="gap:10px;align-items:center;justify-content:space-between">
  <input id="tp_search" type="text" placeholder="Filtrar por URL..." style="padding:6px;min-width:320px;flex:1">
  <div class="tp-mode">
    <?php
      $base = strtok($_SERVER['REQUEST_URI'],'?');
      $qs_pages = http_build_query(array_merge($_GET, ['tp_mode'=>'pages']));
      $qs_entry = http_build_query(array_merge($_GET, ['tp_mode'=>'entry']));
    ?>
    <a href="<?= e($base.'?'.$qs_pages) ?>" aria-current="<?= $mode==='pages'?'true':'false' ?>">Páginas</a>
    <a href="<?= e($base.'?'.$qs_entry) ?>" aria-current="<?= $mode==='entry'?'true':'false' ?>">Entradas (URL de entrada)</a>
  </div>
</div>

<div class="table-scroll">
  <table class="simple" id="tp_table">
    <thead>
      <tr>
        <th><?= $mode==='entry' ? 'URL de entrada (landing)' : 'URL de página' ?></th>
        <th>Sesiones</th>
        <th><?= $mode==='entry' ? 'Pageviews de la landing' : 'Visitas' ?></th>
      </tr>
    </thead>
    <tbody>
      <?php
        if (!$rows){
          echo '<tr><td colspan="3"><span class="muted">Sin datos</span></td></tr>';
        } else {
          foreach ($rows as $r) {
            $url = (string)($r['url'] ?? '');
            echo '<tr>';
            echo '<td class="tp-url" title="'.e($url).'">'.e($url).'</td>';
            echo '<td>'.number_format((int)$r['sesiones']).'</td>';
            echo '<td>'.number_format((int)$r['visitas']).'</td>';
            echo '</tr>';
          }
        }
      ?>
    </tbody>
  </table>
</div>

<script>
(function(){
  const q  = document.getElementById('tp_search');
  if(!q) return;
  const trs= [...document.querySelectorAll('#tp_table tbody tr')];
  function apply(){
    const t=(q.value||'').toLowerCase();
    trs.forEach(tr=>{
      const show = !t || (tr.cells[0].innerText||'').toLowerCase().includes(t);
      tr.style.display = show ? '' : 'none';
    });
  }
  q.addEventListener('input', apply);
})();
</script>
