<?php
// Relatório PDF — renderiza HTML limpo para impressão/save as PDF
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../config.php';

require_login();
$user = current_user();
$pdo  = db();

$ipId   = (int)($_GET['ip_id'] ?? 0);
$days   = max(1, min(90, (int)($_GET['days'] ?? 7)));
$status = in_array($_GET['status'] ?? '', ['online','offline']) ? $_GET['status'] : 'all';

if (!$ipId) { http_response_code(400); echo 'IP não informado.'; exit; }

$ipStmt = $pdo->prepare("SELECT * FROM monitored_ips WHERE id = ? AND user_id = ?");
$ipStmt->execute([$ipId, $user['id']]);
$ipRow = $ipStmt->fetch();
if (!$ipRow) { http_response_code(403); echo 'Acesso negado.'; exit; }

$tz = new DateTimeZone(in_array($user['timezone'] ?? '', timezone_identifiers_list(), true) ? $user['timezone'] : 'America/Sao_Paulo');

// Query
$sql = "SELECT checked_at, status, latency_ms FROM ping_logs
        WHERE monitored_ip_id = ? AND checked_at >= NOW() - ? * INTERVAL '1 day'";
$params = [$ipId, $days];
if ($status !== 'all') { $sql .= " AND status = ?"; $params[] = $status; }
$sql .= " ORDER BY checked_at DESC";
$rows = $pdo->prepare($sql);
$rows->execute($params);
$logs = $rows->fetchAll();

// Stats
$total   = count($logs);
$online  = count(array_filter($logs, fn($r) => $r['status'] === 'online'));
$offline = $total - $online;
$uptime  = $total > 0 ? round($online / $total * 100, 2) : 0;
$avgLat  = $total > 0 ? round(array_sum(array_filter(array_column($logs, 'latency_ms'), fn($v) => $v !== null)) / max(1, count(array_filter($logs, fn($r) => $r['latency_ms'] !== null))), 1) : null;

$statusLabel = $status !== 'all' ? ' · Filtro: ' . strtoupper($status) : '';
$geradoEm    = (new DateTimeImmutable('now', $tz))->format('d/m/Y H:i:s');
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Relatório — <?= htmlspecialchars($ipRow['label']) ?> — <?= $days ?>d</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Segoe UI', Arial, sans-serif; font-size: 11px; color: #1e293b; background: #fff; }

