<?php
// Relatório de Falhas — HTML otimizado para impressão/salvar como 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(365, (int)($_GET['days'] ?? 30)));

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

// Uptime geral no período
$statsStmt = $pdo->prepare("
    SELECT COUNT(*) AS total,
           SUM(CASE WHEN status='online' THEN 1 ELSE 0 END) AS on_count
    FROM ping_logs
    WHERE monitored_ip_id = ? AND checked_at >= NOW() - ? * INTERVAL '1 day'
");
$statsStmt->execute([$ipId, $days]);
$stats = $statsStmt->fetch();
$totalChecks  = (int)($stats['total'] ?? 0);
$onCount      = (int)($stats['on_count'] ?? 0);
$uptimePct    = $totalChecks > 0 ? round($onCount / $totalChecks * 100, 3) : null;

// Incidentes de latência alta no período
$latThreshold = (int)($ipRow['latency_alert_ms'] ?? 0);
$latIncidents = [];
$latStatsRow  = null;
if ($latThreshold > 0) {
    $latStmt = $pdo->prepare("
        SELECT id, started_at, recovered_at, duration_seconds,
               peak_latency_ms, checks_above_threshold, threshold_ms
        FROM latency_incidents
        WHERE monitored_ip_id = ? AND started_at >= NOW() - ? * INTERVAL '1 day'
        ORDER BY started_at DESC
        LIMIT 500
    ");
    $latStmt->execute([$ipId, $days]);
    $latIncidents = $latStmt->fetchAll();

    $latStatStmt = $pdo->prepare("
        SELECT COUNT(*) AS total,
               AVG(peak_latency_ms)::INT AS avg_ms,
               MAX(peak_latency_ms) AS max_ms,
               SUM(COALESCE(duration_seconds, 0)) AS total_dur_sec
        FROM latency_incidents
        WHERE monitored_ip_id = ? AND started_at >= NOW() - ? * INTERVAL '1 day'
    ");
    $latStatStmt->execute([$ipId, $days]);
    $latStatsRow = $latStatStmt->fetch();
}

// Transições de status → lista de incidentes
$transStmt = $pdo->prepare("
    WITH logs AS (
        SELECT checked_at, status,
               LAG(status) OVER (ORDER BY checked_at) AS prev_status
        FROM ping_logs
        WHERE monitored_ip_id = ? AND checked_at >= NOW() - ? * INTERVAL '1 day'
    )
    SELECT checked_at::TEXT, status FROM logs
    WHERE status IS DISTINCT FROM prev_status
    ORDER BY checked_at LIMIT 2000
");
$transStmt->execute([$ipId, $days]);
$transitions = $transStmt->fetchAll();

$incidents       = [];
$totalDownSec    = 0;
$pendingStart    = null;
$pendingStartRaw = null;

foreach ($transitions as $t) {
    if ($t['status'] === 'offline') {
        $pendingStart    = $t['checked_at'];
        $pendingStartRaw = $t['checked_at'];
    } elseif ($t['status'] === 'online' && $pendingStart !== null) {
        try {
            $startDt = new DateTimeImmutable($pendingStart);
            $endDt   = new DateTimeImmutable($t['checked_at']);
            $dur     = max(0, $endDt->getTimestamp() - $startDt->getTimestamp());
            $totalDownSec += $dur;
            $incidents[] = [
                'start'    => $startDt->setTimezone($tz)->format('d/m/Y H:i:s'),
                'end'      => $endDt->setTimezone($tz)->format('d/m/Y H:i:s'),
                'duration' => $dur,
                'open'     => false,
            ];
        } catch (Throwable) {}
        $pendingStart = null;
    }
}
if ($pendingStart !== null) {
    try {
        $startDt = new DateTimeImmutable($pendingStart);
        $dur = max(0, time() - $startDt->getTimestamp());
        $totalDownSec += $dur;
        $incidents[] = [
            'start'    => $startDt->setTimezone($tz)->format('d/m/Y H:i:s'),
            'end'      => null,
            'duration' => $dur,
            'open'     => true,
        ];
    } catch (Throwable) {}
}

// Ordena: mais recentes primeiro
$incidents = array_reverse($incidents);

function fmtDur(int $sec): string {
    if ($sec < 60)   return $sec . 's';
    if ($sec < 3600) return round($sec / 60) . ' min';
    $h = intdiv($sec, 3600);
    $m = intdiv($sec % 3600, 60);
    return $m > 0 ? "{$h}h {$m}min" : "{$h}h";
}

$geradoEm   = (new DateTimeImmutable('now', $tz))->format('d/m/Y H:i:s');
$totalInc   = count($incidents);
$totalDownFmt = $totalDownSec > 0 ? fmtDur($totalDownSec) : '0';
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Relatório de Falhas — <?= 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; }

.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: #dc2626; 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; }

.report-header {
    border-bottom: 3px solid #dc2626;
    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; }

.stats { display: flex; gap: 12px; margin-bottom: 20px; flex-wrap: wrap; }
.stat-card {
    flex: 1; min-width: 130px;
    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; }
.stat-amber { color: #92400e; border-color: #fde68a; background: #fffbeb; }

.section-title {
    font-size: 13px; font-weight: 800; color: #0f172a;
    margin-bottom: 10px; padding-bottom: 6px;
    border-bottom: 2px solid #f1f5f9;
    display: flex; align-items: center; gap: 6px;
}

table { width: 100%; border-collapse: collapse; font-size: 10.5px; }
thead tr { background: #7f1d1d; color: #fff; }
thead th { padding: 9px 12px; text-align: left; font-weight: 700; font-size: 9px; text-transform: uppercase; letter-spacing: .06em; }
tbody tr:nth-child(even) { background: #fef9f9; }
tbody tr.open-row { background: #fff1f2; }
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-closed  { background: #dcfce7; color: #16a34a; }
.badge-open    { background: #fee2e2; color: #dc2626; }
.badge-long    { background: #fef3c7; color: #92400e; }

.no-incidents {
    text-align: center; padding: 40px 20px;
    color: #16a34a; font-size: 14px; font-weight: 700;
    background: #f0fdf4; border-radius: 10px; border: 1px solid #86efac;
}

.lat-stats { display: flex; gap: 12px; margin-bottom: 14px; flex-wrap: wrap; }
.lat-stat  { flex:1; min-width:120px; border-radius:8px; padding:10px 14px; text-align:center; }
.lat-stat .val { font-size:18px; font-weight:900; }
.lat-stat .lbl { font-size:9px; font-weight:700; text-transform:uppercase; letter-spacing:.05em; color:#92400e; margin-top:2px; }

table.lat-table thead tr { background: #92400e; color:#fff; }
table.lat-table tbody tr:nth-child(even) { background:#fffbeb; }
.badge-lat { display:inline-block; padding:2px 8px; border-radius:20px; font-size:9px; font-weight:700; background:#fee2e2; color:#b91c1c; }

.report-footer {
    margin-top: 28px;
    padding: 16px 20px;
    background: #1e293b;
    border-radius: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px;
    font-size: 12px;
    color: #94a3b8;
}

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

<div class="print-bar">
    <div style="font-size:13px;font-weight:700;">
        🚨 Relatório de Falhas: <?= htmlspecialchars($ipRow['label']) ?> · <?= $days ?> dias
    </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">

    <div class="report-header">
        <div>
            <div class="report-title">🚨 Relatório de Falhas</div>
            <div class="report-sub">
                <strong><?= htmlspecialchars($ipRow['label']) ?></strong>
                &nbsp;·&nbsp;
                <code style="background:#fff1f2;color:#dc2626;padding:2px 6px;border-radius:4px;font-size:11px;"><?= htmlspecialchars($ipRow['host']) ?></code>
                &nbsp;·&nbsp; Período: últimos <?= $days ?> dias
            </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 <?= $uptimePct !== null && $uptimePct >= 99 ? 'stat-green' : 'stat-red' ?>">
            <div class="stat-value"><?= $uptimePct !== null ? $uptimePct . '%' : '—' ?></div>
            <div class="stat-label">Disponibilidade</div>
        </div>
        <div class="stat-card <?= $totalInc === 0 ? 'stat-green' : 'stat-red' ?>">
            <div class="stat-value"><?= $totalInc ?></div>
            <div class="stat-label">Incidentes</div>
        </div>
        <div class="stat-card <?= $totalDownSec === 0 ? 'stat-green' : 'stat-amber' ?>">
            <div class="stat-value" style="font-size:<?= strlen($totalDownFmt) > 5 ? '16px' : '22px' ?>;"><?= htmlspecialchars($totalDownFmt) ?></div>
            <div class="stat-label">Tempo Offline</div>
        </div>
        <div class="stat-card stat-gray">
            <div class="stat-value"><?= $totalChecks ?></div>
            <div class="stat-label">Checks no período</div>
        </div>
        <div class="stat-card stat-blue">
            <div class="stat-value"><?= $days ?>d</div>
            <div class="stat-label">Período analisado</div>
        </div>
    </div>

    <!-- Tabela de incidentes -->
    <div class="section-title">🔴 Histórico de Incidentes</div>

    <?php if (empty($incidents)): ?>
    <div class="no-incidents">
        ✅ Nenhum incidente registrado nos últimos <?= $days ?> dias!
    </div>
    <?php else: ?>
    <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Início da Queda</th>
                <th>Recuperação</th>
                <th>Duração</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($incidents as $idx => $inc):
            $isOpen  = $inc['open'];
            $isLong  = !$isOpen && $inc['duration'] > 3600; // > 1h
        ?>
        <tr class="<?= $isOpen ? 'open-row' : '' ?>">
            <td style="color:#94a3b8;font-size:9px;"><?= $totalInc - $idx ?></td>
            <td style="font-family:monospace;color:#dc2626;font-weight:700;"><?= htmlspecialchars($inc['start']) ?></td>
            <td style="font-family:monospace;color:<?= $isOpen ? '#dc2626' : '#16a34a' ?>;">
                <?= $isOpen ? '<em>Em andamento</em>' : htmlspecialchars($inc['end']) ?>
            </td>
            <td style="font-weight:700;color:<?= $isLong ? '#92400e' : ($isOpen ? '#dc2626' : '#475569') ?>;">
                <?= htmlspecialchars(fmtDur($inc['duration'])) ?>
                <?= $isOpen ? ' (estimado)' : '' ?>
            </td>
            <td>
                <?php if ($isOpen): ?>
                    <span class="badge badge-open">Em andamento</span>
                <?php elseif ($isLong): ?>
                    <span class="badge badge-long">Queda longa</span>
                <?php else: ?>
                    <span class="badge badge-closed">Recuperado</span>
                <?php endif; ?>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>

    <!-- Seção de Incidentes de Latência Alta -->
    <?php if ($latThreshold > 0): ?>
    <div style="margin-top:28px;">
        <div class="section-title">⚠️ Incidentes de Latência Alta</div>

        <?php if ($latStatsRow && (int)$latStatsRow['total'] > 0): ?>
        <div class="lat-stats">
            <div class="lat-stat" style="background:#fff7ed;border:1px solid #fed7aa;">
                <div class="val" style="color:#c2410c;"><?= (int)$latStatsRow['total'] ?></div>
                <div class="lbl">Incidentes</div>
            </div>
            <div class="lat-stat" style="background:#fefce8;border:1px solid #fde68a;">
                <div class="val" style="color:#92400e;"><?= (int)$latStatsRow['avg_ms'] ?> ms</div>
                <div class="lbl">Pico médio</div>
            </div>
            <div class="lat-stat" style="background:#fef2f2;border:1px solid #fca5a5;">
                <div class="val" style="color:#b91c1c;"><?= (int)$latStatsRow['max_ms'] ?> ms</div>
                <div class="lbl">Pico máximo</div>
            </div>
            <div class="lat-stat" style="background:#f8fafc;border:1px solid #e2e8f0;">
                <div class="val" style="color:#475569;"><?= $latThreshold ?> ms</div>
                <div class="lbl">Limiar</div>
            </div>
        </div>

        <?php if (!empty($latIncidents)): ?>
        <table class="lat-table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Início</th>
                    <th>Recuperação</th>
                    <th>Duração</th>
                    <th>Pico</th>
                    <th>Checks</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($latIncidents as $idx => $inc):
                $isOpen  = $inc['recovered_at'] === null;
                $startDt = (new DateTimeImmutable($inc['started_at']))->setTimezone($tz)->format('d/m/Y H:i:s');
                $endDt   = $isOpen ? null : (new DateTimeImmutable($inc['recovered_at']))->setTimezone($tz)->format('d/m/Y H:i:s');
                $durSec  = $isOpen
                    ? (time() - strtotime($inc['started_at']))
                    : (int)$inc['duration_seconds'];
                $durFmt  = $durSec < 60 ? "{$durSec}s"
                         : ($durSec < 3600 ? round($durSec / 60) . ' min'
                         : intdiv($durSec, 3600) . 'h ' . intdiv($durSec % 3600, 60) . 'min');
            ?>
            <tr>
                <td style="color:#94a3b8;font-size:9px;"><?= count($latIncidents) - $idx ?></td>
                <td style="font-family:monospace;color:#92400e;font-weight:700;"><?= $startDt ?></td>
                <td style="font-family:monospace;color:<?= $isOpen ? '#dc2626' : '#16a34a' ?>;">
                    <?= $isOpen ? '<em>Em andamento</em>' : $endDt ?>
                </td>
                <td style="font-weight:700;color:<?= $isOpen ? '#dc2626' : '#475569' ?>;">
                    <?= $durFmt ?><?= $isOpen ? '*' : '' ?>
                </td>
                <td style="font-weight:900;color:#b91c1c;"><?= (int)$inc['peak_latency_ms'] ?> ms</td>
                <td style="color:#64748b;"><?= (int)$inc['checks_above_threshold'] ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php if (count($latIncidents) >= 500): ?>
            <p style="font-size:9px;color:#94a3b8;margin-top:6px;">* Exibindo os 500 incidentes mais recentes do período.</p>
        <?php endif; ?>
        <?php endif; ?>

        <?php else: ?>
        <div class="no-incidents">
            ✅ Nenhum incidente de latência alta registrado nos últimos <?= $days ?> dias!
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <div class="report-footer">
        <div style="display:flex; align-items:center; gap:10px;">
            <span style="font-size:15px; font-weight:800; color:#f1f5f9; letter-spacing:-0.01em;">MonitorPing</span>
            <span style="color:#475569;">·</span>
            <span style="color:#cbd5e1; font-size:12px;">Relatório de Falhas</span>
        </div>
        <div style="display:flex; gap:16px; align-items:center; flex-wrap:wrap;">
            <span style="background:rgba(255,255,255,0.07); padding:4px 12px; border-radius:20px; font-size:11px; color:#94a3b8;">
                🖥️ <?= htmlspecialchars($ipRow['host']) ?>
            </span>
            <span style="background:rgba(255,255,255,0.07); padding:4px 12px; border-radius:20px; font-size:11px; color:#94a3b8;">
                📅 <?= $days ?> dias
            </span>
            <span style="background:rgba(220,38,38,0.2); padding:4px 12px; border-radius:20px; font-size:11px; color:#fca5a5; font-weight:700;">
                🚨 <?= $totalInc ?> incidente(s)
            </span>
            <span style="color:#475569; font-size:11px;">Gerado em <?= $geradoEm ?></span>
        </div>
    </div>

</div>

<script>
window.addEventListener('load', function() {
    setTimeout(function() { window.print(); }, 400);
});
</script>
</body>
</html>
