<?php
/**
 * Generador de informe HTML semanal por usuario.
 * Dark theme + SVG charts (line chart + donut).
 * Puede usarse standalone (admin preview) o desde report_cron.php.
 */
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/db.php';

if (!function_exists('fmtNR')) {
    function fmtNR(int $n): string {
        if ($n >= 1000000) return number_format($n / 1000000, 1) . 'M';
        if ($n >= 1000)    return number_format($n / 1000, 1) . 'K';
        return (string)$n;
    }
}

// ── SVG: Gráfico de líneas para actividad diaria ──────────────────────────────
function _svgLineChart(array $daily, int $w = 564, int $h = 185): string
{
    if (count($daily) < 2) return '';

    $padL = 38; $padR = 10; $padT = 14; $padB = 28;
    $cW   = $w - $padL - $padR;
    $cH   = $h - $padT - $padB;
    $n    = count($daily);
    $maxV = max(1, max(array_map(fn($d) => (int)$d['total'], $daily)));

    // Líneas de grilla horizontales + etiquetas Y
    $grid = '';
    for ($i = 0; $i <= 4; $i++) {
        $y   = round($padT + $cH - ($i / 4) * $cH, 2);
        $val = fmtNR((int)round($maxV * $i / 4));
        $x2  = $padL + $cW;
        $grid .= "<line x1=\"{$padL}\" y1=\"{$y}\" x2=\"{$x2}\" y2=\"{$y}\" stroke=\"#1e3a5f\" stroke-width=\"1\"/>";
        $grid .= "<text x=\"" . ($padL - 5) . "\" y=\"" . ($y + 3) . "\" text-anchor=\"end\" font-size=\"8\" fill=\"#475569\">{$val}</text>";
    }

    $dayNames  = ['Dom','Lun','Mar','Mié','Jue','Vie','Sáb'];
    $totalPts  = $blockPts = [];
    $xLabels   = $dotsTot = $dotsBlk = '';

    foreach ($daily as $i => $d) {
        $x  = round($padL + ($i / ($n - 1)) * $cW, 2);
        $yT = round($padT + $cH - ((int)$d['total']   / $maxV) * $cH, 2);
        $yB = round($padT + $cH - ((int)$d['blocked'] / $maxV) * $cH, 2);
        $totalPts[] = "{$x},{$yT}";
        $blockPts[] = "{$x},{$yB}";

        $dt     = strtotime($d['day']);
        $label  = $dayNames[(int)date('w', $dt)] . ' ' . date('d/m', $dt);
        $labelY = $padT + $cH + 18;
        $xLabels .= "<text x=\"{$x}\" y=\"{$labelY}\" text-anchor=\"middle\" font-size=\"7.5\" fill=\"#475569\">{$label}</text>";

        $dotsTot .= "<circle cx=\"{$x}\" cy=\"{$yT}\" r=\"3\" fill=\"#3b82f6\" stroke=\"#162032\" stroke-width=\"1.5\"/>";
        $dotsBlk .= "<circle cx=\"{$x}\" cy=\"{$yB}\" r=\"3\" fill=\"#ef4444\" stroke=\"#162032\" stroke-width=\"1.5\"/>";
    }

    $lineTot  = 'M ' . implode(' L ', $totalPts);
    $lineBlk  = 'M ' . implode(' L ', $blockPts);
    [$fx]     = explode(',', $totalPts[0]);
    [$lx]     = explode(',', $totalPts[count($totalPts) - 1]);
    $by       = $padT + $cH;
    $area     = "M {$fx},{$by} L " . implode(' L ', $totalPts) . " L {$lx},{$by} Z";
    $gid      = 'g' . substr(md5(serialize($daily)), 0, 8);

    return <<<SVG
<svg width="{$w}" height="{$h}" viewBox="0 0 {$w} {$h}" xmlns="http://www.w3.org/2000/svg" style="display:block">
  <defs>
    <linearGradient id="{$gid}" x1="0" y1="0" x2="0" y2="1">
      <stop offset="0%" stop-color="#3b82f6" stop-opacity="0.28"/>
      <stop offset="100%" stop-color="#3b82f6" stop-opacity="0.02"/>
    </linearGradient>
  </defs>
  {$grid}
  <path d="{$area}" fill="url(#{$gid})"/>
  <path d="{$lineTot}" fill="none" stroke="#3b82f6" stroke-width="2.2" stroke-linejoin="round" stroke-linecap="round"/>
  <path d="{$lineBlk}" fill="none" stroke="#ef4444" stroke-width="2.2" stroke-linejoin="round" stroke-linecap="round"/>
  {$dotsTot}{$dotsBlk}
  {$xLabels}
</svg>
SVG;
}

