<?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>';
  return;
}

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

/* ===== Descubrir columna de nombre de evento ===== */
function column_exists(PDO $pdo, string $table, string $column): bool {
  try { $st = $pdo->prepare("SHOW COLUMNS FROM {$table} LIKE :c"); $st->execute([':c'=>$column]); return (bool)$st->fetch();
  } catch (Throwable $e) { return false; }
}
$tblLVA       = 'matomo_log_link_visit_action';
$colEventName = column_exists($pdo, $tblLVA, 'idaction_event_name') ? 'idaction_event_name' : 'idaction_name';

/* ===== SQL comunes de filtro global ===== */
list($campWhere, $campParams)               = campaign_source_condition($GF, 'v');
list($advWhere, $advParams, $needAinJoin)   = build_advanced_where($GF, 'v', 'ain');
$ainJoin = "LEFT JOIN matomo_log_action ain ON ain.idaction = v.visit_entry_idaction_url"; // siempre para evitar avisos
list($noUtmWhere, $noUtmParams)             = non_campaign_guard_sql($GF, 'ain'); // Directo => sin UTM

/* ========= CONDICIÓN: excluir “sin categoría/acción” salvo “Verificar …” ========= */
$validEventGuard = "
  AND (
        LOWER(nam.name) LIKE 'verificar%%'
      OR (COALESCE(cat.name,'') <> '' AND COALESCE(act.name,'') <> '')
  )
";

/* ===================== 1) Filtros (selects de categoría y acción) ===================== */
$cats=[]; $acts=[];
try{
  $sqlF = "
    SELECT DISTINCT
      CASE
        WHEN nam.name IS NOT NULL AND LOWER(nam.name) LIKE 'verificar%%' THEN 'UI'
        ELSE COALESCE(cat.name,'')
      END AS c,
      COALESCE(act.name,'') AS a
    FROM matomo_log_link_visit_action lva
    JOIN matomo_log_visit v ON v.idvisit = lva.idvisit
    $ainJoin
    LEFT JOIN matomo_log_action cat ON cat.idaction = lva.idaction_event_category
    LEFT JOIN matomo_log_action act ON act.idaction = lva.idaction_event_action
    LEFT JOIN matomo_log_action nam ON nam.idaction = lva.{$colEventName}
    WHERE v.idsite = :site
      AND lva.server_time BETWEEN :from AND :to
      AND (
           lva.idaction_event_category IS NOT NULL
        OR lva.idaction_event_action  IS NOT NULL
        OR lva.{$colEventName}        IS NOT NULL
      )
      $campWhere
      $advWhere
      $noUtmWhere
      $validEventGuard
    ORDER BY c, a
  ";
  $st = $pdo->prepare($sqlF);
  $st->execute([':site'=>$GF['site'], ':from'=>$from, ':to'=>$to] + $campParams + $advParams + $noUtmParams);
  foreach($st->fetchAll() as $r){
    if ($r['c'] !== '') $cats[$r['c']] = true;
    if ($r['a'] !== '') $acts[$r['a']] = true;
  }
}catch(Throwable $e){ /* silencioso */ }

