<?php
$panelId = (int)($_GET['id'] ?? 0);
if (!$panelId) { header('Location: ' . UBNT_URL . '?page=ubnt_panels'); exit; }

$stmt = $pdo->prepare("SELECT * FROM ubiquiti_panels WHERE id=? AND user_id=?");
$stmt->execute([$panelId, $user['id']]);
$panel = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$panel) { header('Location: ' . UBNT_URL . '?page=ubnt_panels'); exit; }

// Histórico de clientes — últimas 24h (máx. 288 pontos)
$clientHist = $pdo->prepare("
    SELECT date_trunc('minute', recorded_at) AS ts,
           ROUND(AVG(client_count)) AS clients,
           ROUND(AVG(ccq)) AS ccq
    FROM ubiquiti_client_logs
    WHERE panel_id = ? AND recorded_at >= NOW() - INTERVAL '24 hours'
    GROUP BY 1 ORDER BY 1 ASC
");
$clientHist->execute([$panelId]);
$clientRows = $clientHist->fetchAll(PDO::FETCH_ASSOC);

// Histórico de link — últimas 24h
$linkHist = $pdo->prepare("
    SELECT date_trunc('minute', recorded_at) AS ts,
           iface_speed, iface_status
    FROM ubiquiti_link_logs
    WHERE panel_id = ? AND recorded_at >= NOW() - INTERVAL '24 hours'
    ORDER BY recorded_at ASC
");
$linkHist->execute([$panelId]);
$linkRows = $linkHist->fetchAll(PDO::FETCH_ASSOC);

// Alertas recentes
$alertStmt = $pdo->prepare("
    SELECT * FROM ubiquiti_alerts
    WHERE panel_id = ? ORDER BY created_at DESC LIMIT 20
");
$alertStmt->execute([$panelId]);
$alerts = $alertStmt->fetchAll(PDO::FETCH_ASSOC);

// Prepara dados para Chart.js
$chartLabels   = json_encode(array_column($clientRows, 'ts'));
$chartClients  = json_encode(array_map(fn($r) => (int)$r['clients'], $clientRows));
$chartCcq      = json_encode(array_map(fn($r) => $r['ccq'] !== null ? (int)$r['ccq'] : null, $clientRows));

$isOnline = $panel['last_status'] === 'online';
$statusColor = $isOnline ? '#16a34a' : '#dc2626';

function ubnt_speed_label(?int $speed): string {
    if ($speed === null) return '–';
    return match($speed) {
        1000 => '1G',
        100  => '100M',
        10   => '10M',
        default => $speed . 'M',
    };
}

require_once __DIR__ . '/../../includes/header.php';
?>

<div style="display:flex;flex-direction:column;gap:20px;">

    <!-- Breadcrumb -->
    <div style="display:flex;align-items:center;gap:8px;font-size:0.85rem;color:#64748b;">
        <a href="<?= UBNT_URL ?>?page=ubnt_panels" style="color:#1d4ed8;text-decoration:none;font-weight:600;">Painéis</a>
        <span>›</span>
        <span style="font-weight:700;color:#0f172a;"><?= h($panel['name']) ?></span>
    </div>

    <!-- Header do painel -->
    <div style="background:linear-gradient(135deg,#1e3a5f,#1d4ed8);border-radius:20px;padding:28px 32px;color:#eff6ff;">
        <div style="display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:16px;">
            <div>
                <div style="display:flex;align-items:center;gap:12px;margin-bottom:6px;">
                    <h1 style="margin:0;font-size:1.6rem;font-weight:800;"><?= h($panel['name']) ?></h1>
                    <span style="background:<?= $isOnline ? '#22c55e' : '#ef4444' ?>20;color:<?= $isOnline ? '#22c55e' : '#ef4444' ?>;border:1px solid <?= $isOnline ? '#22c55e' : '#ef4444' ?>40;border-radius:20px;padding:4px 14px;font-size:0.82rem;font-weight:700;">
                        <?= $isOnline ? '● Online' : '● Offline' ?>
                    </span>
                </div>
                <p style="margin:0;opacity:0.75;font-size:0.9rem;"><?= h($panel['hostname']) ?>
                    <?php if ($panel['location']): ?> · <?= h($panel['location']) ?><?php endif; ?>
                </p>
            </div>
            <a href="<?= UBNT_URL ?>?page=ubnt_panel_form&id=<?= $panelId ?>"
                style="display:inline-flex;align-items:center;gap:8px;background:rgba(255,255,255,0.15);border:1px solid rgba(255,255,255,0.3);color:#fff;text-decoration:none;padding:10px 20px;border-radius:10px;font-weight:600;font-size:0.88rem;">
                <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                Editar
            </a>
        </div>

        <!-- Métricas em tempo real -->
        <div style="display:flex;gap:16px;margin-top:24px;flex-wrap:wrap;">
            <?php
            $metrics = [
                ['label'=>'Clientes', 'value'=> $panel['last_client_count'] !== null ? (int)$panel['last_client_count'] : '–', 'unit'=>''],
                ['label'=>'Link',     'value'=> ubnt_speed_label($panel['last_iface_speed'] !== null ? (int)$panel['last_iface_speed'] : null), 'unit'=>''],
                ['label'=>'CCQ',      'value'=> $panel['last_ccq'] !== null ? (int)$panel['last_ccq'].'%' : '–', 'unit'=>''],
                ['label'=>'Sinal',    'value'=> $panel['last_signal'] !== null ? (int)$panel['last_signal'].' dBm' : '–', 'unit'=>''],
            ];
            foreach ($metrics as $m): ?>
                <div style="background:rgba(255,255,255,0.12);border-radius:14px;padding:16px 22px;min-width:110px;text-align:center;">
                    <div style="font-size:1.6rem;font-weight:800;"><?= h($m['value']) ?></div>
                    <div style="font-size:0.75rem;opacity:0.75;text-transform:uppercase;letter-spacing:0.05em;margin-top:2px;"><?= $m['label'] ?></div>
                </div>
            <?php endforeach; ?>
            <?php if ($panel['last_check_at']): ?>
                <div style="align-self:flex-end;opacity:0.6;font-size:0.78rem;margin-left:auto;">
                    Atualizado: <?= date('d/m H:i', strtotime($panel['last_check_at'])) ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Gráfico de Clientes -->
    <div style="background:#fff;border-radius:20px;border:1px solid #e2e8f0;padding:24px 28px;">
        <h3 style="margin:0 0 20px;font-size:1rem;font-weight:700;color:#0f172a;">Clientes Conectados — Últimas 24h</h3>
        <?php if (empty($clientRows)): ?>
            <div style="text-align:center;padding:40px;color:#94a3b8;font-size:0.9rem;">Sem dados históricos ainda. Aguarde o próximo ciclo de polling.</div>
        <?php else: ?>
            <canvas id="clientChart" height="100"></canvas>
        <?php endif; ?>
    </div>

    <!-- Gráfico de Link Speed -->
    <div style="background:#fff;border-radius:20px;border:1px solid #e2e8f0;padding:24px 28px;">
        <h3 style="margin:0 0 20px;font-size:1rem;font-weight:700;color:#0f172a;">Velocidade da Interface — Últimas 24h</h3>
        <?php if (empty($linkRows)): ?>
            <div style="text-align:center;padding:40px;color:#94a3b8;font-size:0.9rem;">Sem dados históricos ainda.</div>
        <?php else: ?>
            <canvas id="linkChart" height="80"></canvas>
        <?php endif; ?>
    </div>

    <!-- Alertas recentes -->
    <div style="background:#fff;border-radius:20px;border:1px solid #e2e8f0;overflow:hidden;">
        <div style="padding:20px 28px;border-bottom:1px solid #e2e8f0;display:flex;justify-content:space-between;align-items:center;">
            <h3 style="margin:0;font-size:1rem;font-weight:700;color:#0f172a;">Alertas Recentes</h3>
            <a href="<?= UBNT_URL ?>?page=ubnt_alerts&panel_id=<?= $panelId ?>" style="font-size:0.82rem;color:#1d4ed8;text-decoration:none;font-weight:600;">Ver todos →</a>
        </div>
        <?php if (empty($alerts)): ?>
            <div style="padding:32px;text-align:center;color:#94a3b8;font-size:0.9rem;">Nenhum alerta registrado.</div>
        <?php else: ?>
            <table style="width:100%;border-collapse:collapse;">
                <thead><tr style="background:#f8fafc;">
                    <th style="padding:12px 20px;text-align:left;font-size:0.78rem;font-weight:700;color:#64748b;text-transform:uppercase;">Horário</th>
                    <th style="padding:12px 16px;text-align:left;font-size:0.78rem;font-weight:700;color:#64748b;text-transform:uppercase;">Tipo</th>
                    <th style="padding:12px 16px;text-align:left;font-size:0.78rem;font-weight:700;color:#64748b;text-transform:uppercase;">Severidade</th>
                    <th style="padding:12px 16px;text-align:left;font-size:0.78rem;font-weight:700;color:#64748b;text-transform:uppercase;">Detalhe</th>
                </tr></thead>
                <tbody>
                    <?php foreach ($alerts as $a):
                        $details = json_decode($a['details'] ?? '{}', true) ?? [];
                        $typeLabel = match($a['type']) {
                            'iface_speed'    => 'Queda de Velocidade',
                            'iface_down'     => 'Interface Down',
                            'iface_up'       => 'Interface Up',
                            'client_drop'    => 'Queda de Clientes',
                            'client_recover' => 'Recuperação de Clientes',
                            default          => $a['type'],
                        };
                        $sevColor = $a['severity'] === 'critical' ? '#dc2626' : '#d97706';
                    ?>
                    <tr style="border-bottom:1px solid #f1f5f9;">
                        <td style="padding:12px 20px;font-size:0.85rem;color:#475569;"><?= date('d/m H:i', strtotime($a['created_at'])) ?></td>
                        <td style="padding:12px 16px;font-size:0.85rem;font-weight:600;color:#0f172a;"><?= $typeLabel ?></td>
                        <td style="padding:12px 16px;">
                            <span style="background:<?= $sevColor ?>15;color:<?= $sevColor ?>;border:1px solid <?= $sevColor ?>30;border-radius:6px;padding:2px 10px;font-size:0.78rem;font-weight:700;text-transform:uppercase;"><?= $a['severity'] ?></span>
                        </td>
                        <td style="padding:12px 16px;font-size:0.82rem;color:#64748b;"><?= h($details['msg'] ?? json_encode($details)) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</div>

<?php if (!empty($clientRows) || !empty($linkRows)): ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
<?php if (!empty($clientRows)): ?>
const clientLabels = <?= $chartLabels ?>;
const clientData   = <?= $chartClients ?>;
const ccqData      = <?= $chartCcq ?>;

new Chart(document.getElementById('clientChart'), {
    type: 'line',
    data: {
        labels: clientLabels.map(l => {
            const d = new Date(l);
            return d.getHours().toString().padStart(2,'0') + ':' + d.getMinutes().toString().padStart(2,'0');
        }),
        datasets: [{
            label: 'Clientes',
            data: clientData,
            borderColor: '#1d4ed8',
            backgroundColor: 'rgba(29,78,216,0.08)',
            borderWidth: 2,
            fill: true,
            tension: 0.3,
            pointRadius: 0,
            pointHoverRadius: 4,
            yAxisID: 'y',
        }, {
            label: 'CCQ %',
            data: ccqData,
            borderColor: '#16a34a',
            backgroundColor: 'transparent',
            borderWidth: 1.5,
            borderDash: [4,4],
            fill: false,
            tension: 0.3,
            pointRadius: 0,
            pointHoverRadius: 4,
            yAxisID: 'y1',
        }]
    },
    options: {
        responsive: true,
        interaction: { mode: 'index', intersect: false },
        plugins: { legend: { position: 'top' } },
        scales: {
            y:  { beginAtZero: true, title: { display: true, text: 'Clientes' }, position: 'left' },
            y1: { beginAtZero: true, max: 100, title: { display: true, text: 'CCQ %' }, position: 'right', grid: { drawOnChartArea: false } },
            x:  { ticks: { maxTicksLimit: 12, maxRotation: 0 } }
        }
    }
});
<?php endif; ?>

<?php if (!empty($linkRows)): ?>
const linkLabels = <?= json_encode(array_column($linkRows, 'ts')) ?>;
const linkSpeeds = <?= json_encode(array_map(fn($r) => $r['iface_speed'] !== null ? (int)$r['iface_speed'] : null, $linkRows)) ?>;

new Chart(document.getElementById('linkChart'), {
    type: 'line',
    data: {
        labels: linkLabels.map(l => {
            const d = new Date(l);
            return d.getHours().toString().padStart(2,'0') + ':' + d.getMinutes().toString().padStart(2,'0');
        }),
        datasets: [{
            label: 'Velocidade (Mbps)',
            data: linkSpeeds,
            borderColor: '#d97706',
            backgroundColor: 'rgba(217,119,6,0.08)',
            borderWidth: 2,
            fill: true,
            stepped: true,
            pointRadius: 0,
            pointHoverRadius: 4,
        }]
    },
    options: {
        responsive: true,
        plugins: { legend: { position: 'top' } },
        scales: {
            y: {
                ticks: { callback: v => v + 'M' },
                min: 0,
                max: 1100,
                title: { display: true, text: 'Mbps' }
            },
            x: { ticks: { maxTicksLimit: 12, maxRotation: 0 } }
        }
    }
});
<?php endif; ?>
</script>
<?php endif; ?>

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