/* Botão de imprimir — some na impressão */
.print-bar {
    position: fixed; top: 0; left: 0; right: 0;
    background: #1e293b; color: #fff;
    display: flex; align-items: center; justify-content: space-between;
    padding: 10px 24px; gap: 12px; z-index: 999;
}
.print-bar button {
    padding: 8px 20px; border-radius: 8px; border: none; cursor: pointer;
    font-weight: 700; font-size: 13px;
}
.btn-pdf   { background: #ea580c; color: #fff; }
.btn-close { background: rgba(255,255,255,.12); color: #fff; }

.content { margin-top: 52px; padding: 24px 28px; max-width: 900px; margin-left: auto; margin-right: auto; }

/* Cabeçalho do relatório */
.report-header {
    border-bottom: 3px solid #ea580c;
    padding-bottom: 16px; margin-bottom: 20px;
    display: flex; justify-content: space-between; align-items: flex-end; flex-wrap: wrap; gap: 10px;
}
.report-title { font-size: 20px; font-weight: 800; color: #0f172a; }
.report-sub   { font-size: 12px; color: #64748b; margin-top: 4px; }
.report-meta  { text-align: right; font-size: 10px; color: #94a3b8; line-height: 1.6; }

/* Cards de resumo */
.stats { display: flex; gap: 12px; margin-bottom: 20px; flex-wrap: wrap; }
.stat-card {
    flex: 1; min-width: 120px;
    border: 1px solid #e2e8f0; border-radius: 10px;
    padding: 12px 16px; text-align: center;
}
.stat-value { font-size: 22px; font-weight: 900; }
.stat-label { font-size: 9px; font-weight: 700; text-transform: uppercase; letter-spacing: .05em; color: #64748b; margin-top: 3px; }
.stat-green { color: #16a34a; border-color: #86efac; background: #f0fdf4; }
.stat-red   { color: #dc2626; border-color: #fca5a5; background: #fef2f2; }
.stat-blue  { color: #2563eb; border-color: #93c5fd; background: #eff6ff; }
.stat-gray  { color: #475569; border-color: #e2e8f0; background: #f8fafc; }

/* Tabela */
.log-table { width: 100%; border-collapse: collapse; font-size: 10.5px; }
.log-table thead tr { background: #1e293b; color: #fff; }
.log-table thead th { padding: 9px 12px; text-align: left; font-weight: 700; font-size: 9px; text-transform: uppercase; letter-spacing: .06em; }
.log-table tbody tr:nth-child(even) { background: #f8fafc; }
.log-table tbody tr.offline-row { background: #fff5f5; border-left: 3px solid #ef4444; }
.log-table tbody td { padding: 7px 12px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; }
.badge { display: inline-block; padding: 2px 8px; border-radius: 20px; font-size: 9px; font-weight: 700; text-transform: uppercase; }
.badge-on  { background: #dcfce7; color: #16a34a; }
.badge-off { background: #fee2e2; color: #dc2626; }

/* Footer */
.report-footer { margin-top: 20px; padding-top: 12px; border-top: 1px solid #e2e8f0; display: flex; justify-content: space-between; font-size: 9px; color: #94a3b8; }

@media print {
    .print-bar { display: none !important; }
    .content { margin-top: 0 !important; padding: 16px !important; }
    body { font-size: 10px; }
    .log-table { page-break-inside: auto; }
    .log-table tr { page-break-inside: avoid; page-break-after: auto; }
    .log-table thead { display: table-header-group; }
    @page { margin: 15mm; size: A4; }
}
</style>
</head>
<body>

<!-- Barra de ação (some na impressão) -->
<div class="print-bar">
    <div style="font-size:13px;font-weight:700;">
        📄 Relatório: <?= htmlspecialchars($ipRow['label']) ?> · <?= $days ?> dias<?= htmlspecialchars($statusLabel) ?>
    </div>
    <div style="display:flex;gap:8px;">
        <button class="btn-pdf" onclick="window.print()">🖨️ Salvar como PDF / Imprimir</button>
        <button class="btn-close" onclick="window.close()">✕ Fechar</button>
    </div>
</div>

<div class="content">

    <!-- Cabeçalho -->
    <div class="report-header">
        <div>
            <div class="report-title">📊 Relatório de Monitoramento</div>
            <div class="report-sub">
                <strong><?= htmlspecialchars($ipRow['label']) ?></strong>
                &nbsp;·&nbsp;
                <code style="background:#fff7ed;color:#ea580c;padding:2px 6px;border-radius:4px;font-size:11px;"><?= htmlspecialchars($ipRow['host']) ?></code>
                &nbsp;·&nbsp; Período: últimos <?= $days ?> dias
                <?= $statusLabel ?>
            </div>
        </div>
        <div class="report-meta">
            Gerado em: <?= $geradoEm ?><br>
            Fuso: <?= $tz->getName() ?><br>
            MonitorPing
        </div>
    </div>

    <!-- Resumo -->
    <div class="stats">
        <div class="stat-card stat-gray">
            <div class="stat-value"><?= $total ?></div>
            <div class="stat-label">Total de Registros</div>
        </div>
        <div class="stat-card stat-green">
            <div class="stat-value"><?= $online ?></div>
            <div class="stat-label">Online</div>
        </div>
        <div class="stat-card stat-red">
            <div class="stat-value"><?= $offline ?></div>
            <div class="stat-label">Quedas</div>
        </div>
        <div class="stat-card stat-blue">
            <div class="stat-value"><?= $uptime ?>%</div>
            <div class="stat-label">Disponibilidade</div>
        </div>
        <?php if ($avgLat !== null): ?>
        <div class="stat-card stat-gray">
            <div class="stat-value" style="font-size:18px;"><?= $avgLat ?> ms</div>
            <div class="stat-label">Latência Média</div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Tabela -->
    <table class="log-table">
        <thead>
            <tr>
                <th>#</th>
                <th>Data / Hora</th>
                <th>Status</th>
                <th style="text-align:right;">Latência (ms)</th>
                <th>Avaliação</th>
            </tr>
        </thead>
        <tbody>
        <?php if (empty($logs)): ?>
            <tr><td colspan="5" style="text-align:center;padding:20px;color:#94a3b8;">Nenhum registro encontrado.</td></tr>
        <?php else: ?>
            <?php foreach ($logs as $i => $log):
                $isOff = $log['status'] === 'offline';
                $dt    = $log['checked_at'] ? (new DateTimeImmutable($log['checked_at']))->setTimezone($tz)->format('d/m/Y H:i:s') : '—';
                $lat   = $log['latency_ms'];
                if ($isOff)          { $av = 'Queda';         $avColor = '#dc2626'; }
                elseif ($lat === null){ $av = 'Timeout';       $avColor = '#94a3b8'; }
                elseif ($lat > 200)  { $av = 'Latência Alta'; $avColor = '#dc2626'; }
                elseif ($lat > 100)  { $av = 'Lat. Média';    $avColor = '#ca8a04'; }
                else                 { $av = 'Ótimo';          $avColor = '#16a34a'; }
            ?>
            <tr class="<?= $isOff ? 'offline-row' : '' ?>">
                <td style="color:#94a3b8;font-size:9px;"><?= $total - $i ?></td>
                <td style="font-family:monospace;"><?= $dt ?></td>
                <td><span class="badge <?= $isOff ? 'badge-off' : 'badge-on' ?>"><?= $isOff ? 'OFFLINE' : 'ONLINE' ?></span></td>
                <td style="text-align:right;font-weight:700;color:<?= $isOff ? '#dc2626' : ($lat > 200 ? '#dc2626' : ($lat > 100 ? '#ca8a04' : '#16a34a')) ?>;">
                    <?= $lat !== null ? $lat . ' ms' : '<span style="color:#94a3b8;">—</span>' ?>
                </td>
                <td style="color:<?= $avColor ?>;font-weight:700;"><?= $av ?></td>
            </tr>
            <?php endforeach; ?>
        <?php endif; ?>
        </tbody>
    </table>

    <div class="report-footer">
        <span>MonitorPing · Relatório gerado em <?= $geradoEm ?></span>
        <span><?= $total ?> registro(s) · <?= $days ?> dias · <?= htmlspecialchars($ipRow['host']) ?></span>
    </div>

</div>

<script>
// Abre o diálogo de impressão automaticamente após carregar
window.addEventListener('load', function() {
    // Pequeno delay para garantir renderização
    setTimeout(function() { window.print(); }, 400);
});
</script>
</body>
</html>