// ── SVG: Donut de categorías ──────────────────────────────────────────────────
function _svgDonut(array $cats, int $size = 158): string
{
    if (empty($cats)) return '';
    $total = array_sum(array_column($cats, 'cnt'));
    if ($total == 0) return '';

    $cx = $size / 2;
    $cy = $size / 2;
    $r  = $size * 0.42;
    $ir = $size * 0.25;

    $paths      = '';
    $startAngle = -90.0;

    foreach ($cats as $c) {
        $sweep = ((int)$c['cnt'] / $total) * 360;
        if ($sweep < 1) continue;

        $endAngle = $startAngle + $sweep;
        $sR = deg2rad($startAngle);
        $eR = deg2rad($endAngle);

        $x1  = round($cx + $r  * cos($sR), 3);  $y1  = round($cy + $r  * sin($sR), 3);
        $x2  = round($cx + $r  * cos($eR), 3);  $y2  = round($cy + $r  * sin($eR), 3);
        $ix1 = round($cx + $ir * cos($eR), 3);  $iy1 = round($cy + $ir * sin($eR), 3);
        $ix2 = round($cx + $ir * cos($sR), 3);  $iy2 = round($cy + $ir * sin($sR), 3);
        $la  = $sweep > 180 ? 1 : 0;
        $col = htmlspecialchars($c['category_color'] ?: '#64748b');

        $paths .= "<path d=\"M {$x1} {$y1} A {$r} {$r} 0 {$la} 1 {$x2} {$y2} L {$ix1} {$iy1} A {$ir} {$ir} 0 {$la} 0 {$ix2} {$iy2} Z\" fill=\"{$col}\" stroke=\"#0d1629\" stroke-width=\"1.5\"/>\n";
        $startAngle = $endAngle;
    }

    // Texto central
    $lbl  = fmtNR($total);
    $ty1  = round($cy - 5, 1);
    $ty2  = round($cy + 9, 1);
    $paths .= "<text x=\"{$cx}\" y=\"{$ty1}\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"bold\" fill=\"#e2e8f0\" font-family=\"Arial\">{$lbl}</text>";
    $paths .= "<text x=\"{$cx}\" y=\"{$ty2}\" text-anchor=\"middle\" font-size=\"8\" fill=\"#64748b\" font-family=\"Arial\">bloqueadas</text>";

    return "<svg width=\"{$size}\" height=\"{$size}\" viewBox=\"0 0 {$size} {$size}\" xmlns=\"http://www.w3.org/2000/svg\" style=\"display:block;margin:0 auto\">{$paths}</svg>";
}

