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

$totalUsers    = (int)$pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
$totalIps      = (int)$pdo->query("SELECT COUNT(*) FROM monitored_ips")->fetchColumn();
$offlineIps    = (int)$pdo->query("SELECT COUNT(*) FROM monitored_ips WHERE last_status = 'offline'")->fetchColumn();
$totalLogs24   = (int)$pdo->query("SELECT COUNT(*) FROM ping_logs WHERE checked_at >= (NOW() - INTERVAL 1 DAY)")->fetchColumn();
$newUsers7Days = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE created_at >= (NOW() - INTERVAL 7 DAY)")->fetchColumn();

$alertHealthRaw = $pdo->query("
    SELECT type, SUM(status='success') AS ok_count, SUM(status='failed') AS fail_count
    FROM alerts_sent
    WHERE sent_at >= (NOW() - INTERVAL 1 DAY)
    GROUP BY type
")->fetchAll();
$alertHealth = [
    'email' => ['label' => 'E-mail',   'ok' => 0, 'fail' => 0],
    'webhook' => ['label' => 'Webhook', 'ok' => 0, 'fail' => 0],
    'whatsapp' => ['label' => 'WhatsApp', 'ok' => 0, 'fail' => 0],
    'sms' => ['label' => 'SMS', 'ok' => 0, 'fail' => 0],
];
foreach ($alertHealthRaw as $row) {
    $type = $row['type'];
    if (!isset($alertHealth[$type])) {
        $alertHealth[$type] = ['label' => ucfirst($type), 'ok' => 0, 'fail' => 0];
    }
    $alertHealth[$type]['ok'] = (int)$row['ok_count'];
    $alertHealth[$type]['fail'] = (int)$row['fail_count'];
}

$recentAlertErrors = $pdo->query("
    SELECT 
        a.sent_at,
        a.type,
        a.error_message,
        a.message,
        'info' AS severity,
        mi.label AS ip_label,
        mi.host,
        COALESCE(ac.target, mi.alert_email) AS target
    FROM alerts_sent a
    LEFT JOIN alert_channels ac ON ac.id = a.channel_id
    LEFT JOIN monitored_ips mi ON mi.id = a.monitored_ip_id
    WHERE a.status = 'failed'
    ORDER BY a.sent_at DESC
    LIMIT 10
")->fetchAll();

$recentOffline = $pdo->query("
    SELECT pl.checked_at, pl.status, mi.label, mi.host, u.email
    FROM ping_logs pl
    JOIN monitored_ips mi ON mi.id = pl.monitored_ip_id
    JOIN users u ON u.id = mi.user_id
    WHERE pl.status = 'offline'
    ORDER BY pl.checked_at DESC
    LIMIT 5
")->fetchAll();
?>

<div class="card-grid stats-grid">
    <div class="stats-card">
        <small>Usuários</small>
        <strong><?php echo $totalUsers; ?></strong>
        <p><?php echo $newUsers7Days; ?> novos nos últimos 7 dias.</p>
    </div>
    <div class="stats-card">
        <small>IPs monitorados</small>
        <strong><?php echo $totalIps; ?></strong>
        <p><?php echo $offlineIps; ?> estão offline agora.</p>
    </div>
    <div class="stats-card">
        <small>Logs (24h)</small>
        <strong><?php echo $totalLogs24; ?></strong>
        <p>Execuções do cron no período.</p>
    </div>
    <div class="stats-card">
        <small>Painel do usuário</small>
        <strong>Ativo</strong>
        <p>Verifique alertas críticos abaixo.</p>
    </div>
</div>

<div class="card">
    <h2>Ações rápidas</h2>
    <p>Gerencie recursos críticos em um clique.</p>
    <div class="ip-card-actions">
        <a class="primary-button" href="<?php echo BASE_URL; ?>index.php?page=admin_users">Gerenciar usuários</a>
        <a class="primary-button" href="<?php echo BASE_URL; ?>index.php?page=admin_plans">Gerenciar planos</a>
        <a class="ghost-button" href="<?php echo BASE_URL; ?>index.php?page=admin_ips">IPs globais</a>
        <a class="ghost-button" href="<?php echo BASE_URL; ?>index.php?page=admin_logs">Logs globais</a>
    </div>
</div>

<div class="card">
    <h2>Saúde dos alertas (últimas 24h)</h2>
    <p>Taxa de sucesso e falhas por canal.</p>
    <div class="card-grid stats-grid">
        <?php foreach ($alertHealth as $type => $info):
            $total = $info['ok'] + $info['fail'];
            $failRate = $total > 0 ? round(($info['fail'] / $total) * 100, 1) : 0;
            $statusClass = $failRate > 5 ? 'status-offline' : 'status-online';
        ?>
            <div class="stats-card">
                <small><?php echo h($info['label']); ?></small>
                <strong class="<?php echo $statusClass; ?>"><?php echo $total; ?> envios</strong>
                <p><?php echo $info['ok']; ?> ok • <?php echo $info['fail']; ?> falhas • <?php echo $failRate; ?>% falha</p>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<div class="card">
    <h2>Últimos erros de alerta</h2>
    <p>Falhas recentes ao disparar canais.</p>
    <?php if (empty($recentAlertErrors)): ?>
        <p>Nenhuma falha registrada.</p>
    <?php else: ?>
        <table>
            <thead>
                <tr>
                    <th>Data/Hora</th>
                    <th>Canal</th>
                    <th>Destino</th>
                    <th>Host</th>
                    <th>Severidade</th>
                    <th>Erro</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($recentAlertErrors as $error): ?>
                    <tr>
                        <td><?php echo h($error['sent_at']); ?></td>
                        <td><?php echo strtoupper(h($error['type'])); ?></td>
                        <td><?php echo h($error['target'] ?: '—'); ?></td>
                        <td><?php echo h($error['ip_label'] ?: '—'); ?> (<?php echo h($error['host'] ?: ''); ?>)</td>
                        <td>
                            <?php
                            $sev = strtolower($error['severity'] ?? 'info');
                            $sevLabel = $sev === 'critical' ? 'Crítico' : ($sev === 'warning' ? 'Alerta' : 'Info');
                            $sevClass = $sev === 'critical' ? 'status-offline' : ($sev === 'warning' ? 'status-offline' : 'status-online');
                            ?>
                            <span class="<?php echo $sevClass; ?>"><?php echo h($sevLabel); ?></span>
                        </td>
                        <td><?php echo h($error['error_message'] ?: 'Erro não informado'); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<div class="card">
    <h2>Últimos alertas offline</h2>
    <p>Eventos recentes registrados pelo cron.</p>
    <?php if (empty($recentOffline)): ?>
        <p>Nenhum evento offline nas últimas execuções.</p>
    <?php else: ?>
        <table>
            <thead>
                <tr>
                    <th>Data/Hora</th>
                    <th>Host</th>
                    <th>Usuário</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($recentOffline as $event): ?>
                    <tr>
                        <td><?php echo h($event['checked_at']); ?></td>
                        <td><?php echo h($event['label']); ?> (<?php echo h($event['host']); ?>)</td>
                        <td><?php echo h($event['email']); ?></td>
                        <td class="status-offline"><?php echo strtoupper($event['status']); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

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