<?php
require_once __DIR__ . '/../includes/header.php';
$pdo = db();
$ipId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$stmt = $pdo->prepare("SELECT * FROM monitored_ips WHERE id = ? AND user_id = ?");
$stmt->execute([$ipId, $user['id']]);
$ip = $stmt->fetch();

if (!$ip) {
    echo "<div class='card'><h2>IP não encontrado</h2><p>Verifique o link e tente novamente.</p></div>";
    require_once __DIR__ . '/../includes/footer.php';
    exit;
}

$channels = get_alert_channels($ip['id']) ?: [];
$emailChannels = array_values(array_filter($channels, static function ($channel) {
    return isset($channel['type']) && $channel['type'] === 'email';
}));
$testAlertSuccess = null;
$testAlertMessage = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'test_alert') {
    if (!csrf_check($_POST['csrf_token'] ?? null)) {
        $testAlertSuccess = false;
        $testAlertMessage = 'CSRF inválido.';
    } elseif (!rate_limit_check('test_alert_email_' . $user['id'], 60)) {
        $testAlertSuccess = false;
        $testAlertMessage = 'Aguarde alguns segundos antes de novo teste.';
    } else {
        $channelId = isset($_POST['channel_id']) ? (int)$_POST['channel_id'] : 0;
        $selectedChannel = null;
        foreach ($emailChannels as $channel) {
            if ((int)($channel['id'] ?? 0) === $channelId) {
                $selectedChannel = $channel;
            break;
        }
    }

    if (!$selectedChannel) {
        $testAlertSuccess = false;
        $testAlertMessage = 'Selecione um canal de e-mail válido para o teste.';
    } else {
        $testIp = $ip;
        $testIp['label'] = ($ip['label'] ?? 'Canal monitorado') . ' (Teste)';
        $content = build_alert_email_content($testIp, 'offline', null, get_user_name($pdo, (int)$ip['user_id']));
        $errorMsg = null;
        if (send_email_message($selectedChannel['target'], $content['subject'], $content['text'], $errorMsg, $content['html'])) {
            $testAlertSuccess = true;
            $testAlertMessage = "Alerta de teste enviado para {$selectedChannel['target']}.";
        } else {
            $testAlertSuccess = false;
            $testAlertMessage = $errorMsg ?: 'Falha ao enviar alerta de teste.';
        }
    }
}
}