/* ===================== 2) Agregado por Categoría/Acción/Nombre con IDs HEX ===================== */
$selCat = $_GET['ev_cat'] ?? '';
$selAct = $_GET['ev_act'] ?? '';
$aggRows = [];
try{
  $sqlAgg = "
    SELECT
      CASE
        WHEN nam.name IS NOT NULL AND LOWER(nam.name) LIKE 'verificar%%' THEN 'UI'
        ELSE COALESCE(cat.name,'(sin categoría)')
      END AS category_display,
      COALESCE(act.name,'(sin acción)') AS action,
      CASE
        WHEN nam.name IS NULL THEN '(sin nombre)'
        WHEN LOWER(nam.name) LIKE 'verificar%%' THEN 'Verificar'
        ELSE nam.name
      END AS event_name,
      COUNT(*)                          AS clicks,
      COUNT(DISTINCT v.idvisit)         AS visits,
      COUNT(DISTINCT HEX(v.idvisitor))  AS users,
      GROUP_CONCAT(DISTINCT HEX(v.idvisitor) ORDER BY HEX(v.idvisitor) SEPARATOR ',') AS hex_ids
    FROM matomo_log_link_visit_action lva
    JOIN matomo_log_visit v ON v.idvisit = lva.idvisit
    $ainJoin
    LEFT JOIN matomo_log_action cat ON cat.idaction = lva.idaction_event_category
    LEFT JOIN matomo_log_action act ON act.idaction = lva.idaction_event_action
    LEFT JOIN matomo_log_action nam ON nam.idaction = lva.{$colEventName}
    WHERE v.idsite = :site
      AND lva.server_time BETWEEN :from AND :to
      AND (
           lva.idaction_event_category IS NOT NULL
        OR lva.idaction_event_action  IS NOT NULL
        OR lva.{$colEventName}        IS NOT NULL
      )
      $campWhere
      $advWhere
      $noUtmWhere
      $validEventGuard
  ";
  $paramsAgg = [':site'=>$GF['site'], ':from'=>$from, ':to'=>$to] + $campParams + $advParams + $noUtmParams;

  if($selCat !== ''){
    $sqlAgg .= " AND (
      (nam.name IS NOT NULL AND LOWER(nam.name) LIKE 'verificar%%' AND 'UI' = :__catF)
      OR (nam.name IS NULL OR LOWER(nam.name) NOT LIKE 'verificar%%') AND COALESCE(cat.name,'(sin categoría)') = :__catF
    )";
    $paramsAgg[':__catF'] = $selCat;
  }
  if($selAct !== ''){
    $sqlAgg .= " AND COALESCE(act.name,'(sin acción)') = :__actF ";
    $paramsAgg[':__actF'] = $selAct;
  }

  $sqlAgg .= " GROUP BY category_display, action, event_name
               ORDER BY clicks DESC, users DESC, event_name ASC
               LIMIT 500";
  $stAgg = $pdo->prepare($sqlAgg);
  $stAgg->execute($paramsAgg);
  $aggRows = $stAgg->fetchAll() ?: [];
}catch(Throwable $e){ /* silencioso */ }

/* ===================== UI (Agregado) ===================== */
?>
<div class="filters" style="gap:8px;align-items:center">
  <label><b>Categoría:</b></label>
  <select id="ev_cat" onchange="location.search=updateQS('ev_cat',this.value)">
    <option value="">Todas</option>
    <?php foreach(array_keys($cats) as $c): ?>
      <option value="<?= e($c) ?>" <?= ($selCat===$c)?'selected':'' ?>><?= e($c) ?></option>
    <?php endforeach; ?>
  </select>

  <label><b>Acción:</b></label>
  <select id="ev_act" onchange="location.search=updateQS('ev_act',this.value)">
    <option value="">Todas</option>
    <?php foreach(array_keys($acts) as $a): ?>
      <option value="<?= e($a) ?>" <?= ($selAct===$a)?'selected':'' ?>><?= e($a) ?></option>
    <?php endforeach; ?>
  </select>

  <input type="text" id="ev_search" placeholder="Buscar evento..." style="margin-left:auto;padding:6px;min-width:260px">
</div>

<div class="table-scroll">
  <table class="simple" id="ev_table">
    <thead>
      <tr>
        <th>Categoría</th>
        <th>Acción</th>
        <th>Nombre</th>
        <th>Clicks</th>
        <th>Visitas</th>
        <th>Usuarios</th>
        <th>Usuarios (HEX)</th>
      </tr>
    </thead>
    <tbody>
      <?php if(!$aggRows){ ?>
        <tr><td colspan="7"><span class="muted">Sin datos</span></td></tr>
      <?php } else {
        foreach($aggRows as $r){
          $idsRaw = trim((string)($r['hex_ids'] ?? ''));
          $idList = $idsRaw !== '' ? explode(',', $idsRaw) : [];
          echo '<tr>';
          echo '<td>'.e($r['category_display']).'</td>';
          echo '<td>'.e($r['action']).'</td>';
          echo '<td>'.e($r['event_name']).'</td>';
          echo '<td>'.(int)$r['clicks'].'</td>';
          echo '<td>'.(int)$r['visits'].'</td>';
          echo '<td>'.(int)$r['users'].'</td>';
          echo '<td>';
          if ($idList){
            $count = count($idList);
            echo '<details><summary>▶ '.(int)$count.' IDs</summary>';
            echo '<div style="margin-top:6px">';
            foreach($idList as $hx){
              echo '<code style="font-family:ui-monospace,monospace;margin-right:8px;display:inline-block">'.e($hx).'</code>';
            }
            echo '</div></details>';
          }else{
            echo '<span class="muted">—</span>';
          }
          echo '</td>';
          echo '</tr>';
        }
      } ?>
    </tbody>
  </table>