// ── Generador principal ───────────────────────────────────────────────────────
function generateReport(PDO $pdo, int $userId, int $days = 7): string
{
    $uStmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $uStmt->execute([$userId]);
    $uRow = $uStmt->fetch();
    if (!$uRow) return '';

    $clientStmt = $pdo->prepare("SELECT adguard_client_id FROM client_mapping WHERE user_id = ?");
    $clientStmt->execute([$userId]);
    $clientIds = $clientStmt->fetchAll(PDO::FETCH_COLUMN);
    if (empty($clientIds)) return '';

    $ph    = implode(',', array_fill(0, count($clientIds), '?'));
    $since = date('Y-m-d H:i:s', strtotime("-{$days} days"));

    // Stats globales
    $s = $pdo->prepare("SELECT COUNT(*) AS total, SUM(reason LIKE 'Filtered%') AS blocked FROM query_logs WHERE adguard_client_id IN ($ph) AND log_time >= ?");
    $s->execute([...$clientIds, $since]);
    $stats     = $s->fetch();
    $total     = (int)$stats['total'];
    $blocked   = (int)$stats['blocked'];
    $allowed   = $total - $blocked;
    $blockRate = $total > 0 ? round($blocked / $total * 100, 1) : 0;

    // Top 10 categorías bloqueadas
    $cStmt = $pdo->prepare("SELECT category, category_color, COUNT(*) AS cnt FROM query_logs WHERE adguard_client_id IN ($ph) AND reason LIKE 'Filtered%' AND log_time >= ? GROUP BY category, category_color ORDER BY cnt DESC LIMIT 10");
    $cStmt->execute([...$clientIds, $since]);
    $cats = $cStmt->fetchAll();

    // Top 10 dominios bloqueados
    $dStmt = $pdo->prepare("SELECT domain, category, category_color, COUNT(*) AS cnt FROM query_logs WHERE adguard_client_id IN ($ph) AND reason LIKE 'Filtered%' AND log_time >= ? GROUP BY domain, category, category_color ORDER BY cnt DESC LIMIT 10");
    $dStmt->execute([...$clientIds, $since]);
    $doms = $dStmt->fetchAll();

    // Actividad diaria
    $tStmt = $pdo->prepare("SELECT DATE(log_time) AS day, COUNT(*) AS total, SUM(reason LIKE 'Filtered%') AS blocked FROM query_logs WHERE adguard_client_id IN ($ph) AND log_time >= ? GROUP BY day ORDER BY day ASC");
    $tStmt->execute([...$clientIds, $since]);
    $daily = $tStmt->fetchAll();

    // Logos en base64
    $logoZT = '';
    if (is_file(__DIR__ . '/logos/OrigZeroTrustDNS.png')) {
        $logoZT = 'data:image/png;base64,' . base64_encode(file_get_contents(__DIR__ . '/logos/OrigZeroTrustDNS.png'));
    }
    $logoPCAS = '';
    if (is_file(__DIR__ . '/logos/PCASSI-cs-OJPG.jpg')) {
        $logoPCAS = 'data:image/jpeg;base64,' . base64_encode(file_get_contents(__DIR__ . '/logos/PCASSI-cs-OJPG.jpg'));
    }

    $name     = htmlspecialchars($uRow['display_name']);
    $fromDate = date('d/m/Y', strtotime("-{$days} days"));
    $toDate   = date('d/m/Y');
    $genDate  = date('d/m/Y H:i');

    $maxDom   = !empty($doms)  ? max(1, (int)$doms[0]['cnt'])  : 1;
    $maxCat   = !empty($cats)  ? max(1, (int)$cats[0]['cnt'])  : 1;
    $maxDaily = !empty($daily) ? max(1, (int)max(array_column($daily, 'total'))) : 1;
    $dayNames = ['Dom','Lun','Mar','Mié','Jue','Vie','Sáb'];

    // SVG charts
    $svgLine  = count($daily) >= 2 ? _svgLineChart($daily, 564, 185) : '';
    $svgDonut = !empty($cats)      ? _svgDonut($cats, 158)            : '';

    ob_start(); ?>
<!DOCTYPE html>
<html lang="es">
<head><meta charset="UTF-8"><title>Informe Semanal DNS – <?= $name ?></title></head>
<body style="margin:0;padding:0;background:#0d1629;font-family:Arial,Helvetica,sans-serif;font-size:13px;color:#e2e8f0">
<table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#0d1629" style="background:#0d1629;padding:16px 0">
<tr><td align="center">
<table width="620" cellpadding="0" cellspacing="0" border="0" bgcolor="#0d1629" style="background:#0d1629;max-width:620px">

  <!-- ═══ HERO BANNER — "PCASSI te está protegiendo" ═══ -->
  <tr><td bgcolor="#102a4c" style="background:#102a4c;padding:22px 28px;border-radius:10px 10px 0 0">
    <table width="100%" cellpadding="0" cellspacing="0" border="0">
      <tr>
        <td style="vertical-align:middle">
          <div style="font-size:9px;color:#38bdf8;text-transform:uppercase;letter-spacing:1.5px;margin-bottom:6px">
            &#128737;&nbsp; ZeroTrust DNS &middot; Protección activa
          </div>
          <div style="font-size:22px;font-weight:600;color:#ffffff;line-height:1.15;letter-spacing:-0.2px">
            PCASSI te está protegiendo
          </div>
          <div style="font-size:13px;color:#93c5fd;margin-top:6px;font-weight:400">
            Con nosotros estás seguro — tu red monitoreada 24/7
          </div>
        </td>
        <td align="right" valign="middle" style="padding-left:16px;white-space:nowrap">
          <div style="font-size:28px;font-weight:900;color:#ef4444;line-height:1"><?= fmtNR($blocked) ?></div>
          <div style="font-size:9px;color:#fca5a5;text-transform:uppercase;letter-spacing:.5px">amenazas bloqueadas</div>
          <div style="font-size:9px;color:#475569;margin-top:3px"><?= $fromDate ?> – <?= $toDate ?></div>
        </td>
      </tr>
    </table>
  </td></tr>

  <!-- ═══ HEADER CON LOGOS ═══ -->
  <tr><td bgcolor="#0f2540" style="background:#0f2540;padding:0">
    <table width="100%" cellpadding="0" cellspacing="0" border="0">
      <tr>
        <td valign="middle" style="padding:18px 14px 18px 24px;width:190px">
          <?php if ($logoZT): ?>
          <img src="<?= $logoZT ?>" alt="Zero Trust DNS" height="58" style="display:block;border:0;height:58px;max-width:185px">
          <?php else: ?>
          <span style="color:#ffffff;font-size:14px;font-weight:600">Zero Trust DNS</span>
          <?php endif; ?>
        </td>
        <td valign="middle" style="padding:18px 16px;border-left:1px solid rgba(255,255,255,0.15);border-right:1px solid rgba(255,255,255,0.15);width:175px">
          <?php if ($logoPCAS): ?>
          <img src="<?= $logoPCAS ?>" alt="PCASSI" height="52" style="display:block;border:0;height:52px;max-width:168px">
          <?php else: ?>
          <span style="color:#93c5fd;font-size:12px;font-weight:600">PCASSI Ciberseguridad</span>
          <?php endif; ?>
        </td>
        <td align="right" valign="middle" style="padding:18px 24px 18px 14px">
          <div style="color:#93c5fd;font-size:10px;line-height:1.9">
            <strong style="color:#ffffff;font-size:13px;font-weight:600;display:block">Informe Semanal DNS</strong>
            <?= $fromDate ?> – <?= $toDate ?><br>
            <span style="color:#60a5fa;font-weight:600"><?= $name ?></span>
          </div>
        </td>
      </tr>
    </table>
  </td></tr>

  <!-- ═══ BARRA SUBTÍTULO ═══ -->
  <tr><td bgcolor="#0c1f3a" style="background:#0c1f3a;padding:6px 24px">
    <table width="100%" cellpadding="0" cellspacing="0"><tr>
      <td style="color:#38bdf8;font-size:9px;text-transform:uppercase;letter-spacing:.9px">Panel de Protección DNS · Tiempo Real</td>
      <td align="right" style="color:#2d4060;font-size:9px">Generado: <?= $genDate ?></td>
    </tr></table>
  </td></tr>

  <!-- ═══ TARJETAS KPI ═══ -->
  <tr><td bgcolor="#0d1629" style="background:#0d1629;padding:20px 20px 0">
    <table width="100%" cellpadding="0" cellspacing="0" border="0">
      <tr>
        <td width="23%" bgcolor="#132236" style="background:#132236;text-align:center;padding:16px 4px 13px;border-radius:8px;border-top:3px solid #3b82f6">
          <div style="font-size:26px;font-weight:900;color:#e2e8f0;line-height:1"><?= fmtNR($total) ?></div>
          <div style="font-size:8.5px;color:#4a6080;text-transform:uppercase;margin-top:6px;letter-spacing:.6px">Consultas DNS</div>
        </td>
        <td width="4%">&nbsp;</td>
        <td width="23%" bgcolor="#1c0e12" style="background:#1c0e12;text-align:center;padding:16px 4px 13px;border-radius:8px;border-top:3px solid #ef4444">
          <div style="font-size:26px;font-weight:900;color:#f87171;line-height:1"><?= fmtNR($blocked) ?></div>
          <div style="font-size:8.5px;color:#4a3040;text-transform:uppercase;margin-top:6px;letter-spacing:.6px">Bloqueadas</div>
        </td>
        <td width="4%">&nbsp;</td>
        <td width="23%" bgcolor="#0c1c12" style="background:#0c1c12;text-align:center;padding:16px 4px 13px;border-radius:8px;border-top:3px solid #22c55e">
          <div style="font-size:26px;font-weight:900;color:#4ade80;line-height:1"><?= fmtNR($allowed) ?></div>
          <div style="font-size:8.5px;color:#2a4030;text-transform:uppercase;margin-top:6px;letter-spacing:.6px">Permitidas</div>
        </td>
        <td width="4%">&nbsp;</td>
        <td width="23%" bgcolor="#120e28" style="background:#120e28;text-align:center;padding:16px 4px 13px;border-radius:8px;border-top:3px solid #8b5cf6">
          <div style="font-size:26px;font-weight:900;color:#a78bfa;line-height:1"><?= $blockRate ?>%</div>
          <div style="font-size:8.5px;color:#3a2860;text-transform:uppercase;margin-top:6px;letter-spacing:.6px">Tasa Bloqueo</div>
        </td>
      </tr>
    </table>
  </td></tr>

  <!-- ═══ GRÁFICO DE LÍNEAS — ACTIVIDAD DNS ═══ -->
  <?php if ($svgLine): ?>
  <tr><td bgcolor="#0d1629" style="background:#0d1629;padding:16px 20px 0">
    <table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#132236" style="background:#132236;border-radius:8px">
      <tr><td style="padding:14px 16px 4px">
        <table width="100%" cellpadding="0" cellspacing="0"><tr>
          <td style="font-size:12px;font-weight:bold;color:#e2e8f0;border-left:3px solid #3b82f6;padding-left:8px">
            Actividad DNS
            <span style="font-size:9px;color:#475569;font-weight:normal;margin-left:8px">últimos <?= $days ?> días</span>
          </td>
          <td align="right" style="font-size:9px;color:#475569;white-space:nowrap">
            <span style="color:#60a5fa">&#9644;</span>&nbsp;Total consultas
            &nbsp;&nbsp;
            <span style="color:#ef4444">&#9644;</span>&nbsp;Bloqueadas
          </td>
        </tr></table>
      </td></tr>
      <tr><td style="padding:6px 16px 14px"><?= $svgLine ?></td></tr>
    </table>
  </td></tr>
  <?php endif; ?>

  <!-- ═══ DONUT + CATEGORÍAS (dos columnas) ═══ -->
  <?php if ($svgDonut): ?>
  <tr><td bgcolor="#0d1629" style="background:#0d1629;padding:14px 20px 0">
    <table width="100%" cellpadding="0" cellspacing="0" border="0">
      <tr valign="top">

        <!-- Donut -->
        <td width="188" bgcolor="#132236" style="background:#132236;border-radius:8px;padding:14px 12px 14px">
          <div style="font-size:11px;font-weight:bold;color:#e2e8f0;border-left:3px solid #8b5cf6;padding-left:8px;margin-bottom:10px">Por Categoría</div>
          <?= $svgDonut ?>
        </td>

        <td width="14">&nbsp;</td>

        <!-- Lista categorías -->
        <td bgcolor="#132236" style="background:#132236;border-radius:8px;padding:14px 14px 14px">
          <div style="font-size:11px;font-weight:bold;color:#e2e8f0;border-left:3px solid #8b5cf6;padding-left:8px;margin-bottom:10px">Categorías Bloqueadas</div>
          <table width="100%" cellpadding="0" cellspacing="2" border="0">
            <?php foreach ($cats as $i => $c):
              $barW    = (int)round((int)$c['cnt'] / $maxCat * 100);
              $barRest = 100 - $barW;
              $color   = htmlspecialchars($c['category_color'] ?: '#8b5cf6');
              $rowBg   = $i % 2 ? '#1a2d42' : '#132236';
            ?>
            <tr bgcolor="<?= $rowBg ?>" style="background:<?= $rowBg ?>">
              <td width="14" style="vertical-align:middle;padding:4px 6px 4px 0">
                <div style="width:9px;height:9px;border-radius:50%;background:<?= $color ?>"></div>
              </td>
              <td style="padding:4px 8px 4px 0;vertical-align:middle">
                <div style="font-size:9.5px;color:#cbd5e1;margin-bottom:3px"><?= htmlspecialchars($c['category']) ?></div>
                <table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#0d1629" style="background:#0d1629;border-radius:3px;height:5px">
                  <tr>
                    <?php if ($barW > 0): ?><td width="<?= $barW ?>%" style="background:<?= $color ?>;height:5px;border-radius:3px 0 0 3px"></td><?php endif; ?>
                    <?php if ($barRest > 0): ?><td width="<?= $barRest ?>%" style="height:5px"></td><?php endif; ?>
                  </tr>
                </table>
              </td>
              <td width="42" style="font-size:10px;font-weight:bold;color:#e2e8f0;text-align:right;vertical-align:middle;white-space:nowrap"><?= fmtNR((int)$c['cnt']) ?></td>
            </tr>
            <?php endforeach; ?>
          </table>
        </td>

      </tr>
    </table>
  </td></tr>
  <?php endif; ?>

  <!-- ═══ SEPARADOR "DETALLE" ═══ -->
  <tr><td bgcolor="#0d1629" style="background:#0d1629;padding:20px 24px 8px">
    <div style="border-top:1px solid #1e3a5f;padding-top:14px;font-size:9px;color:#2d4060;text-transform:uppercase;letter-spacing:1px">
      &#9632;&nbsp; Detalle del período — <?= $fromDate ?> al <?= $toDate ?>
    </div>
  </td></tr>

  <!-- ═══ ACTIVIDAD DIARIA — TABLA ═══ -->
  <?php if (!empty($daily)): ?>
  <tr><td bgcolor="#0d1629" style="background:#0d1629;padding:0 20px">
    <table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#132236" style="background:#132236;border-radius:8px">
      <tr><td style="padding:12px 14px 0">
        <div style="font-size:11px;font-weight:bold;color:#e2e8f0;border-left:3px solid #3b82f6;padding-left:8px;margin-bottom:10px">Actividad Diaria</div>
        <table width="100%" cellpadding="0" cellspacing="3" border="0">
          <tr>
            <td width="76" style="font-size:8px;color:#475569;text-transform:uppercase;padding-bottom:4px">Día</td>
            <td style="font-size:8px;color:#475569;text-transform:uppercase;padding-bottom:4px">Actividad (bloqueado / permitido)</td>
            <td width="44" style="font-size:8px;color:#475569;text-transform:uppercase;text-align:right;padding-bottom:4px">Total</td>
            <td width="36" style="font-size:8px;color:#475569;text-transform:uppercase;text-align:right;padding-bottom:4px">Bloq%</td>
          </tr>
          <?php foreach ($daily as $i => $d):
            $dt        = strtotime($d['day']);
            $t         = (int)$d['total'];
            $b         = (int)$d['blocked'];
            $pct       = $t > 0 ? round($b / $t * 100, 1) : 0;
            $barTotal  = (int)round($t / $maxDaily * 100);
            $barBlock  = $t > 0 ? (int)round($b / $t * $barTotal) : 0;
            $barAllow  = $barTotal - $barBlock;
            $barEmpty  = 100 - $barTotal;
            $rowBg     = $i % 2 ? '#1a2d42' : '#132236';
            $dayLabel  = $dayNames[(int)date('w', $dt)] . ' ' . date('d/m', $dt);
          ?>
          <tr bgcolor="<?= $rowBg ?>" style="background:<?= $rowBg ?>">
            <td style="font-size:10px;color:#94a3b8;padding:5px 0;white-space:nowrap;vertical-align:middle"><?= $dayLabel ?></td>
            <td style="vertical-align:middle;padding:5px 6px">
              <table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#0d1629" style="background:#0d1629;border-radius:3px;height:10px">
                <tr>
                  <?php if ($barBlock > 0): ?><td width="<?= $barBlock ?>%" style="background:#ef4444;height:10px;border-radius:3px 0 0 3px"></td><?php endif; ?>
                  <?php if ($barAllow > 0): ?><td width="<?= $barAllow ?>%" style="background:#22c55e;height:10px<?= $barBlock === 0 ? ';border-radius:3px 0 0 3px' : '' ?>"></td><?php endif; ?>
                  <?php if ($barEmpty > 0): ?><td width="<?= $barEmpty ?>%" style="height:10px"></td><?php endif; ?>
                </tr>
              </table>
            </td>
            <td style="font-size:10px;font-weight:bold;color:#e2e8f0;text-align:right;padding:5px 0;vertical-align:middle;white-space:nowrap"><?= fmtNR($t) ?></td>
            <td style="font-size:10px;color:<?= $pct > 30 ? '#f87171' : '#64748b' ?>;text-align:right;padding:5px 0;vertical-align:middle"><?= $pct ?>%</td>
          </tr>
          <?php endforeach; ?>
        </table>
      </td></tr>
      <tr><td style="height:12px"></td></tr>
    </table>
  </td></tr>
  <?php endif; ?>

  <!-- ═══ TOP 10 DOMINIOS BLOQUEADOS ═══ -->
  <?php if (!empty($doms)): ?>
  <tr><td bgcolor="#0d1629" style="background:#0d1629;padding:12px 20px 0">
    <table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#132236" style="background:#132236;border-radius:8px">
      <tr><td style="padding:12px 14px 0">
        <div style="font-size:11px;font-weight:bold;color:#e2e8f0;border-left:3px solid #ef4444;padding-left:8px;margin-bottom:10px">Top 10 Dominios Bloqueados</div>
        <table width="100%" cellpadding="0" cellspacing="2" border="0">
          <?php foreach ($doms as $i => $d):
            $barW    = (int)round((int)$d['cnt'] / $maxDom * 100);
            $barRest = 100 - $barW;
            $color   = htmlspecialchars($d['category_color'] ?: '#ef4444');
            $domain  = htmlspecialchars(strlen($d['domain']) > 38 ? substr($d['domain'], 0, 36) . '…' : $d['domain']);
            $rowBg   = $i % 2 ? '#1a2d42' : '#132236';
          ?>
          <tr bgcolor="<?= $rowBg ?>" style="background:<?= $rowBg ?>">
            <td width="22" style="font-size:9px;color:#475569;padding:5px 4px 5px 0;vertical-align:middle"><?= $i + 1 ?>.</td>
            <td style="padding:5px 8px 5px 0;vertical-align:middle">
              <div style="font-size:10px;color:#cbd5e1;margin-bottom:3px;white-space:nowrap;overflow:hidden"><?= $domain ?></div>
              <table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#0d1629" style="background:#0d1629;border-radius:3px;height:6px">
                <tr>
                  <?php if ($barW > 0): ?><td width="<?= $barW ?>%" style="background:<?= $color ?>;height:6px;border-radius:3px 0 0 3px"></td><?php endif; ?>
                  <?php if ($barRest > 0): ?><td width="<?= $barRest ?>%" style="height:6px"></td><?php endif; ?>
                </tr>
              </table>
            </td>
            <td width="46" style="font-size:11px;font-weight:bold;color:#e2e8f0;text-align:right;vertical-align:middle;white-space:nowrap"><?= fmtNR((int)$d['cnt']) ?></td>
          </tr>
          <?php endforeach; ?>
        </table>
      </td></tr>
      <tr><td style="height:12px"></td></tr>
    </table>
  </td></tr>
  <?php endif; ?>

  <!-- ═══ BLOQUE DE RESUMEN ═══ -->
  <tr><td bgcolor="#0d1629" style="background:#0d1629;padding:14px 20px 0">
    <table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#0c2040" style="background:#0c2040;border-radius:8px;border-left:4px solid #3b82f6">
      <tr><td style="padding:13px 16px">
        <div style="font-size:11px;color:#60a5fa;font-weight:bold;margin-bottom:5px">&#128737; Resumen de Protección</div>
        <div style="font-size:10px;color:#93c5fd;line-height:1.7">
          Durante los últimos <?= $days ?> días, <strong style="color:#e2e8f0"><?= $name ?></strong> realizó
          <strong style="color:#e2e8f0"><?= fmtNR($total) ?></strong> consultas DNS.
          Se bloquearon <strong style="color:#f87171"><?= fmtNR($blocked) ?></strong> amenazas potenciales
          (<?= $blockRate ?>% del total), manteniendo la red protegida contra
          publicidad, malware y rastreadores.
        </div>
      </td></tr>
    </table>
  </td></tr>

  <!-- ═══ FOOTER ═══ -->
  <tr><td bgcolor="#0a1e38" style="background:#0a1e38;padding:16px 24px 20px;border-radius:0 0 10px 10px;margin-top:16px">
    <table width="100%" cellpadding="0" cellspacing="0" border="0" style="border-top:1px solid #1a3050;padding-top:14px">
      <tr>
        <td style="font-size:9px;color:#2d4060;line-height:1.6">
          <strong style="color:#3d5070">ZeroTrust Shield</strong> by PCASSI Ciberseguridad<br>
          Protección DNS en tiempo real &middot; <?= $genDate ?>
        </td>
        <td align="right">
          <a href="<?= APP_URL ?>" style="color:#3b82f6;text-decoration:none;font-size:10px;font-weight:bold">Ver Dashboard &#8594;</a>
        </td>
      </tr>
    </table>
  </td></tr>

</table>
</td></tr>
</table>
</body>
</html>
<?php
    return ob_get_clean();
}

// Si se accede directamente en browser (admin only) → preview
// IMPORTANTE: no ejecutar si este archivo fue incluido desde otro script (ej: api.php)
if (PHP_SAPI !== 'cli' && realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) {
    requireAdmin();
    $pdo    = db();
    $userId = (int)($_GET['user_id'] ?? 0);
    if (!$userId) {
        http_response_code(400);
        die('<p style="font-family:sans-serif;color:#888">Parámetro user_id requerido.</p>');
    }
    $html = generateReport($pdo, $userId);
    if (!$html) die('<p style="font-family:sans-serif;color:#888">Usuario no encontrado o sin clientes asignados.</p>');
    echo $html;
    exit;
}
