<?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 base ===== */
[$from,$to] = build_range($GF['range'] ?? 'month', $GF['fromUi'] ?? '', $GF['toUi'] ?? '');

/* ===== Filtros globales ===== */
$entryCond = entry_condition_sql();
list($campWhere, $campParams)             = campaign_source_condition($GF, 'v');
list($advWhere, $advParams, $needAinJoin) = build_advanced_where($GF, 'v', 'ain');
list($noUtmWhere, $noUtmParams)           = non_campaign_guard_sql($GF, 'ain');

$params = [
  ':site' => $GF['site'],
  ':from' => $from,
  ':to'   => $to,
] + allowed_url_params() + $campParams + $advParams + $noUtmParams;

/* ===== Consulta (7x24) ===== */
$gridS = []; $gridU = [];
for($d=1;$d<=7;$d++){ for($h=0;$h<24;$h++){ $gridS[$d][$h]=0; $gridU[$d][$h]=0; } }
$maxS=0; $maxU=0;

try{
  $sql = "
    SELECT
      DAYOFWEEK(v.visit_last_action_time) AS dow,  -- 1=Dom..7=Sáb
      HOUR(v.visit_last_action_time)      AS hh,
      COUNT(*)                            AS sessions,
      COUNT(DISTINCT HEX(v.idvisitor))    AS uniques
    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
      $noUtmWhere
    GROUP BY dow, hh
    ORDER BY dow, hh
  ";
  $st = $pdo->prepare($sql);
  $st->execute($params);
  foreach($st->fetchAll() as $r){
    $d=(int)$r['dow']; $h=(int)$r['hh'];
    $s=(int)$r['sessions']; $u=(int)$r['uniques'];
    $gridS[$d][$h] = $s;
    $gridU[$d][$h] = $u;
    if($s>$maxS) $maxS=$s;
    if($u>$maxU) $maxU=$u;
  }
}catch(Throwable $e){
  echo '<div class="warn">No se pudo calcular el heatmap.</div>';
}

/* ===== Labels (lunes primero) ===== */
$dowOrder = [2,3,4,5,6,7,1]; // Lu..Do
$dowLbl = [1=>'Do',2=>'Lu',3=>'Ma',4=>'Mi',5=>'Ju',6=>'Vi',7=>'S&aacute;'];

?>
<div class="filters" style="gap:10px;align-items:center">
  <label><b>M&eacute;trica:</b></label>
  <select id="hm_metric">
    <option value="s">Sesiones</option>
    <option value="u">Visitantes &Uacute;nicos</option>
  </select>
  <span class="muted">Cuanto m&aacute;s oscuro, mayor intensidad.</span>
</div>

<style>
.hm-wrap{overflow:auto;border:1px solid #e5e5e5;border-radius:8px}
.hm{border-collapse:collapse;font-size:12px}
.hm th,.hm td{border:1px solid #e5e5e5;padding:6px;text-align:center;white-space:nowrap}
.hm th{background:#f7f7f7;font-weight:700;position:sticky;top:0;z-index:1}
.hm td{min-width:36px}
.hm .row-hdr{position:sticky;left:0;background:#f7f7f7;z-index:2}
.hm .val{font-weight:600}
.hm .muted{color:#6b7280;font-weight:400}
.hm-legend{display:flex;gap:6px;align-items:center;margin:6px 0}
.hm-c{width:18px;height:10px;border-radius:2px;border:1px solid #e5e5e5}
</style>

<div class="hm-wrap">
  <table class="hm" id="hm_table"
         data-smax="<?= (int)$maxS ?>" data-umax="<?= (int)$maxU ?>">
    <thead>
      <tr>
        <th class="row-hdr">&nbsp;</th>
        <?php for($h=0;$h<24;$h++): ?>
          <th><?= $h ?>h</th>
        <?php endfor; ?>
      </tr>
    </thead>
    <tbody>
      <?php foreach($dowOrder as $d): ?>
        <tr>
          <th class="row-hdr"><?= $dowLbl[$d] ?></th>
          <?php for($h=0;$h<24;$h++):
            $s = $gridS[$d][$h];
            $u = $gridU[$d][$h];
            // Sesiones por defecto
            $ratio = ($maxS>0) ? ($s/$maxS) : 0;
            // Escala de luz: 95% (bajo) a 35% (alto)
            $light = 95 - (int)round($ratio*60);
            $style = "background-color:hsl(220,90%,$light%);";
          ?>
          <td class="hm-cell"
              data-s="<?= (int)$s ?>" data-u="<?= (int)$u ?>"
              style="<?= $style ?>">
            <div class="val"><?= (int)$s ?></div>
            <div class="muted"><?= (int)$u ?></div>
          </td>
          <?php endfor; ?>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<div class="hm-legend">
  <span class="muted">Bajo</span>
  <span class="hm-c" style="background:hsl(220,90%,95%)"></span>
  <span class="hm-c" style="background:hsl(220,90%,80%)"></span>
  <span class="hm-c" style="background:hsl(220,90%,65%)"></span>
  <span class="hm-c" style="background:hsl(220,90%,50%)"></span>
  <span class="hm-c" style="background:hsl(220,90%,35%)"></span>
  <span class="muted">Alto</span>
</div>

<script>
(function(){
  const tbl = document.getElementById('hm_table');
  const sel = document.getElementById('hm_metric');
  function recolor(){
    const use = sel.value; // 's' o 'u'
    const max = +tbl.dataset[(use==='s')?'smax':'umax'] || 0;
    document.querySelectorAll('#hm_table .hm-cell').forEach(td=>{
      const v = +(td.dataset[use]||0);
      const ratio = max>0 ? v/max : 0;
      const light = Math.round(95 - ratio*60); // 95 -> 35
      td.style.backgroundColor = `hsl(220,90%,${light}%)`;
      // Valor visible en grande = métrica seleccionada, pequeño = la otra
      if(use==='s'){
        td.querySelector('.val').innerText = v;
        td.querySelector('.muted').innerText = td.dataset.u || 0;
      }else{
        td.querySelector('.val').innerText = v;
        td.querySelector('.muted').innerText = td.dataset.s || 0;
      }
    });
  }
  sel.addEventListener('change', recolor);
})();
</script>