</div>

<script>
function updateQS(k,v){
  const u = new URL(location.href);
  if(v===undefined || v==='') u.searchParams.delete(k); else u.searchParams.set(k,v);
  return u.search;
}
(function(){
  const q = document.getElementById('ev_search');
  const trs = Array.from(document.querySelectorAll('#ev_table tbody tr'));
  function apply(){
    const t = (q && q.value ? q.value.toLowerCase() : '');
    trs.forEach(tr=>{
      const txt = tr.innerText.toLowerCase();
      tr.style.display = (!t || txt.includes(t)) ? '' : 'none';
    });
  }
  if(q) q.addEventListener('input', apply);
})();
</script>

<?php
/* ===================== 3) Historial completo con Usuario (HEX) ===================== */
$hist = [];
try{
  $sqlH = "
    SELECT
      DATE_FORMAT(lva.server_time,'%Y-%m-%d %H:%i:%s') AS at,
      HEX(v.idvisitor)                                AS visitor_hex,
      CASE
        WHEN nam.name IS NOT NULL AND LOWER(nam.name) LIKE 'verificar%%' THEN 'UI'
        ELSE COALESCE(cat.name,'(sin categoría)')
      END AS category,
      COALESCE(act.name,'(sin acción)')               AS action,
      COALESCE(nam.name,'(sin nombre)')               AS event_name
    FROM matomo_log_link_visit_action lva
    JOIN matomo_log_visit v ON v.idvisit = lva.idvisit
    $ainJoin
    LEFT JOIN matomo_log_action cat ON cat.idaction = lva.idaction_event_category
    LEFT JOIN matomo_log_action act ON act.idaction = lva.idaction_event_action
    LEFT JOIN matomo_log_action nam ON nam.idaction = lva.{$colEventName}
    WHERE v.idsite = :site
      AND lva.server_time BETWEEN :from AND :to
      AND (
           lva.idaction_event_category IS NOT NULL
        OR lva.idaction_event_action  IS NOT NULL
        OR lva.{$colEventName}        IS NOT NULL
      )
      $campWhere
      $advWhere
      $noUtmWhere
      $validEventGuard
    ORDER BY lva.server_time DESC
  ";
  $stH = $pdo->prepare($sqlH);
  $stH->execute([':site'=>$GF['site'], ':from'=>$from, ':to'=>$to] + $campParams + $advParams + $noUtmParams);
  $hist = $stH->fetchAll() ?: [];
}catch(Throwable $e){ /* silencioso */ }
?>

<div class="muted" style="margin-top:10px">Historial de eventos (todos):</div>

<div class="filters" style="gap:8px">
  <input type="text" id="hist_search" placeholder="Buscar en historial…" style="padding:6px;min-width:320px">
</div>

<div class="table-scroll">
  <table class="simple" id="hist_table">
    <thead>
      <tr>
        <th>Fecha/Hora</th>
        <th>Usuario (HEX)</th>
        <th>Categoría</th>
        <th>Acción</th>
        <th>Nombre</th>
      </tr>
    </thead>
    <tbody>
      <?php if(!$hist){ ?>
        <tr><td colspan="5"><span class="muted">Sin datos</span></td></tr>
      <?php } else {
        foreach($hist as $r){
          echo '<tr>';
          echo '<td>'.e($r['at']).'</td>';
          echo '<td style="font-family:ui-monospace,monospace">'.e($r['visitor_hex']).'</td>';
          echo '<td>'.e($r['category']).'</td>';
          echo '<td>'.e($r['action']).'</td>';
          echo '<td>'.e($r['event_name']).'</td>';
          echo '</tr>';
        }
      } ?>
    </tbody>
  </table>
</div>

<script>
(function(){
  const q   = document.getElementById('hist_search');
  const trs = Array.from(document.querySelectorAll('#hist_table tbody tr'));
  function apply(){
    const t = (q && q.value ? q.value.toLowerCase() : '');
    trs.forEach(tr=>{
      const txt = tr.innerText.toLowerCase();
      tr.style.display = (!t || txt.includes(t)) ? '' : 'none';
    });
  }
  if(q) q.addEventListener('input', apply);
})();
</script>
<?php if (function_exists('client_pager_js')) { client_pager_js('hist_table', 50); } ?>
