<?php
require_once __DIR__ . '/../includes/header.php';
$pdo = db();
$plan = get_user_plan($user['id']);
$ipsCount = count_user_ips($user['id']);

$summaryStmt = $pdo->prepare("
    SELECT 
        COUNT(*) AS total_ips,
        SUM(CASE WHEN last_status='online' THEN 1 ELSE 0 END) AS online_ips,
        SUM(CASE WHEN last_status='offline' THEN 1 ELSE 0 END) AS offline_ips,
        AVG(last_latency_ms) AS avg_latency
    FROM monitored_ips
    WHERE user_id = ?
");
$summaryStmt->execute([$user['id']]);
$summary = $summaryStmt->fetch() ?: [];

$uptimeStmt = $pdo->prepare("
    SELECT COUNT(*) AS total,
           SUM(CASE WHEN status='online' THEN 1 ELSE 0 END) AS on_count
    FROM ping_logs pl
    JOIN monitored_ips mi ON mi.id = pl.monitored_ip_id
    WHERE mi.user_id = ? AND pl.checked_at >= (NOW() - INTERVAL 1 DAY)
");
$uptimeStmt->execute([$user['id']]);
$uptimeRow = $uptimeStmt->fetch();
$uptime = ($uptimeRow['total'] ?? 0) > 0
    ? round(($uptimeRow['on_count'] / $uptimeRow['total']) * 100, 2)
    : null;

$latencyStmt = $pdo->prepare("
    SELECT AVG(pl.latency_ms) 
    FROM ping_logs pl
    JOIN monitored_ips mi ON mi.id = pl.monitored_ip_id
    WHERE mi.user_id = ? AND pl.checked_at >= (NOW() - INTERVAL 1 DAY)
");
$latencyStmt->execute([$user['id']]);
$avgLatency24 = $latencyStmt->fetchColumn();
$avgLatency24 = $avgLatency24 !== null ? round((float)$avgLatency24, 1) : null;

$ipsStmt = $pdo->prepare("SELECT * FROM monitored_ips WHERE user_id = ? ORDER BY created_at DESC");
$ipsStmt->execute([$user['id']]);
$ips = $ipsStmt->fetchAll();

$uptimeByIp = [];
if (!empty($ips)) {
    $ids = array_column($ips, 'id');
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $uptimePerIpStmt = $pdo->prepare("
        SELECT monitored_ip_id,
               SUM(CASE WHEN status='online' THEN 1 ELSE 0 END) AS on_count,
               COUNT(*) AS total
        FROM ping_logs
        WHERE monitored_ip_id IN ($placeholders)
          AND checked_at >= (NOW() - INTERVAL 1 DAY)
        GROUP BY monitored_ip_id
    ");
    $uptimePerIpStmt->execute($ids);
    while ($row = $uptimePerIpStmt->fetch()) {
        $uptimeByIp[$row['monitored_ip_id']] = $row;
    }
}

$allowedRanges = [3, 6, 12, 24];
$rangeHours = (int)($_GET['range'] ?? 24);
if (!in_array($rangeHours, $allowedRanges, true)) {
    $rangeHours = 24;
}

$dbNowRow = $pdo->query("SELECT NOW() AS current_ts")->fetch();
$dbTz = new DateTimeZone('UTC');
$now = isset($dbNowRow['current_ts']) ? new DateTimeImmutable($dbNowRow['current_ts'], $dbTz) : new DateTimeImmutable('now', $dbTz);
$currentSlot = $now->setTime((int)$now->format('H'), 0, 0);
$startSlot = $currentSlot->modify('-' . ($rangeHours - 1) . ' hour');

$chartLabels = [];
$chartBuckets = [];
for ($i = 0; $i < $rangeHours; $i++) {
    $slot = $startSlot->modify("+{$i} hour");
    $key = $slot->format('Y-m-d H:00:00');
    $chartBuckets[$key] = null;
    $chartLabels[] = $slot->format('H:i');
}

$chartStmt = $pdo->prepare("
    SELECT DATE_FORMAT(pl.checked_at, '%Y-%m-%d %H:00:00') AS slot,
           AVG(pl.latency_ms) AS avg_latency
    FROM ping_logs pl
    JOIN monitored_ips mi ON mi.id = pl.monitored_ip_id
    WHERE mi.user_id = ?
      AND pl.checked_at >= (NOW() - INTERVAL ? HOUR)
    GROUP BY slot
    ORDER BY slot
");
$chartStmt->execute([$user['id'], $rangeHours]);
while ($row = $chartStmt->fetch()) {
    $slotKey = $row['slot'];
    if (array_key_exists($slotKey, $chartBuckets)) {
        $chartBuckets[$slotKey] = $row['avg_latency'] !== null ? round((float)$row['avg_latency'], 2) : null;
    }
}
$chartValues = array_values($chartBuckets);

$channelsByIp = [];
if (!empty($ips)) {
    $placeholders = implode(',', array_fill(0, count($ips), '?'));
    $channelStmt = $pdo->prepare("
        SELECT monitored_ip_id, type, target, cooldown_minutes, silence_start, silence_end, active
        FROM alert_channels
        WHERE monitored_ip_id IN ($placeholders)
        ORDER BY id ASC
    ");
    $channelStmt->execute(array_column($ips, 'id'));
    while ($row = $channelStmt->fetch()) {
        $channelsByIp[(int)$row['monitored_ip_id']][] = $row;
    }
}

$humanizeDiff = static function (?string $dateString) use ($now, $dbTz) {
    if (!$dateString) return 'sem registros';
    try {
        $dt = new DateTimeImmutable($dateString, $dbTz);
    } catch (Exception $e) {
        return $dateString;
    }
    $diff = $now->getTimestamp() - $dt->getTimestamp();
    if ($diff < 60) return $diff . 's atrás';
    if ($diff < 3600) return floor($diff / 60) . 'min atrás';
    if ($diff < 86400) return floor($diff / 3600) . 'h atrás';
    return $dt->format('d/m H:i');
};

$nextCheckText = static function (array $ip) use ($now, $dbTz) {
    if (empty($ip['last_check_at'])) return 'Próximo: agora';
    try {
        $last = new DateTimeImmutable($ip['last_check_at'], $dbTz);
    } catch (Exception $e) {
        return 'Próximo: --';
    }
    $next = $last->modify('+' . (int)$ip['interval_seconds'] . ' seconds');
    $diff = $next->getTimestamp() - $now->getTimestamp();
    if ($diff <= 0) return 'Próximo: agora';
    if ($diff < 60) return 'Próximo: em ' . $diff . 's';
    return 'Próximo: em ' . floor($diff / 60) . 'min';
};

$isAdmin = $user['role'] === 'admin';
?>

<div class="card-grid stats-grid">
    <div class="stats-card">
        <small>Total de IPs</small>
        <strong id="dashTotal"><?php echo (int)($summary['total_ips'] ?? 0); ?></strong>
        <p><?php echo $ipsCount; ?> usados de <?php echo (int)$plan['max_ips']; ?> disponíveis.</p>
    </div>
    <div class="stats-card">
        <small>Online</small>
        <strong id="dashOnline" class="status-online"><?php echo (int)($summary['online_ips'] ?? 0); ?></strong>
        <p>IPs respondendo agora.</p>
    </div>
    <div class="stats-card">
        <small>Offline</small>
        <strong id="dashOffline" class="status-offline"><?php echo (int)($summary['offline_ips'] ?? 0); ?></strong>
        <p>Revise alertas recentes.</p>
    </div>
    <div class="stats-card">
        <small>Latência média (24h)</small>
        <strong id="dashLat"><?php echo $avgLatency24 !== null ? $avgLatency24 . ' ms' : '—'; ?></strong>
        <p>Uptime 24h: <?php echo $uptime !== null ? $uptime . '%' : 'Sem dados'; ?></p>
    </div>
</div>

<div class="card chart-card">
    <div class="card-head">
        <h2>Tempo de resposta</h2>
        <p>Latência média dos seus IPs nas últimas <?php echo $rangeHours; ?> horas.</p>
        <div class="range-tabs">
            <?php foreach ($allowedRanges as $opt): 
                $active = $opt === $rangeHours ? 'active' : '';
                $link = BASE_URL . 'index.php?page=dashboard&range=' . $opt;
            ?>
                <a class="range-tab <?php echo $active; ?>" href="<?php echo h($link); ?>"><?php echo $opt; ?>h</a>
            <?php endforeach; ?>
        </div>
    </div>
    <canvas id="latencyChart"></canvas>
</div>

<?php if ($isAdmin): ?>
    <div class="card">
        <div class="card-head">
            <h3>Área administrativa disponível</h3>
            <p>Gerencie usuários, planos e logs globais sem sair da sessão atual.</p>
        </div>
        <a class="primary-button" href="<?php echo BASE_URL; ?>index.php?page=admin_dashboard">Abrir Dashboard Admin</a>
    </div>
<?php endif; ?>

<!-- INCIDENTES RECENTES (NOVO) -->
<div class="card">
    <div class="card-head">
        <h2>Últimos Eventos de Monitoramento</h2>
        <p>Feed recente de alterações e falhas de status nas últimas 24hs.</p>
    </div>
    <div id="incidentsFeed" style="display:flex;flex-direction:column;gap:12px;font-size:14px;background:#f8fafc;padding:16px;border-radius:12px;">
        <span style="color:#64748b;">Carregando histórico...</span>
    </div>
</div>

<div class="card">
    <div class="card-head">
        <h2>IPs monitorados</h2>
        <div>
            <p>Resumo dos IPs cadastrados no plano atual. Atualização em: <strong id="refreshCountdown">15s</strong></p>
        </div>
    </div>
    <?php if (empty($ips)): ?>
        <p>Você ainda não cadastrou nenhum host. <a href="<?php echo BASE_URL; ?>index.php?page=user_ip_form">Adicionar IP</a></p>
    <?php else: ?>
        <div class="ip-cards" id="ipGrid">
            <?php foreach ($ips as $ip): 
                $status = $ip['last_status'];
                $latency = $ip['last_latency_ms'] !== null ? (int)$ip['last_latency_ms'] . ' ms' : 'N/A';
                $ipUptime = $uptimeByIp[$ip['id']] ?? null;
                $uptimeText = ($ipUptime && $ipUptime['total'] > 0)
                    ? round(($ipUptime['on_count'] / $ipUptime['total']) * 100, 1) . '%'
                    : 'Sem dados';
                $latencyRisk = $ip['last_latency_ms'] !== null && (int)$ip['last_latency_ms'] >= 200;
                $channels = $channelsByIp[$ip['id']] ?? [];
                if (!$channels && !empty($ip['alert_email'])) {
                    $channels[] = ['type' => 'email', 'target' => $ip['alert_email'], 'active' => 1, 'cooldown_minutes' => 0];
                }
                ?>
                <div id="card-ip-<?php echo $ip['id']; ?>"
                    class="ip-card <?php echo $status === 'online' ? 'online' : ($status === 'offline' ? 'offline' : ''); ?> <?php echo $latencyRisk ? 'latency-risk' : ''; ?>" 
                    style="<?php echo $ip['active'] == 0 ? 'opacity:0.6; filter:grayscale(1);' : ''; ?>">
                    <div class="ip-card-head" style="cursor:pointer;" onclick="window.location.href='<?php echo BASE_URL; ?>index.php?page=user_ip_detail&id=<?php echo $ip['id']; ?>'">
                        <div>
                            <h3><?php echo h($ip['label']); ?></h3>
                            <small><?php echo h($ip['host']); ?></small>
                        </div>
                        <div style="display:flex;flex-direction:column;align-items:flex-end;gap:6px;">
                            <span class="chip <?php echo $status === 'online' ? 'chip-live' : 'chip'; ?> chip-status-text">
                                <?php echo $ip['active'] == 0 ? 'PAUSADO' : ($status ? strtoupper($status) : 'DESCONHECIDO'); ?>
                            </span>
                            <span class="chip-risk-badge" style="display: <?php echo $latencyRisk ? 'inline-block' : 'none'; ?>;" class="chip chip-risk">Latência alta</span>
                        </div>
                    </div>
                    
                    <div class="ip-card-meta">
                        <span class="meta-item"><strong id="valNext-<?php echo $ip['id']; ?>" style="font-weight:600;color:#334155;"><?php echo h($nextCheckText($ip)); ?></strong></span>
                    </div>
                    <div class="ip-card-stats">
                        <div>
                            <small>Resposta</small>
                            <strong id="valLat-<?php echo $ip['id']; ?>"><?php echo $latency; ?></strong>
                        </div>
                        <div>
                            <small>Saúde (15 checks)</small>
                            <div id="valBar-<?php echo $ip['id']; ?>" style="display:flex; height:12px; margin-top:4px;">
                                <small style="color:#94a3b8;">Gravando...</small>
                            </div>
                        </div>
                        <div>
                            <small>Uptime (24h)</small>
                            <strong><?php echo $uptimeText; ?></strong>
                        </div>
                        <div>
                            <small>Último check</small>
                            <strong><?php echo $ip['last_check_at'] ?: '-'; ?></strong>
                        </div>
                    </div>
                    <?php if ($channels): ?>
                        <div class="ip-channel-row">
                            <?php foreach ($channels as $channel): ?>
                                <?php if (!empty($channel['active'])): ?>
                                    <span class="chip chip-channel">
                                        <?php echo strtoupper(h($channel['type'])); ?>
                                        <?php if (!empty($channel['cooldown_minutes'])): ?>
                                            <small class="chip-sub">CD <?php echo (int)$channel['cooldown_minutes']; ?>m</small>
                                        <?php endif; ?>
                                        <?php if (!empty($channel['silence_start']) && !empty($channel['silence_end'])): ?>
                                            <small class="chip-sub"><?php echo h(substr($channel['silence_start'],0,5)); ?>-<?php echo h(substr($channel['silence_end'],0,5)); ?></small>
                                        <?php endif; ?>
                                    </span>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                    <div class="ip-card-actions" style="margin-top:16px; border-top:1px solid #e2e8f0; padding-top:12px; display:flex; gap:12px;">
                        <button onclick="toggleIp(<?php echo $ip['id']; ?>, <?php echo $ip['active'] == 1 ? 0 : 1; ?>)" class="secondary-button" id="btnToggle-<?php echo $ip['id']; ?>" style="flex:1; padding:6px; font-size:12px; background:<?php echo $ip['active']==1 ? '#fef2f2' : '#f0fdf4'; ?>; color:<?php echo $ip['active']==1 ? '#ef4444' : '#16a34a'; ?>; cursor:pointer; border-radius:6px; font-weight:600; border:1px solid currentColor;">
                           <?php echo $ip['active'] == 1 ? '⏸ Pausar Check' : '▶ Retomar'; ?>
                        </button>
                        <a href="<?php echo BASE_URL; ?>index.php?page=user_ip_form&id=<?php echo $ip['id']; ?>" style="flex:1;text-align:center;padding:6px;border-radius:6px;background:#f1f5f9;color:#334155;font-size:12px;font-weight:600;">Editar</a>
                        <a href="<?php echo BASE_URL; ?>index.php?page=user_logs&id=<?php echo $ip['id']; ?>" style="flex:1;text-align:center;padding:6px;border-radius:6px;background:#f1f5f9;color:#334155;font-size:12px;font-weight:600;">Logs</a>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('latencyChart');
if (ctx) {
    new Chart(ctx, {
        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>

<script>
// SPA AESTHETICS & AUTO REFRESH

// 1. Alternador de Liga/Desliga individual (Toggle AJAX)
function toggleIp(ipId, desiredState) {
    const btn = document.getElementById('btnToggle-' + ipId);
    if(btn) {
        btn.innerHTML = 'Carregando...';
        btn.style.opacity = '0.5';
    }
    
    const formData = new URLSearchParams();
    formData.append('id', ipId);
    formData.append('active', desiredState);

    fetch('<?php echo BASE_URL; ?>index.php?page=api_toggle_ip', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: formData.toString()
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            fetchDashboardData(); // Força update da tela imediatamente
        } else {
            alert('Erro: ' + data.error);
        }
    }).finally(() => {
        if(btn) btn.style.opacity = '1';
    });
}

// 2. Fetch Refresh Loop a cada 15 segs
let counter = 15;
function fetchDashboardData() {
    fetch('<?php echo BASE_URL; ?>index.php?page=api_dashboard')
      .then(r => r.json())
      .then(data => {
         // Update Summary Cards
         if(document.getElementById('dashTotal')) document.getElementById('dashTotal').innerText = data.summary.total;
         if(document.getElementById('dashOnline')) document.getElementById('dashOnline').innerText = data.summary.online;
         if(document.getElementById('dashOffline')) document.getElementById('dashOffline').innerText = data.summary.offline;
         if(document.getElementById('dashLat')) document.getElementById('dashLat').innerText = data.summary.lat24;
         
         // Update Incidents Feed
         const feed = document.getElementById('incidentsFeed');
         if (feed) {
             feed.innerHTML = '';
             if (data.incidents.length === 0) {
                 feed.innerHTML = '<span style="color:#64748b;">Nenhuma instabilidade nas últimas 24h.</span>';
             } else {
                 data.incidents.forEach(inc => {
                     const div = document.createElement('div');
                     div.style.display = 'flex';
                     div.style.gap = '8px';
                     div.style.alignItems = 'center';
                     div.innerHTML = `<strong style="color: ${inc.color === 'red' ? '#ef4444' : '#16a34a'}">· ${inc.time}</strong> <span><b>${inc.label}</b> ${inc.message}</span>`;
                     feed.appendChild(div);
                 });
             }
         }

         // Update IP Cards
         data.ips.forEach(ip => {
             const card = document.getElementById('card-ip-' + ip.id);
             if (!card) return;
             
             // Update status and visual appearance
             if (ip.active === 0) {
                 card.className = 'ip-card';
                 card.style.opacity = '0.6'; card.style.filter = 'grayscale(1)';
             } else {
                 card.style.opacity = '1'; card.style.filter = 'none';
                 card.className = 'ip-card ' + (ip.status === 'online' ? 'online' : (ip.status === 'offline' ? 'offline' : ''));
                 if (ip.risk) card.classList.add('latency-risk');
             }

             // Update latency text
             const valLat = document.getElementById('valLat-' + ip.id);
             if (valLat) valLat.innerText = ip.latency;

             // Update next check text
             const valNext = document.getElementById('valNext-' + ip.id);
             if (valNext) valNext.innerText = ip.next_check;

             // Update health bar visual
             const valBar = document.getElementById('valBar-' + ip.id);
             if (valBar) valBar.innerHTML = ip.history_html;

             // Update text inside the card header chip
             const statusChip = card.querySelector('.chip-status-text');
             if (statusChip) {
                 statusChip.className = 'chip chip-status-text ' + (ip.status === 'online' && ip.active === 1 ? 'chip-live' : '');
                 statusChip.innerText = ip.active === 0 ? 'PAUSADO' : ip.status.toUpperCase();
             }

             const riskBadge = card.querySelector('.chip-risk-badge');
             if (riskBadge) riskBadge.style.display = ip.risk ? 'inline-block' : 'none';

             // Update button text and parameters
             const btn = document.getElementById('btnToggle-' + ip.id);
             if (btn) {
                 btn.setAttribute('onclick', `toggleIp(${ip.id}, ${ip.active === 1 ? 0 : 1})`);
                 if (ip.active === 1) {
                     btn.style.background = '#fef2f2'; btn.style.color = '#ef4444'; btn.innerText = '⏸ Pausar Check';
                 } else {
                     btn.style.background = '#f0fdf4'; btn.style.color = '#16a34a'; btn.innerText = '▶ Retomar';
                 }
             }
         });
      });
}

setInterval(() => {
    counter--;
    if(counter <= 0) {
        counter = 15;
        fetchDashboardData();
    }
    const cd = document.getElementById('refreshCountdown');
    if (cd) cd.innerText = counter + 's';
}, 1000);

// Fetch imediato inicial pra carregar barras de histórico da timeline e feed de alertas
fetchDashboardData();

</script>


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