<?php
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/db.php';

requireLogin();
$user    = currentUser();
$pdo     = db();
$isAdmin = $user['role'] === 'admin';

$period  = $_GET['period'] ?? '24h';
$periodMap = ['6h' => 6, '24h' => 24, '7d' => 168, '30d' => 720];
$hours   = $periodMap[$period] ?? 24;
$since   = date('Y-m-d H:i:s', strtotime("-{$hours} hours"));

$periodLabels = ['6h' => 'Últimas 6 horas', '24h' => 'Últimas 24 horas', '7d' => 'Últimos 7 días', '30d' => 'Últimos 30 días'];
$periodLabel  = $periodLabels[$period] ?? $period;

// Determine client IDs
if ($isAdmin && !empty($_GET['view_user'])) {
    $viewUserId = (int)$_GET['view_user'];
    $stmt = $pdo->prepare("SELECT adguard_client_id FROM client_mapping WHERE user_id = ?");
    $stmt->execute([$viewUserId]);
    $clientIds = $stmt->fetchAll(PDO::FETCH_COLUMN);
    $viewUserRow = $pdo->prepare("SELECT display_name FROM users WHERE id = ?");
    $viewUserRow->execute([$viewUserId]);
    $viewUserName = $viewUserRow->fetchColumn() ?: 'Usuario';
    if (empty($clientIds)) $clientIds = ['__no_match__'];
} elseif ($isAdmin) {
    $clientIds  = $pdo->query("SELECT DISTINCT adguard_client_id FROM query_logs")->fetchAll(PDO::FETCH_COLUMN);
    $viewUserName = 'Todos los clientes';
} else {
    $clientIds  = $user['client_ids'];
    $viewUserName = $user['display_name'];
}

if (empty($clientIds)) $clientIds = ['__no_match__'];
$ph = clientIdPlaceholders($clientIds);

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

// Top categories
$catRows = $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 12
");
$catRows->execute([...$clientIds, $since]);
$categories = $catRows->fetchAll();

// Top domains
$domRows = $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 20
");
$domRows->execute([...$clientIds, $since]);
$topDomains = $domRows->fetchAll();

