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

/* Fuerza cabecera UTF-8 (evita caracteres raros) */
if (!headers_sent()) {
  header('Content-Type: text/html; charset=UTF-8');
}

$pdo = pdo_m();

/* --- helpers de presentación (solo UI) --- */
function pretty_campaign_label($raw){
  $n = trim((string)$raw);
  if ($n === '') return '(sin nombre)';
  if (preg_match('/\{[^}]+\}/', $n)) {
    return $n.' (placeholder)'; // ASCII only
  }
  return preg_replace('/\s+/',' ', $n);
}

/* ====== leer filtros actuales ====== */
$sites = fetch_sites();
$GF    = get_global_filters(); // canónico
$g_site  = $GF['site'];
$g_range = $GF['range'] ?? 'month';
$g_from  = $GF['fromUi'] ?? '';
$g_to    = $GF['toUi']   ?? '';

/* Rango de fechas según global */
[$from,$to] = build_range($g_range, $g_from, $g_to);

/* Construir selector unificado (campañas y otras fuentes) limitado a páginas permitidas */
$selectOpts = [];          // value => label
$selectOpts['all'] = 'Todas las fuentes';

if ($g_site && $from && $to) {
  $entryCond = entry_condition_sql(); // usa alias ain
  $params    = [':site'=>$g_site, ':from'=>$from, ':to'=>$to] + allowed_url_params();

  // Campañas (referer_type = 6) por nombre
  try{
    $st = $pdo->prepare("
      SELECT v.referer_name AS name, COUNT(*) AS c
      FROM matomo_log_visit v
      LEFT JOIN matomo_log_action ain ON ain.idaction = v.visit_entry_idaction_url
      WHERE v.idsite = :site
        AND v.visit_last_action_time BETWEEN :from AND :to
        AND $entryCond
        AND v.referer_type = 6
        AND v.referer_name IS NOT NULL AND v.referer_name <> ''
      GROUP BY v.referer_name
      ORDER BY c DESC, name ASC
    ");
    $st->execute($params);
    $rows = $st->fetchAll() ?: [];
    if ($rows) {
      $selectOpts['camp:any'] = 'Solo campañas (todas)';
      foreach($rows as $r){
        $raw = (string)$r['name'];
        $disp = pretty_campaign_label($raw);   // solo cambia la etiqueta
        $selectOpts['camp:'.$raw] = "Campaña: {$disp} ({$r['c']})"; // el value conserva el nombre crudo
      }
    }
  }catch(Throwable $e){ /* no romper UI */ }

  // Otras fuentes: Directo(1), Búsqueda(2), Referencias(3)
  // Directo excluye UTM en la URL de ENTRADA
  try{
    $st = $pdo->prepare("
      SELECT v.referer_type, COALESCE(v.referer_name,'') AS name, COUNT(*) AS c
      FROM matomo_log_visit v
      LEFT JOIN matomo_log_action ain ON ain.idaction = v.visit_entry_idaction_url
      WHERE v.idsite = :site
        AND v.visit_last_action_time BETWEEN :from AND :to
        AND $entryCond
        AND (v.referer_type IN (1,2,3))
        AND (v.referer_type <> 1 OR ain.name NOT LIKE '%utm_%')
      GROUP BY v.referer_type, v.referer_name
      ORDER BY v.referer_type ASC, c DESC, name ASC
    ");
    $st->execute($params);
    $rows = $st->fetchAll() ?: [];
    $hasDir=false;
    foreach($rows as $r){
      $t = (int)$r['referer_type']; $n = trim($r['name']); $c = (int)$r['c'];
      if ($t===1){ // Directo (sin UTM)
        if(!$hasDir){ $selectOpts['direct'] = "Directo ({$c})"; $hasDir=true; }
      }elseif($t===2){ // Búsqueda
        $lbl = $n ? "Búsqueda: {$n} ({$c})" : "Búsqueda ({$c})";
        $selectOpts['search:'.$n] = $lbl;
      }elseif($t===3){ // Referencia
        $lbl = $n ? "Referencia: {$n} ({$c})" : "Referencia ({$c})";
        $selectOpts['ref:'.$n] = $lbl;
      }
    }
  }catch(Throwable $e){ /* no romper UI */ }
}

/* Valor elegido en el select unificado */
$g_src = $GF['src'] ?? 'all';

/* Filtros avanzados actuales (solo para vistas que los apliquen explícitamente) */
$g_idvisit   = $GF['q_idvisit']   ?? '';
$g_idvisitor = $GF['q_idvisitor'] ?? '';
$g_url       = $GF['q_url']       ?? '';

/* ——— UI ——— */
?>
<form class="filters card" method="get" accept-charset="UTF-8" style="gap:16px;align-items:flex-end">
  <div>
    <label><b>Sitio (global)</b></label><br>
    <select name="g_site" required style="min-width:360px;padding:8px">
      <option value="">— Selecciona un sitio —</option>
      <?php foreach($sites as $s): $id=(int)$s['idsite']; ?>
        <option value="<?= $id ?>" <?= ($g_site===$id)?'selected':'' ?>>
          <?= e($s['idsite'].' - '.$s['name']) ?>
        </option>
      <?php endforeach; ?>
    </select>
  </div>

  <div>
    <label><b>Periodo (global)</b></label><br>
    <select name="g_range" style="padding:8px">
      <option value="week"  <?= $g_range==='week'?'selected':''  ?>>Última semana</option>
      <option value="month" <?= $g_range==='month'?'selected':'' ?>>Mes a hoy</option>
      <option value="year"  <?= $g_range==='year'?'selected':''  ?>>Año a hoy</option>
      <option value="custom"<?= $g_range==='custom'?'selected':''?>>Personalizado</option>
    </select>
  </div>

  <div>
    <label>&nbsp;</label><br>
    <input type="date" name="g_from" value="<?= e($g_from) ?>" style="padding:8px">
  </div>
  <div>
    <label>&nbsp;</label><br>
    <input type="date" name="g_to" value="<?= e($g_to) ?>" style="padding:8px">
  </div>

  <div style="min-width:420px;flex:1">
    <label><b>Campaña / Fuente (global)</b></label><br>
    <select name="g_src" style="width:100%;padding:8px">
      <?php foreach($selectOpts as $val=>$lbl): ?>
        <option value="<?= e($val) ?>" <?= ($g_src===$val)?'selected':'' ?>><?= e($lbl) ?></option>
      <?php endforeach; ?>
    </select>
  </div>

  <div style="margin-left:auto">
    <button style="padding:10px 16px">Aplicar a todas</button>
  </div>

  <div style="flex-basis:100%"></div>

  <details style="width:100%">
    <summary><b>Busqueda avanzada (opcional)</b> <span class="muted">— por sesión, usuario o URL de entrada</span></summary>
    <div class="adv-grid">
      <div>
        <label><b>ID de sesión (idvisit)</b></label><br>
        <input type="text" name="g_idvisit" value="<?= e((string)$g_idvisit) ?>" placeholder="Ej: 4741" style="padding:8px;min-width:200px">
      </div>
      <div>
        <label><b>ID de usuario (idvisitor HEX)</b></label><br>
        <input type="text" name="g_idvisitor" value="<?= e((string)$g_idvisitor) ?>" placeholder="Ej: 306313250913161B o 0x3063..." style="padding:8px;min-width:260px">
      </div>
      <div style="flex:1">
        <label><b>URL de entrada contiene</b></label><br>
        <input type="text" name="g_url" value="<?= e((string)$g_url) ?>" placeholder="fragmento de URL (entry)" style="padding:8px;width:100%">
      </div>
    </div>
    <div class="helper-note">Nota: la búsqueda avanzada NO afecta tarjetas ni otras tablas; solo vistas que la activen.</div>
  </details>
</form>
