<?php
// visits_line.php — Serie de visitas por día (respeta filtros globales + búsqueda avanzada)
// Guardar como UTF-8 (sin BOM). No toca headers.

require_once __DIR__ . "/_commons.php";

$pdo = pdo_m();
$GF  = get_global_filters();
if(!require_filters_guard($GF)) {
  // Placeholder sin romper layout del contenedor padre
  echo '<div class="warn">Sin filtros aplicados. Selecciona sitio y periodo.</div>';
  echo '<div style="height:260px;display:flex;align-items:center;justify-content:center;border:1px dashed #e5e5e5;border-radius:6px"><span class="muted">Sin datos</span></div>';
  return;
}

$siteId = (int)($GF['site'] ?? 0);
$range  = (string)($GF['range'] ?? 'month');
$fromUi = (string)($GF['fromUi'] ?? '');
$toUi   = (string)($GF['toUi']   ?? '');

[$from, $to] = build_range($range, $fromUi, $toUi);

$rows = [];
if ($siteId && $from && $to) {
  $entryCond = entry_condition_sql();                              // limitación por URL de entrada/UTM permitidas
  $params    = [':site'=>$siteId, ':from'=>$from, ':to'=>$to] + allowed_url_params();

  // Fuente/campaña global (g_src) → WHERE adicional
  list($campWhere, $campParams) = campaign_source_condition($GF, 'v');

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

  try {
    $sql = "
      SELECT DATE(v.visit_last_action_time) AS d, COUNT(*) AS visits
      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
        $campWhere
        $advWhere
      GROUP BY DATE(v.visit_last_action_time)
      ORDER BY d ASC
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params + $campParams + $advParams);
    $rows = $stmt->fetchAll() ?: [];
  } catch (Throwable $e) {
    $rows = [];
  }
}

/** Serie continua día a día (rellena huecos con 0) */
$series = [];
if ($from && $to) {
  $map = [];
  foreach ($rows as $r) $map[$r['d']] = (int)$r['visits'];

  $start = new DateTime(substr($from, 0, 10));
  $end   = new DateTime(substr($to,   0, 10));
  for ($d = (clone $start); $d <= $end; $d->modify('+1 day')) {
    $k = $d->format('Y-m-d');
    $series[] = [$k, $map[$k] ?? 0];
  }
}
?>

<?php if (!$series) { ?>
  <div class="warn">Sin datos para el rango y filtros elegidos.</div>
  <div style="height:260px;display:flex;align-items:center;justify-content:center;border:1px dashed #e5e5e5;border-radius:6px">
    <span class="muted">Sin datos</span>
  </div>
<?php } else { ?>
  <div id="visits_line_chart" style="width:100%;height:360px"></div>

  <script>
    (function loadGC(cb){
      if (typeof window.ensureGoogleCharts === 'function') {
        try { return window.ensureGoogleCharts(cb); } catch(_) {}
      }
      function start(){
        if (window.google && google.charts) {
          google.charts.load('current', {packages:['corechart'], language:'es'});
          google.charts.setOnLoadCallback(cb);
        }
      }
      if (window.google && google.charts) { start(); }
      else {
        var s=document.createElement('script'); s.src='https://www.gstatic.com/charts/loader.js'; s.async=true; s.onload=start; document.head.appendChild(s);
      }
    })(function drawLine(){
      const data = new google.visualization.DataTable();
      data.addColumn('date','Fecha');
      data.addColumn('number','Visitas');

      function mkDate(iso){ const p=iso.split('-'); return new Date(+p[0], +p[1]-1, +p[2]); }
      <?php foreach ($series as $r): ?>
        data.addRow([ mkDate('<?= $r[0] ?>'), <?= (int)$r[1] ?> ]);
      <?php endforeach; ?>

      const opts = {
        title: 'Visitas',
        legend: { position:'none' },
        hAxis:  { format:'d MMM', slantedText:true, slantedTextAngle:45 },
        vAxis:  { viewWindowMode:'explicit', viewWindow:{min:0} },
        pointSize: 5,
        curveType: 'function',
        lineWidth: 3,
        chartArea: {left:56, top:36, right:12, bottom:60},
        tooltip: { isHtml:false }
      };

      const el = document.getElementById('visits_line_chart');
      while (el.firstChild) el.removeChild(el.firstChild);
      new google.visualization.LineChart(el).draw(data, opts);
    });
  </script>
<?php } ?>
