<?php
require_once __DIR__ . '/../includes/header.php';
$pdo = db();

// Dashboard de SLA mensal — últimos 6 meses por host
$months = 6;

// Hosts do usuário
$hosts = $pdo->prepare("SELECT id, label, host FROM monitored_ips WHERE user_id = ? AND active = TRUE ORDER BY label ASC");
$hosts->execute([$user['id']]);
$hosts = $hosts->fetchAll();

// Gera os últimos N meses
$monthList = [];
for ($i = $months - 1; $i >= 0; $i--) {
    $dt = new DateTimeImmutable("first day of -{$i} month");
    $monthList[] = [
        'key'   => $dt->format('Y-m'),
        'label' => mb_strtoupper($dt->format('M/y')),
        'start' => $dt->format('Y-m-01 00:00:00'),
        'end'   => $dt->modify('last day of this month')->format('Y-m-t 23:59:59'),
    ];
}

// Busca uptime por host por mês
$slaData = [];
if ($hosts) {
    $ipIds = array_column($hosts, 'id');
    $ph = implode(',', array_fill(0, count($ipIds), '?'));
    $slaStmt = $pdo->prepare("
        SELECT
            monitored_ip_id,
            to_char(date_trunc('month', checked_at AT TIME ZONE 'UTC'), 'YYYY-MM') AS month,
            ROUND(100.0 * SUM(CASE WHEN status='online' THEN 1 ELSE 0 END) / NULLIF(COUNT(*),0), 3) AS uptime_pct,
            ROUND(AVG(latency_ms) FILTER (WHERE status='online'), 1) AS avg_latency,
            COUNT(*) AS total_checks,
            SUM(CASE WHEN status='offline' THEN 1 ELSE 0 END) AS offline_count
        FROM ping_logs
        WHERE monitored_ip_id IN ({$ph})
          AND checked_at >= NOW() - INTERVAL '{$months} months'
        GROUP BY monitored_ip_id, month
        ORDER BY month
    ");
    $slaStmt->execute($ipIds);
    foreach ($slaStmt->fetchAll() as $row) {
        $slaData[$row['monitored_ip_id']][$row['month']] = $row;
    }
}

function sla_color(float $pct): string {
    if ($pct >= 99.9) return '#22c55e';
    if ($pct >= 99.0) return '#84cc16';
    if ($pct >= 95.0) return '#f59e0b';
    if ($pct >= 90.0) return '#f97316';
    return '#ef4444';
}
function sla_label(float $pct): string {
    if ($pct >= 99.9) return 'Excelente';
    if ($pct >= 99.0) return 'Bom';
    if ($pct >= 95.0) return 'Atenção';
    if ($pct >= 90.0) return 'Crítico';
    return 'Falha';
}
?>

<div class="card">
    <div class="card-head">
        <div>
            <h2>📊 SLA — Uptime Mensal</h2>
            <p>Histórico de disponibilidade por host nos últimos <?php echo $months; ?> meses.</p>
        </div>
        <div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
            <span style="font-size:12px;font-weight:600;">Legenda:</span>
            <?php foreach ([['#22c55e','≥99.9%'],['#84cc16','≥99%'],['#f59e0b','≥95%'],['#f97316','≥90%'],['#ef4444','<90%']] as [$c,$l]): ?>
            <span style="display:inline-flex;align-items:center;gap:4px;font-size:12px;">
                <span style="width:12px;height:12px;border-radius:3px;background:<?php echo $c; ?>;display:inline-block;"></span>
                <?php echo $l; ?>
            </span>
            <?php endforeach; ?>
        </div>
    </div>

    <?php if (empty($hosts)): ?>
        <div style="text-align:center;padding:40px;color:var(--text-secondary);">
            <div style="font-size:48px;margin-bottom:12px;">📊</div>
            <p>Nenhum host monitorado ainda.</p>
        </div>
    <?php else: ?>
        <div style="overflow-x:auto;">
            <table style="min-width:700px;">
                <thead>
                    <tr>
                        <th style="text-align:left;min-width:180px;">Host</th>
                        <?php foreach ($monthList as $m): ?>
                        <th style="text-align:center;min-width:90px;"><?php echo h($m['label']); ?></th>
                        <?php endforeach; ?>
                        <th style="text-align:center;">Média</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($hosts as $host):
                        $avgPct = null;
                        $avgCount = 0;
                        $avgSum = 0;
                    ?>
                    <tr>
                        <td>
                            <div style="font-weight:600;font-size:14px;"><?php echo h($host['label']); ?></div>
                            <div style="font-size:11px;color:var(--text-secondary);"><?php echo h($host['host']); ?></div>
                        </td>
                        <?php foreach ($monthList as $m):
                            $entry = $slaData[$host['id']][$m['key']] ?? null;
                            $pct   = $entry ? (float)$entry['uptime_pct'] : null;
                            if ($pct !== null) { $avgSum += $pct; $avgCount++; }
                            $bg    = $pct !== null ? sla_color($pct) : 'var(--border)';
                            $label = $pct !== null ? number_format($pct, 2) . '%' : '—';
                            $title = $pct !== null ? "Uptime: {$label}\nChecks: {$entry['total_checks']}\nOfflines: {$entry['offline_count']}\nLatência média: {$entry['avg_latency']} ms" : 'Sem dados';
                        ?>
                        <td style="text-align:center;padding:6px;">
                            <div title="<?php echo h($title); ?>"
                                 style="background:<?php echo $bg; ?>;color:#fff;border-radius:8px;padding:6px 4px;font-size:12px;font-weight:700;cursor:default;min-width:72px;display:inline-block;">
                                <?php echo $label; ?>
                            </div>
                            <?php if ($pct !== null): ?>
                            <div style="font-size:10px;color:var(--text-secondary);margin-top:2px;"><?php echo sla_label($pct); ?></div>
                            <?php endif; ?>
                        </td>
                        <?php endforeach; ?>
                        <td style="text-align:center;">
                            <?php if ($avgCount > 0):
                                $avg = $avgSum / $avgCount;
                            ?>
                            <div style="background:<?php echo sla_color($avg); ?>;color:#fff;border-radius:8px;padding:6px 4px;font-size:13px;font-weight:700;display:inline-block;min-width:72px;">
                                <?php echo number_format($avg, 2); ?>%
                            </div>
                            <?php else: ?>
                            <span style="color:var(--text-secondary);">—</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- SLA Overview Cards -->
        <?php
        $totalUp = 0; $totalChecks = 0;
        foreach ($slaData as $ipId => $months_data) {
            foreach ($months_data as $m => $d) {
                $totalUp += (int)$d['online_count'] ?? 0;
                $totalChecks += (int)$d['total_checks'];
            }
        }
        $overallSla = $totalChecks > 0 ? round(100 * $totalUp / $totalChecks, 3) : null;
        ?>
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px;margin-top:24px;">
            <div class="stats-card">
                <small>SLA Global (<?php echo $months; ?> meses)</small>
                <strong style="color:<?php echo $overallSla !== null ? sla_color($overallSla) : 'var(--text-secondary)'; ?>;">
                    <?php echo $overallSla !== null ? number_format($overallSla, 3) . '%' : '—'; ?>
                </strong>
                <p>Todos os hosts combinados</p>
            </div>
            <div class="stats-card">
                <small>Total de Checks</small>
                <strong><?php echo number_format($totalChecks); ?></strong>
                <p>Nos últimos <?php echo $months; ?> meses</p>
            </div>
            <div class="stats-card">
                <small>Hosts monitorados</small>
                <strong><?php echo count($hosts); ?></strong>
                <p>Hosts ativos</p>
            </div>
        </div>

        <div style="margin-top:16px;padding:12px 16px;background:var(--bg-main);border-radius:10px;border:1px solid var(--border);font-size:13px;color:var(--text-secondary);">
            💡 <strong>Dica:</strong> Passe o mouse sobre os valores mensais para ver detalhes de checks e latência.
            Use <strong>Janelas de Manutenção</strong> para excluir períodos planejados do cálculo de SLA.
        </div>
    <?php endif; ?>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