$recentAlertsStmt = $pdo->prepare("
    SELECT a.type, a.status, a.error_message, a.sent_at, COALESCE(c.target, mi.alert_email) AS target
    FROM alerts_sent a
    LEFT JOIN alert_channels c ON c.id = a.channel_id
    LEFT JOIN monitored_ips mi ON mi.id = a.monitored_ip_id
    WHERE a.monitored_ip_id = ?
    ORDER BY a.sent_at DESC
    LIMIT 3
");
$recentAlertsStmt->execute([$ip['id']]);
$recentAlerts = $recentAlertsStmt->fetchAll();

$summary24Stmt = $pdo->prepare("
    SELECT 
        COUNT(*) AS total,
        SUM(CASE WHEN status='online' THEN 1 ELSE 0 END) AS on_count,
        AVG(latency_ms) AS avg_latency,
        MIN(latency_ms) AS min_latency,
        MAX(latency_ms) AS max_latency
    FROM ping_logs
    WHERE monitored_ip_id = ? AND checked_at >= (NOW() - INTERVAL 1 DAY)
");
$summary24Stmt->execute([$ip['id']]);
$stats24 = $summary24Stmt->fetch() ?: ['total' => 0, 'on_count' => 0];

$uptimePercent = function(int $days) use ($pdo, $ip) {
    $stmt = $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 $days DAY)
    ");
    $stmt->execute([$ip['id']]);
    $row = $stmt->fetch();
    if (!$row || !$row['total']) {
        return null;
    }
    return round(($row['on_count'] / $row['total']) * 100, 3);
};

$uptime24 = ($stats24['total'] ?? 0) > 0 ? round(($stats24['on_count'] / $stats24['total']) * 100, 2) : null;
$uptime7  = $uptimePercent(7);
$uptime30 = $uptimePercent(30);

$checks24 = (int)($stats24['total'] ?? 0);
$avgLatency24 = isset($stats24['avg_latency']) ? round((float)$stats24['avg_latency'], 1) : null;
$minLatency24 = isset($stats24['min_latency']) && $stats24['min_latency'] !== null ? (int)$stats24['min_latency'] : null;
$maxLatency24 = isset($stats24['max_latency']) && $stats24['max_latency'] !== null ? (int)$stats24['max_latency'] : null;

$previousAvgStmt = $pdo->prepare("
    SELECT AVG(latency_ms) AS avg_latency
    FROM ping_logs
    WHERE monitored_ip_id = ? 
      AND checked_at < (NOW() - INTERVAL 1 DAY)
      AND checked_at >= (NOW() - INTERVAL 2 DAY)
");
$previousAvgStmt->execute([$ip['id']]);
$previousAvg = $previousAvgStmt->fetchColumn();
$latencyTrend = ($avgLatency24 !== null && $previousAvg !== false && $previousAvg !== null)
    ? round($avgLatency24 - (float)$previousAvg, 1)
    : null;

$chartBuckets = array_fill(0, 24, null);
$chartStmt = $pdo->prepare("
    SELECT HOUR(checked_at) AS hour_slot, AVG(latency_ms) AS avg_latency
    FROM ping_logs
    WHERE monitored_ip_id = ? AND checked_at >= (NOW() - INTERVAL 1 DAY)
    GROUP BY hour_slot
    ORDER BY hour_slot
");
$chartStmt->execute([$ip['id']]);
while ($row = $chartStmt->fetch()) {
    $chartBuckets[(int)$row['hour_slot']] = $row['avg_latency'] !== null ? round((float)$row['avg_latency'], 2) : null;
}
$chartLabels = [];
$chartValues = [];
for ($i = 0; $i < 24; $i++) {
    $chartLabels[] = sprintf('%02d:00', $i);
    $chartValues[] = $chartBuckets[$i];
}

$heatmapData = array_fill(0, 24, ['ratio' => null]);
$heatmapStmt = $pdo->prepare("
    SELECT HOUR(checked_at) AS hour_slot,
           SUM(CASE WHEN status='online' THEN 1 ELSE 0 END) AS on_count,
           COUNT(*) AS total
    FROM ping_logs
    WHERE monitored_ip_id = ? AND checked_at >= (NOW() - INTERVAL 1 DAY)
    GROUP BY hour_slot
");
$heatmapStmt->execute([$ip['id']]);
while ($row = $heatmapStmt->fetch()) {
    $ratio = $row['total'] > 0 ? ($row['on_count'] / $row['total']) : null;
    $heatmapData[(int)$row['hour_slot']] = ['ratio' => $ratio];
}

$eventsStmt = $pdo->prepare("
    SELECT 
        SUM(CASE WHEN latency_ms IS NOT NULL AND latency_ms > 200 THEN 1 ELSE 0 END) AS peaks,
        SUM(CASE WHEN status='offline' THEN 1 ELSE 0 END) AS outages
    FROM ping_logs
    WHERE monitored_ip_id = ? AND checked_at >= (NOW() - INTERVAL 7 DAY)
");
$eventsStmt->execute([$ip['id']]);
$events = $eventsStmt->fetch() ?: ['peaks' => 0, 'outages' => 0];

$instabilities = 0;
foreach ($heatmapData as $entry) {
    if (!isset($entry['ratio']) || $entry['ratio'] === null) {
        continue;
    }
    if ($entry['ratio'] < 0.99 && $entry['ratio'] >= 0.9) {
        $instabilities++;
    }
}
$incidents = (int)($events['outages'] ?? 0);
?>

<a class="back-link" href="<?php echo BASE_URL; ?>index.php?page=dashboard">&larr; Voltar para Dashboard</a>

<div class="card detail-header">
    <div>
        <h1><?php echo h($ip['label']); ?></h1>
        <p>Monitorando <?php echo h($ip['host']); ?> · Cliente <?php echo h($user['name']); ?></p>
        <small>Último check: <?php echo $ip['last_check_at'] ?: 'Sem registros'; ?> · Intervalo configurado: <?php echo (int)$ip['interval_seconds']; ?>s</small>
    </div>
    <div class="status-pill <?php echo $ip['last_status']; ?>">
        <?php echo $ip['last_status'] ? ucfirst($ip['last_status']) : 'Desconhecido'; ?>
        <?php if ($ip['last_latency_ms'] !== null): ?>
            <br><strong><?php echo (int)$ip['last_latency_ms']; ?> ms</strong>
        <?php endif; ?>
    </div>
</div>

<div class="card">
    <div class="metric-grid">
        <div class="metric-card">
            <span class="metric-label">Situação atual</span>
            <strong><?php echo $ip['last_status'] ? ucfirst($ip['last_status']) : 'Sem dados'; ?></strong>
            <p>Último check em <?php echo $ip['last_check_at'] ?: 'Sem registros'; ?></p>
        </div>
        <div class="metric-card">
            <span class="metric-label">Última verificação</span>
            <strong><?php echo $ip['last_check_at'] ?: 'Sem registros'; ?></strong>
            <p>Intervalo atual: <?php echo (int)$ip['interval_seconds']; ?> segundos.</p>
        </div>
        <div class="metric-card">
            <span class="metric-label">Uptime (7 dias)</span>
            <strong><?php echo $uptime7 !== null ? $uptime7 . '%' : 'Sem dados'; ?></strong>
            <p>Baseado nos últimos 7 dias.</p>
        </div>
        <div class="metric-card">
            <span class="metric-label">Uptime (30 dias)</span>
            <strong><?php echo $uptime30 !== null ? $uptime30 . '%' : 'Sem dados'; ?></strong>
            <p>Tendência de SLA atual.</p>
        </div>
        <div class="metric-card">
            <span class="metric-label">Latência média (24h)</span>
            <strong><?php echo $avgLatency24 !== null ? $avgLatency24 . ' ms' : 'Sem dados'; ?></strong>
            <p>Min <?php echo $minLatency24 !== null ? $minLatency24 . ' ms' : '—'; ?> · Max <?php echo $maxLatency24 !== null ? $maxLatency24 . ' ms' : '—'; ?></p>
        </div>
        <div class="metric-card">
            <span class="metric-label">Checks (24h)</span>
            <strong><?php echo $checks24; ?></strong>
            <p>Esperado: ~<?php echo round(86400 / max(1, (int)$ip['interval_seconds'])); ?> checks/dia.</p>
        </div>
        <div class="metric-card">
            <span class="metric-label">Tendência de latência</span>
            <strong>
                <?php if ($latencyTrend === null): ?>
                    Sem dados
                <?php elseif ($latencyTrend === 0.0): ?>
                    Estável
                <?php elseif ($latencyTrend > 0): ?>
                    +<?php echo $latencyTrend; ?> ms
                <?php else: ?>
                    <?php echo $latencyTrend; ?> ms
                <?php endif; ?>
            </strong>
            <p>Comparado às 24h anteriores.</p>
        </div>
        <div class="metric-card">
            <span class="metric-label">SLA atual</span>
            <strong><?php echo $uptime30 !== null ? $uptime30 . '%' : 'Sem dados'; ?></strong>
            <p>Meta: 99.90% · Dentro da meta? <?php echo ($uptime30 !== null && $uptime30 >= 99.9) ? 'Sim' : 'Não'; ?></p>
        </div>
    </div>
</div>

<div class="card chart-card">
    <div class="card-head">
        <h2>Tempo de resposta</h2>
        <p>Latência média registrada hora a hora nas últimas 24 horas.</p>
    </div>
    <canvas id="ipLatencyChart"></canvas>
</div>

<div class="card">
    <h2>Heatmap de uptime (últimas 24h)</h2>
    <p>Qualidade do serviço hora a hora.</p>
    <div class="heatmap">
        <?php foreach ($heatmapData as $hour => $entry):
            $ratio = $entry['ratio'];
            $class = '';
            if ($ratio === null) {
                $class = '';
            } elseif ($ratio >= 0.99) {
                $class = 'good';
            } elseif ($ratio >= 0.95) {
                $class = 'medium';
            } else {
                $class = 'bad';
            }
            ?>
            <div class="heatmap-cell <?php echo $class; ?>">
                <strong><?php echo sprintf('%02d', $hour); ?>h</strong><br>
                <small><?php echo $ratio !== null ? round($ratio * 100, 1) . '%' : '—'; ?></small>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<div class="card">
    <h2>Eventos detectados (últimos 7 dias)</h2>
    <div class="ip-card-stats">
        <div>
            <small>Picos de latência (&gt;200 ms)</small>
            <strong><?php echo (int)($events['peaks'] ?? 0); ?></strong>
        </div>
        <div>
            <small>Timeouts</small>
            <strong><?php echo (int)($events['outages'] ?? 0); ?></strong>
        </div>
        <div>
            <small>Instabilidades</small>
            <strong><?php echo $instabilities; ?></strong>
        </div>
        <div>
            <small>Incidentes críticos</small>
            <strong><?php echo $incidents; ?></strong>
        </div>
    </div>
</div>

<?php if ($recentAlerts): ?>
<div class="card">
    <h2>Últimos alertas enviados</h2>
    <p>Visualize os 3 disparos mais recentes para confirmar se o fluxo está ativo.</p>
    <div class="alert-preview-grid">
        <?php foreach ($recentAlerts as $alert): ?>
            <div class="alert-preview-card">
                <div class="alert-preview-head">
                    <span class="alert-type"><?php echo strtoupper(h($alert['type'])); ?></span>
                    <span class="alert-status <?php echo $alert['status'] === 'success' ? 'ok' : 'fail'; ?>">
                        <?php echo $alert['status'] === 'success' ? 'OK' : 'Falhou'; ?>
                    </span>
                </div>
                <p class="alert-target"><?php echo h($alert['target'] ?: 'Destino padrão'); ?></p>
                <small class="alert-date"><?php echo date('d/m/Y H:i', strtotime($alert['sent_at'])); ?></small>
                <?php if (!empty($alert['error_message'])): ?>
                    <p class="alert-error"><?php echo h($alert['error_message']); ?></p>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<?php if ($channels): ?>
<div class="card">
    <h2>Canais de alerta configurados</h2>
    <table>
        <thead>
        <tr>
            <th>Tipo</th>
            <th>Destino</th>
            <th>Mín. falhas</th>
            <th>Cooldown</th>
            <th>Silêncio</th>
            <th>Ativo</th>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($channels as $channel): ?>
            <tr>
                <td><?php echo h(strtoupper($channel['type'])); ?></td>
                <td><?php echo h($channel['target']); ?></td>
                <td><?php echo (int)$channel['min_failures']; ?></td>
                <td><?php echo (int)$channel['cooldown_minutes']; ?> min</td>
                <td>
                    <?php echo ($channel['silence_start'] && $channel['silence_end'])
                        ? h(substr($channel['silence_start'], 0, 5)) . ' - ' . h(substr($channel['silence_end'], 0, 5))
                        : '—'; ?>
                </td>
                <td><?php echo $channel['active'] ? 'Sim' : 'Não'; ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php endif; ?>

<div class="card">
    <h2>Simular alerta de queda</h2>
    <p>Envie um e-mail de teste como se este link tivesse acabado de ficar offline.</p>
    <?php if ($testAlertSuccess !== null): ?>
        <p style="color:<?php echo $testAlertSuccess ? '#16a34a' : '#dc2626'; ?>;font-weight:600;">
            <?php echo h($testAlertMessage); ?>
        </p>
    <?php endif; ?>
    <?php if ($emailChannels): ?>
        <form method="post" style="display:flex;flex-direction:column;gap:10px;max-width:420px;">
            <input type="hidden" name="action" value="test_alert">
            <input type="hidden" name="csrf_token" value="<?php echo h(csrf_token()); ?>">
            <label>Canal de e-mail</label>
            <select name="channel_id" required>
                <option value="">Selecione...</option>
                <?php foreach ($emailChannels as $channel): ?>
                    <option value="<?php echo (int)$channel['id']; ?>">
                        <?php echo h($channel['target']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <button type="submit" class="primary-button">Enviar alerta de teste</button>
            <p class="hint">Não afeta os logs ou contadores do canal.</p>
        </form>
    <?php else: ?>
        <p>Nenhum canal de e-mail está ativo para este IP. Adicione um canal para testar os alertas.</p>
    <?php endif; ?>
</div>

<div class="card">
    <h2>Histórico de incidentes (últimos 7 dias)</h2>
    <?php if ($incidents === 0): ?>
        <p>Nenhum incidente crítico registrado. Continue monitorando a latência para manter o SLA.</p>
    <?php else: ?>
        <p>Foram encontrados <?php echo $incidents; ?> incidentes críticos. Consulte os logs para detalhes.</p>
    <?php endif; ?>
    <div class="detail-actions">
        <a class="ghost-button" href="<?php echo BASE_URL; ?>index.php?page=user_logs&id=<?php echo $ip['id']; ?>">Ver logs</a>
        <a class="primary-button" href="<?php echo BASE_URL; ?>index.php?page=user_ip_form&id=<?php echo $ip['id']; ?>">Gerenciar IP</a>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ipCtx = document.getElementById('ipLatencyChart');
if (ipCtx) {
    new Chart(ipCtx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($chartLabels, JSON_UNESCAPED_UNICODE); ?>,
            datasets: [{
                label: 'Latência média (ms)',
                data: <?php echo json_encode($chartValues, JSON_UNESCAPED_UNICODE); ?>,
                fill: true,
                borderColor: '#2563eb',
                backgroundColor: 'rgba(37, 99, 235, 0.15)',
                tension: 0.35,
                pointRadius: 0
            }]
        },
        options: {
            plugins: { legend: { display: false } },
            scales: {
                y: { beginAtZero: true, ticks: { stepSize: 5 } }
            }
        }
    });
}
</script>

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