<?php
/**
 * inc/heatmap.php — heatmap diario tipo GitHub (último año), a ancho completo.
 * Requiere $daily en scope: ['Y-m-d' => ['req','sess','tin','tout','cached']].
 * El nivel de color va por nº de peticiones; el tooltip muestra el desglose del día.
 */
if (!defined('IN_APP')) { die('Acceso denegado'); }

$hmDaily = isset($daily) && is_array($daily) ? $daily : array();
$hmClass = array(
    0 => 'bg-gray-200 dark:bg-ink-800',
    1 => 'bg-primary-300 dark:bg-primary-900',
    2 => 'bg-primary-500 dark:bg-primary-700',
    3 => 'bg-primary-600 dark:bg-primary-500',
    4 => 'bg-primary-800 dark:bg-primary-300',
);
$hmLvl = function ($c) { if ($c <= 0) return 0; if ($c <= 2) return 1; if ($c <= 5) return 2; if ($c <= 10) return 3; return 4; };
$hmToday = new DateTime('today');
$hmStart = (clone $hmToday)->modify('-' . (53 * 7 - 1) . ' days');
$hmStart->modify('-' . ((int)$hmStart->format('w')) . ' days');

$hmTotal  = (int)$hmStart->diff($hmToday)->days + 1;
$hmActive = 0;
foreach ($hmDaily as $hv) { if ((int)($hv['req'] ?? 0) > 0) $hmActive++; }
$hmPct = $hmTotal > 0 ? round($hmActive * 100 / $hmTotal, 1) : 0;

// Etiquetas (orden fijo: peticiones, sesiones, entrada, salida, cacheado).
$L = array(
    App::t('admin.u_requests'), App::t('admin.u_sessions'),
    App::t('admin.u_tokens_in'), App::t('admin.u_tokens_out'), App::t('admin.u_cached'),
);
?>
<div class="w-full">
  <div class="flex w-full gap-[3px]">
    <?php $hmCur = clone $hmStart; while ($hmCur <= $hmToday): ?>
      <div class="flex flex-1 flex-col gap-[3px]">
        <?php for ($hi = 0; $hi < 7; $hi++):
          if ($hmCur > $hmToday) { echo '<div class="aspect-square w-full"></div>'; continue; }
          $hd = $hmCur->format('Y-m-d');
          $r  = $hmDaily[$hd] ?? null;
          $req = (int)($r['req'] ?? 0);
          $tip = $hd;
          if ($req > 0) {
              $tip = $hd . "\n" . $L[0] . ": " . $req
                   . "\n" . $L[1] . ": " . (int)$r['sess']
                   . "\n" . $L[2] . ": " . number_format((int)$r['tin'])
                   . "\n" . $L[3] . ": " . number_format((int)$r['tout'])
                   . "\n" . $L[4] . ": " . number_format((int)$r['cached']);
          }
          ?>
          <div class="aspect-square w-full rounded-[2px] <?= $hmClass[$hmLvl($req)] ?>" data-tip="<?= App::e($tip) ?>"></div>
        <?php $hmCur->modify('+1 day'); endfor; ?>
      </div>
    <?php endwhile; ?>
  </div>

  <div class="mt-3 flex items-center gap-2 text-xs text-gray-dark dark:text-gray-light">
    <span><strong class="text-ink-900 dark:text-paper"><?= $hmPct ?>%</strong> <?= App::e(App::t('hm.active')) ?></span>
    <span class="ml-auto"><?= App::e(App::t('hm.less')) ?></span>
    <?php for ($i = 0; $i <= 4; $i++): ?><span class="h-3 w-3 rounded-[2px] <?= $hmClass[$i] ?>"></span><?php endfor; ?>
    <span><?= App::e(App::t('hm.more')) ?></span>
  </div>
</div>
