<?php
/**
 * Generador de informe email semanal — versión liviana (sin imágenes base64).
 * Email de notificación con KPIs + link al panel.
 * 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;
    }
}

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 5 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 5");
    $cStmt->execute([...$clientIds, $since]);
    $cats    = $cStmt->fetchAll();
    $maxCat  = !empty($cats) ? max(1, (int)$cats[0]['cnt']) : 1;

    $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');

    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:20px 0">
<tr><td align="center">
<table width="580" cellpadding="0" cellspacing="0" border="0" bgcolor="#0d1629" style="background:#0d1629;max-width:580px">

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

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

  <!-- ═══ TOP CATEGORÍAS ═══ -->
  <?php if (!empty($cats)): ?>
  <tr><td bgcolor="#0d1629" style="background:#0d1629;padding:14px 18px 0">
    <table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#132236" style="background:#132236;border-radius:8px">
      <tr><td style="padding:14px 16px">
        <div style="font-size:11px;font-weight:600;color:#e2e8f0;border-left:3px solid #8b5cf6;padding-left:8px;margin-bottom:10px">
          Principales amenazas bloqueadas
        </div>
        <table width="100%" cellpadding="0" cellspacing="0" border="0">
          <?php foreach ($cats as $i => $c):
            $barW = (int)round((int)$c['cnt'] / $maxCat * 100);
            $barR = 100 - $barW;
            $col  = htmlspecialchars($c['category_color'] ?: '#8b5cf6');
            $rbg  = $i % 2 ? '#1a2d42' : '#132236';
          ?>
          <tr bgcolor="<?= $rbg ?>" style="background:<?= $rbg ?>">
            <td width="14" style="vertical-align:middle;padding:5px 8px 5px 0">
              <div style="width:8px;height:8px;border-radius:50%;background:<?= $col ?>"></div>
            </td>
            <td style="vertical-align:middle;padding:5px 10px 5px 0">
              <div style="font-size:10px;color:#cbd5e1"><?= htmlspecialchars($c['category']) ?></div>
              <table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#0d1629" style="background:#0d1629;border-radius:3px;height:4px;margin-top:3px">
                <tr>
                  <?php if ($barW > 0): ?><td width="<?= $barW ?>%" style="background:<?= $col ?>;height:4px;border-radius:3px 0 0 3px"></td><?php endif; ?>
                  <?php if ($barR  > 0): ?><td width="<?= $barR ?>%"  style="height:4px"></td><?php endif; ?>
                </tr>
              </table>
            </td>
            <td width="50" style="font-size:11px;font-weight:700;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; ?>

  <!-- ═══ BOTÓN CTA ═══ -->
  <tr><td bgcolor="#0d1629" style="background:#0d1629;padding:24px 18px 20px">
    <table width="100%" cellpadding="0" cellspacing="0" border="0">
      <tr>
        <td align="center" style="padding-bottom:10px">
          <a href="<?= APP_URL ?>"
             style="display:inline-block;background:#3b82f6;color:#ffffff;text-decoration:none;font-size:14px;font-weight:600;padding:14px 44px;border-radius:8px;letter-spacing:.2px">
            Ver informe completo en el panel &nbsp;&#8594;
          </a>
        </td>
      </tr>
      <tr>
        <td align="center">
          <div style="font-size:10px;color:#2d4060">
            Gráficos detallados, historial y configuración disponibles en el dashboard
          </div>
        </td>
      </tr>
    </table>
  </td></tr>

  <!-- ═══ FOOTER ═══ -->
  <tr><td bgcolor="#0a1e38" style="background:#0a1e38;padding:14px 24px 18px;border-radius:0 0 10px 10px">
    <table width="100%" cellpadding="0" cellspacing="0" border="0" style="border-top:1px solid #1a3050;padding-top:12px">
      <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">Dashboard &#8594;</a>
        </td>
      </tr>
    </table>
  </td></tr>

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

// Solo ejecutar si se accede directamente a este archivo (no como include desde 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;
}