// Recent log
$logRows = $pdo->prepare("
    SELECT log_time, domain, query_type, reason, category, category_color, filter_name, client_name
    FROM query_logs WHERE adguard_client_id IN ($ph) AND log_time >= ?
    ORDER BY log_time DESC LIMIT 100
");
$logRows->execute([...$clientIds, $since]);
$logEntries = $logRows->fetchAll();

// Timeline data for sparkline table
$gran = $hours <= 48 ? '%Y-%m-%d %H:00:00' : '%Y-%m-%d 00:00:00';
$tlRows = $pdo->prepare("
    SELECT DATE_FORMAT(log_time, ?) AS ts, COUNT(*) AS total, SUM(reason LIKE 'Filtered%') AS blocked
    FROM query_logs WHERE adguard_client_id IN ($ph) AND log_time >= ?
    GROUP BY ts ORDER BY ts ASC
");
$tlRows->execute([$gran, ...$clientIds, $since]);
$timeline = $tlRows->fetchAll();

function fmtN(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 reasonLabel(string $r): string {
    return match($r) {
        'FilteredBlackList'    => 'Bloqueado',
        'FilteredSafeBrowsing' => 'Amenaza',
        'FilteredParental'     => 'Parental',
        'FilteredSafeSearch'   => 'SafeSearch',
        'NotFilteredWhiteList' => 'Lista Blanca',
        'NotFilteredNotFound'  => 'Permitido',
        default => $r,
    };
}

$generatedAt = date('d/m/Y H:i');
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Informe DNS – <?= htmlspecialchars($viewUserName) ?> – <?= $periodLabel ?></title>
<style>
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body { font-family: Arial, sans-serif; font-size: 12px; color: #1e293b; background: #fff; }
  .page { max-width: 960px; margin: 0 auto; padding: 24px; }
  .header { display: flex; align-items: center; justify-content: space-between; border-bottom: 3px solid #3b82f6; padding-bottom: 12px; margin-bottom: 20px; }
  .header-left h1 { font-size: 18px; color: #1e293b; }
  .header-left p { font-size: 11px; color: #64748b; margin-top: 3px; }
  .header-right { font-size: 11px; color: #64748b; text-align: right; }
  .section-title { font-size: 13px; font-weight: bold; color: #1e293b; border-left: 3px solid #3b82f6; padding-left: 8px; margin: 20px 0 10px; }
  .stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin-bottom: 20px; }
  .stat-card { border: 1px solid #e2e8f0; border-radius: 6px; padding: 12px; text-align: center; }
  .stat-value { font-size: 22px; font-weight: bold; color: #1e293b; }
  .stat-label { font-size: 10px; color: #64748b; text-transform: uppercase; letter-spacing: .04em; margin-top: 3px; }
  .stat-card.blocked .stat-value { color: #dc2626; }
  .stat-card.rate .stat-value { color: #16a34a; }
  table { width: 100%; border-collapse: collapse; font-size: 11px; margin-bottom: 4px; }
  th { background: #f1f5f9; color: #64748b; text-transform: uppercase; font-size: 10px; letter-spacing: .04em; padding: 6px 8px; text-align: left; border-bottom: 1px solid #e2e8f0; }
  td { padding: 5px 8px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; }
  tr:last-child td { border-bottom: none; }
  .dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 5px; vertical-align: middle; }
  .badge { display: inline-block; padding: 1px 6px; border-radius: 3px; font-size: 10px; font-weight: 600; }
  .badge-danger { background: #fee2e2; color: #991b1b; }
  .badge-success { background: #dcfce7; color: #166534; }
  .badge-secondary { background: #f1f5f9; color: #475569; }
  .badge-warning { background: #fef9c3; color: #92400e; }
  .two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
  .bar-row { display: flex; align-items: center; gap: 6px; margin-bottom: 4px; }
  .bar-label { width: 180px; font-size: 11px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex-shrink: 0; }
  .bar-track { flex: 1; background: #f1f5f9; border-radius: 3px; height: 12px; }
  .bar-fill { height: 12px; border-radius: 3px; }
  .bar-val { width: 45px; text-align: right; font-size: 11px; font-weight: 600; flex-shrink: 0; }
  .footer { margin-top: 24px; padding-top: 12px; border-top: 1px solid #e2e8f0; font-size: 10px; color: #94a3b8; text-align: center; }
  @media print {
    body { font-size: 11px; }
    .no-print { display: none; }
    .page { padding: 12px; }
  }
</style>
</head>
<body>
<div class="page">

  <!-- Header -->
  <div class="header">
    <div class="header-left">
      <h1>🛡️ ZeroTrust Shield – Informe de Protección DNS</h1>
      <p><?= htmlspecialchars($viewUserName) ?> &nbsp;·&nbsp; <?= $periodLabel ?></p>
    </div>
    <div class="header-right">
      Generado el <?= $generatedAt ?><br>
      <a href="#" onclick="window.print();return false;" style="color:#3b82f6;text-decoration:none">🖨 Imprimir / PDF</a>
    </div>
  </div>

  <!-- Stats cards -->
  <div class="stats-grid">
    <div class="stat-card">
      <div class="stat-value"><?= fmtN($total) ?></div>
      <div class="stat-label">Consultas DNS</div>
    </div>
    <div class="stat-card blocked">
      <div class="stat-value"><?= fmtN($blocked) ?></div>
      <div class="stat-label">Bloqueadas</div>
    </div>
    <div class="stat-card">
      <div class="stat-value"><?= fmtN($allowed) ?></div>
      <div class="stat-label">Permitidas</div>
    </div>
    <div class="stat-card rate">
      <div class="stat-value"><?= $blockRate ?>%</div>
      <div class="stat-label">Tasa de Bloqueo</div>
    </div>
  </div>

  <!-- Timeline -->
  <?php if (!empty($timeline)): ?>
  <div class="section-title">Actividad por período</div>
  <table>
    <thead><tr>
      <th>Fecha/Hora</th>
      <th class="text-right" style="text-align:right">Total consultas</th>
      <th class="text-right" style="text-align:right">Bloqueadas</th>
      <th class="text-right" style="text-align:right">% Bloqueadas</th>
    </tr></thead>
    <tbody>
    <?php foreach ($timeline as $tl):
        $t = (int)$tl['total']; $b = (int)$tl['blocked'];
        $pct = $t > 0 ? round($b / $t * 100, 1) : 0; ?>
      <tr>
        <td><?= htmlspecialchars($tl['ts']) ?></td>
        <td style="text-align:right"><?= fmtN($t) ?></td>
        <td style="text-align:right;color:#dc2626"><?= fmtN($b) ?></td>
        <td style="text-align:right"><?= $pct ?>%</td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
  <?php endif; ?>

  <!-- Two column: Top Domains + Categories -->
  <div class="two-col" style="margin-top:16px">

    <!-- Top domains -->
    <div>
      <div class="section-title">Top 20 Dominios Bloqueados</div>
      <?php if (!empty($topDomains)):
          $maxCnt = (int)($topDomains[0]['cnt'] ?? 1); ?>
        <?php foreach ($topDomains as $i => $d): ?>
          <div class="bar-row">
            <div class="bar-label" title="<?= htmlspecialchars($d['domain']) ?>"><?= $i+1 ?>. <?= htmlspecialchars(strlen($d['domain']) > 28 ? substr($d['domain'],0,26).'…' : $d['domain']) ?></div>
            <div class="bar-track"><div class="bar-fill" style="width:<?= round((int)$d['cnt']/$maxCnt*100) ?>%;background:<?= htmlspecialchars($d['category_color']) ?>"></div></div>
            <div class="bar-val"><?= fmtN((int)$d['cnt']) ?></div>
          </div>
        <?php endforeach; ?>
      <?php else: ?><p style="color:#94a3b8;font-size:11px">Sin datos</p><?php endif; ?>
    </div>

    <!-- Categories -->
    <div>
      <div class="section-title">Categorías Bloqueadas</div>
      <?php if (!empty($categories)):
          $maxCat = (int)($categories[0]['cnt'] ?? 1); ?>
        <?php foreach ($categories as $c): ?>
          <div class="bar-row">
            <div class="bar-label">
              <span class="dot" style="background:<?= htmlspecialchars($c['category_color']) ?>"></span>
              <?= htmlspecialchars($c['category']) ?>
            </div>
            <div class="bar-track"><div class="bar-fill" style="width:<?= round((int)$c['cnt']/$maxCat*100) ?>%;background:<?= htmlspecialchars($c['category_color']) ?>"></div></div>
            <div class="bar-val"><?= fmtN((int)$c['cnt']) ?></div>
          </div>
        <?php endforeach; ?>
      <?php else: ?><p style="color:#94a3b8;font-size:11px">Sin bloqueos</p><?php endif; ?>
    </div>

  </div>

  <!-- Recent log -->
  <div class="section-title" style="margin-top:16px">Últimas 100 consultas registradas</div>
  <table>
    <thead><tr>
      <th style="width:130px">Fecha/Hora</th>
      <th>Dominio</th>
      <th style="width:50px">Tipo</th>
      <th style="width:90px">Estado</th>
      <th style="width:120px">Categoría</th>
      <?php if ($isAdmin): ?><th style="width:110px">Cliente</th><?php endif; ?>
      <th>Lista</th>
    </tr></thead>
    <tbody>
    <?php foreach ($logEntries as $r):
        $isBlk = str_starts_with($r['reason'], 'Filtered');
        $badgeCls = $isBlk ? 'badge-danger' : 'badge-success';
        if ($r['reason'] === 'NotFilteredNotFound') $badgeCls = 'badge-secondary'; ?>
      <tr>
        <td style="font-size:10px;white-space:nowrap"><?= htmlspecialchars(substr($r['log_time'],0,16)) ?></td>
        <td style="font-size:11px"><?= htmlspecialchars($r['domain']) ?></td>
        <td><span class="badge badge-secondary"><?= htmlspecialchars($r['query_type'] ?? 'A') ?></span></td>
        <td><span class="badge <?= $badgeCls ?>"><?= reasonLabel($r['reason']) ?></span></td>
        <td style="font-size:10px">
          <?php if ($r['category']): ?>
            <span class="dot" style="background:<?= htmlspecialchars($r['category_color']) ?>"></span><?= htmlspecialchars($r['category']) ?>
          <?php else: ?>–<?php endif; ?>
        </td>
        <?php if ($isAdmin): ?><td style="font-size:10px"><?= htmlspecialchars($r['client_name'] ?? '') ?></td><?php endif; ?>
        <td style="font-size:10px;color:#64748b"><?= htmlspecialchars(substr($r['filter_name'] ?? '', 0, 30)) ?: '–' ?></td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table>

  <div class="footer">
    ZeroTrust Shield by PCASSI · Informe generado el <?= $generatedAt ?> · <?= $periodLabel ?>
  </div>

</div>
</body>
</html>
