<?php
require_once __DIR__ . '/../../includes/header.php';
require_once __DIR__ . '/../../mikrotik/includes/bandwidth.php';

$pdo = db();
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$id) { header('Location: mikrotik/index.php?page=nms_devices'); exit; }

$s = $pdo->prepare("SELECT * FROM nms_devices WHERE id=? AND user_id=?");
$s->execute([$id, $user['id']]);
$dev = $s->fetch();
if (!$dev) { echo "<p>Equipamento não encontrado.</p>"; require __DIR__.'/../../includes/footer.php'; exit; }

// Interfaces
$ifStmt = $pdo->prepare("SELECT * FROM nms_interfaces WHERE device_id=? ORDER BY last_status ASC, if_name ASC");
$ifStmt->execute([$id]);
$interfaces = $ifStmt->fetchAll();

// Métricas recentes (24h)
$metStmt = $pdo->prepare("SELECT cpu_pct, memory_pct, recorded_at FROM nms_device_metrics WHERE device_id=? AND recorded_at >= NOW() - INTERVAL 24 HOUR ORDER BY recorded_at ASC LIMIT 288");
$metStmt->execute([$id]);
$metrics = $metStmt->fetchAll();

// PPPoE ativos (último snapshot)
$pppoeStmt = $pdo->prepare("SELECT COUNT(*) FROM nms_pppoe_clients WHERE device_id=? AND DATE(snapshot_at)=CURDATE()");
$pppoeStmt->execute([$id]);
$pppoeCount = (int)$pppoeStmt->fetchColumn();

$cpuColor = ($dev['last_cpu'] ?? 0) > 80 ? '#ef4444' : (($dev['last_cpu'] ?? 0) > 60 ? '#f59e0b' : '#22c55e');
?>

<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="<?= NMS_URL ?>?page=nms_dashboard" style="color:#3b82f6; text-decoration:none; font-weight:600;">NMS</a>
        <span>›</span>
        <a href="<?= NMS_URL ?>?page=nms_devices" style="color:#3b82f6; text-decoration:none; font-weight:600;">Equipamentos</a>
        <span>›</span>
        <span style="color:#0f172a; font-weight:700;"><?= h($dev['name']) ?></span>
    </div>

    <!-- Header Card -->
    <div style="background:linear-gradient(135deg,#1e293b,#0f172a); border-radius:20px; padding:28px 32px; color:#f1f5f9; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:16px;">
        <div>
            <div style="display:flex; align-items:center; gap:10px; margin-bottom:6px;">
                <span style="width:12px;height:12px;border-radius:50%;background:<?= $dev['last_status']==='online'?'#22c55e':($dev['last_status']==='offline'?'#ef4444':'#94a3b8') ?>;display:inline-block;"></span>
                <h1 style="margin:0; font-size:1.6rem; font-weight:900;"><?= h($dev['name']) ?></h1>
            </div>
            <code style="color:#94a3b8; font-size:1rem;"><?= h($dev['hostname']) ?></code>
            <div style="margin-top:10px; display:inline-flex; align-items:center; gap:6px; background:rgba(255,255,255,0.07); padding:5px 12px; border-radius:20px; font-size:0.78rem; color:#94a3b8;">
                <span style="width:7px;height:7px;border-radius:50%;background:#22c55e;display:inline-block;animation:pulse 1.5s infinite;"></span>
                Atualizando em <strong id="refresh-counter" style="color:#f1f5f9; margin:0 2px;">30s</strong>
            </div>
            <style>@keyframes pulse{0%,100%{opacity:1}50%{opacity:0.4}}</style>
            <?php if ($dev['location']): ?><span style="color:#64748b; margin-left:10px; font-size:0.85rem;">📍 <?= h($dev['location']) ?></span><?php endif; ?>
        </div>
        <div style="display:flex; gap:20px; flex-wrap:wrap; align-items:center;">
            <?php $metricCards = [['CPU', $dev['last_cpu']!==null?$dev['last_cpu'].'%':'—', $cpuColor],['RAM', $dev['last_memory_pct']!==null?$dev['last_memory_pct'].'%':'—', '#94a3b8'],['Uptime', $dev['uptime_seconds']!==null?format_uptime((int)$dev['uptime_seconds']):'—', '#3b82f6']]; ?>
            <?php foreach ($metricCards as [$label,$val,$color]): ?>
                <div style="text-align:center;">
                    <div style="font-size:1.5rem; font-weight:800; color:<?= $color ?>;"><?= $val ?></div>
                    <div style="font-size:0.7rem; text-transform:uppercase; color:#64748b; letter-spacing:1px;"><?= $label ?></div>
                </div>
            <?php endforeach; ?>
            <?php if ($pppoeCount > 0): ?>
                <div style="text-align:center;">
                    <div style="font-size:1.5rem; font-weight:800; color:#8b5cf6;"><?= $pppoeCount ?></div>
                    <div style="font-size:0.7rem; text-transform:uppercase; color:#64748b; letter-spacing:1px;">PPPoE</div>
                </div>
            <?php endif; ?>
            <!-- Ações rápidas -->
            <div style="display:flex; gap:8px; margin-left:8px;">
                <a href="<?= NMS_URL ?>?page=nms_device_form&id=<?= $id ?>" title="Editar"
                    style="display:inline-flex; align-items:center; gap:6px; padding:9px 16px; background:rgba(255,255,255,0.1); color:#f1f5f9; border-radius:10px; text-decoration:none; font-size:0.82rem; font-weight:700; border:1px solid rgba(255,255,255,0.15); transition:0.2s;"
                    onmouseover="this.style.background='rgba(255,255,255,0.18)'" onmouseout="this.style.background='rgba(255,255,255,0.1)'">
                    <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>
                <form method="post" action="<?= NMS_URL ?>?page=nms_devices" style="margin:0;"
                    onsubmit="return confirm('Remover <?= addslashes(h($dev['name'])) ?>? Todos os dados coletados serão apagados permanentemente.');">
                    <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
                    <input type="hidden" name="action" value="delete_device">
                    <input type="hidden" name="id" value="<?= $id ?>">
                    <button type="submit" title="Deletar"
                        style="display:inline-flex; align-items:center; gap:6px; padding:9px 16px; background:rgba(239,68,68,0.2); color:#fca5a5; border:1px solid rgba(239,68,68,0.3); border-radius:10px; font-size:0.82rem; font-weight:700; cursor:pointer; transition:0.2s;"
                        onmouseover="this.style.background='rgba(239,68,68,0.35)'" onmouseout="this.style.background='rgba(239,68,68,0.2)'">
                        <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                        Deletar
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- Gráfico CPU/RAM -->
    <?php if (!empty($metrics)): ?>
    <div style="background:#fff; border-radius:16px; border:1px solid #e2e8f0; padding:24px;">
        <h3 style="margin:0 0 16px; font-size:1rem; font-weight:700; color:#0f172a;">📊 CPU &amp; RAM — Últimas 24h</h3>
        <canvas id="metricsChart" style="max-height:200px;"></canvas>
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            const labels = <?= json_encode(array_map(fn($m) => (new DateTimeImmutable($m['recorded_at']))->format('H:i'), $metrics)) ?>;
            const cpu    = <?= json_encode(array_map(fn($m) => $m['cpu_pct'], $metrics)) ?>;
            const mem    = <?= json_encode(array_map(fn($m) => $m['memory_pct'], $metrics)) ?>;
            const ctx = document.getElementById('metricsChart').getContext('2d');
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels,
                    datasets: [
                        { label: 'CPU %', data: cpu, borderColor: '#3b82f6', backgroundColor: 'rgba(59,130,246,0.08)', tension: 0.4, fill: true, pointRadius: 0 },
                        { label: 'RAM %', data: mem, borderColor: '#8b5cf6', backgroundColor: 'rgba(139,92,246,0.08)', tension: 0.4, fill: true, pointRadius: 0 }
                    ]
                },
                options: { responsive: true, plugins: { legend: { position: 'top' } }, scales: { y: { min: 0, max: 100, ticks: { callback: v => v+'%' } } } }
            });
        });
        </script>
    </div>
    <?php endif; ?>

    <!-- Interfaces -->
    <div style="background:#fff; border-radius:16px; border:1px solid #e2e8f0; overflow:hidden;">
        <div style="padding:20px 24px; border-bottom:1px solid #e2e8f0; background:#f8fafc; display:flex; justify-content:space-between; align-items:center;">
            <h3 style="margin:0; font-size:1.1rem; font-weight:800; color:#0f172a;">🔌 Interfaces (<?= count($interfaces) ?>)</h3>
            <?php if ($pppoeCount > 0): ?>
                <a href="<?= NMS_URL ?>?page=nms_pppoe&id=<?= $id ?>" style="font-size:0.95rem; color:#8b5cf6; font-weight:700; text-decoration:none;">Ver PPPoE ativos (<?= $pppoeCount ?>) →</a>
            <?php endif; ?>
        </div>
        <?php if (empty($interfaces)): ?>
            <div style="padding:32px; text-align:center; color:#94a3b8;"><div style="font-size:2rem;">🔌</div><p style="margin-top:8px; font-size:1rem;">Aguardando polling das interfaces...</p></div>
        <?php else: ?>
            <div style="overflow-x:auto;">
                <table style="width:100%; border-collapse:collapse; font-size:1rem;">
                    <thead>
                        <tr style="background:#f8fafc;">
                            <th style="padding:14px 16px; text-align:left; font-weight:700; color:#475569; font-size:0.85rem; text-transform:uppercase; border-bottom:2px solid #e2e8f0;">Interface</th>
                            <th style="padding:14px 16px; text-align:center; font-weight:700; color:#475569; font-size:0.85rem; text-transform:uppercase; border-bottom:2px solid #e2e8f0;">Status</th>
                            <th style="padding:14px 16px; text-align:center; font-weight:700; color:#22c55e; font-size:0.85rem; text-transform:uppercase; border-bottom:2px solid #e2e8f0;">↓ Entrada</th>
                            <th style="padding:14px 16px; text-align:center; font-weight:700; color:#ef4444; font-size:0.85rem; text-transform:uppercase; border-bottom:2px solid #e2e8f0;">↑ Saída</th>
                            <th style="padding:14px 16px; text-align:center; font-weight:700; color:#475569; font-size:0.85rem; text-transform:uppercase; border-bottom:2px solid #e2e8f0;">Velocidade</th>
                            <th style="padding:14px 16px; text-align:center; font-weight:700; color:#475569; font-size:0.85rem; text-transform:uppercase; border-bottom:2px solid #e2e8f0;">Último Poll</th>
                            <th style="padding:14px 16px; text-align:center; font-weight:700; color:#475569; font-size:0.85rem; text-transform:uppercase; border-bottom:2px solid #e2e8f0;">Banda</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($interfaces as $iface): ?>
                            <tr style="border-bottom:1px solid #f1f5f9; transition:background 0.15s;" onmouseover="this.style.background='#f8fafc'" onmouseout="this.style.background='transparent'">
                                <td style="padding:14px 16px;">
                                    <div style="font-weight:800; color:#0f172a; font-size:1rem;"><?= h($iface['if_name']) ?></div>
                                    <?php if ($iface['if_alias']): ?><div style="font-size:0.85rem; color:#94a3b8; margin-top:2px;"><?= h($iface['if_alias']) ?></div><?php endif; ?>
                                </td>
                                <td style="padding:14px 16px; text-align:center;">
                                    <?php if ($iface['last_status']==='up'): ?>
                                        <span style="background:#dcfce7; color:#166534; padding:5px 16px; border-radius:20px; font-weight:800; font-size:0.88rem;">UP</span>
                                    <?php elseif ($iface['last_status']==='down'): ?>
                                        <span style="background:#fee2e2; color:#991b1b; padding:5px 16px; border-radius:20px; font-weight:800; font-size:0.88rem;">DOWN</span>
                                    <?php else: ?>
                                        <span style="background:#f1f5f9; color:#64748b; padding:5px 16px; border-radius:20px; font-size:0.88rem;">?</span>
                                    <?php endif; ?>
                                </td>
                                <td style="padding:14px 16px; text-align:center; font-weight:800; color:#22c55e; font-size:1.05rem;">
                                    <?= $iface['last_in_bps'] !== null ? format_bps((int)$iface['last_in_bps']) : '—' ?>
                                </td>
                                <td style="padding:14px 16px; text-align:center; font-weight:800; color:#ef4444; font-size:1.05rem;">
                                    <?= $iface['last_out_bps'] !== null ? format_bps((int)$iface['last_out_bps']) : '—' ?>
                                </td>
                                <td style="padding:14px 16px; text-align:center; color:#64748b; font-size:0.95rem; font-weight:600;">
                                    <?= $iface['if_speed_bps'] ? format_bps((int)$iface['if_speed_bps']) : '—' ?>
                                </td>
                                <td style="padding:14px 16px; text-align:center; color:#94a3b8; font-size:0.92rem;">
                                    <?= $iface['last_polled_at'] ? (new DateTimeImmutable($iface['last_polled_at']))->format('H:i:s') : '—' ?>
                                </td>
                                <td style="padding:14px 16px; text-align:center;">
                                    <button onclick="toggleBwChart(<?= (int)$iface['id'] ?>)" title="Gráfico de banda"
                                        style="display:inline-flex; align-items:center; gap:6px; padding:8px 16px; background:#eff6ff; color:#3b82f6; border:1px solid #bfdbfe; border-radius:8px; font-size:0.88rem; font-weight:700; cursor:pointer; transition:0.2s;"
                                        onmouseover="this.style.background='#dbeafe'" onmouseout="this.style.background='#eff6ff'">
                                        <svg width="15" height="15" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/></svg>
                                        Gráfico
                                    </button>
                                </td>
                            </tr>
                            <!-- Row expandível com gráfico de banda -->
                            <tr id="bwrow-<?= (int)$iface['id'] ?>" style="display:none;">
                                <td colspan="7" style="padding:0; background:#f8fafc; border-bottom:2px solid #e2e8f0;">
                                    <div style="padding:24px 28px;">
                                        <div style="display:flex; align-items:center; gap:16px; margin-bottom:18px; flex-wrap:wrap;">
                                            <span style="font-size:1rem; font-weight:800; color:#0f172a;">📊 Banda — <?= h($iface['if_name']) ?></span>
                                            <div style="display:flex; gap:8px;">
                                                <?php foreach (['1h'=>'1 hora','24h'=>'24 horas'] as $period=>$label): ?>
                                                    <button onclick="loadBwChart(<?= (int)$iface['id'] ?>, '<?= $period ?>')"
                                                        id="btn-<?= (int)$iface['id'] ?>-<?= $period ?>"
                                                        style="padding:7px 16px; border-radius:8px; font-size:0.9rem; font-weight:700; cursor:pointer; border:1px solid #e2e8f0; background:#fff; color:#64748b; transition:0.2s;"><?= $label ?></button>
                                                <?php endforeach; ?>
                                            </div>
                                            <div id="bw-loading-<?= (int)$iface['id'] ?>" style="display:none; font-size:0.9rem; color:#94a3b8; font-weight:600;">Carregando...</div>
                                        </div>
                                        <div style="position:relative; height:240px;">
                                            <canvas id="bwchart-<?= (int)$iface['id'] ?>"></canvas>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>

</div>

<script>
(function() {
    var seconds = 30;
    var el = document.getElementById('refresh-counter');
    var interval = setInterval(function() {
        seconds--;
        if (el) el.textContent = seconds + 's';
        if (seconds <= 0) { clearInterval(interval); location.reload(); }
    }, 1000);
})();
</script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
const _bwCharts = {};
const _bwPeriod = {};

function toggleBwChart(ifaceId) {
    const row = document.getElementById('bwrow-' + ifaceId);
    const visible = row.style.display !== 'none';
    row.style.display = visible ? 'none' : '';
    if (!visible && !_bwCharts[ifaceId]) {
        loadBwChart(ifaceId, '1h');
    }
}

function loadBwChart(ifaceId, period) {
    _bwPeriod[ifaceId] = period;
    // Highlight active button
    ['1h','24h'].forEach(p => {
        const btn = document.getElementById('btn-' + ifaceId + '-' + p);
        if (btn) {
            btn.style.background = p === period ? '#3b82f6' : '#fff';
            btn.style.color      = p === period ? '#fff'    : '#64748b';
            btn.style.borderColor = p === period ? '#3b82f6' : '#e2e8f0';
        }
    });

    const loading = document.getElementById('bw-loading-' + ifaceId);
    if (loading) loading.style.display = '';

    fetch('<?= NMS_URL ?>?page=nms_api_history&interface_id=' + ifaceId + '&period=' + period)
        .then(r => r.json())
        .then(data => {
            if (loading) loading.style.display = 'none';
            if (data.error) return;

            const canvas = document.getElementById('bwchart-' + ifaceId);
            if (!canvas) return;

            if (_bwCharts[ifaceId]) {
                _bwCharts[ifaceId].destroy();
            }

            _bwCharts[ifaceId] = new Chart(canvas.getContext('2d'), {
                type: 'line',
                data: {
                    labels: data.labels,
                    datasets: [
                        { label: '↓ Entrada', data: data.in_bps,  borderColor: '#22c55e', backgroundColor: 'rgba(34,197,94,0.08)',  tension: 0.4, fill: true, pointRadius: 0 },
                        { label: '↑ Saída',   data: data.out_bps, borderColor: '#ef4444', backgroundColor: 'rgba(239,68,68,0.08)',   tension: 0.4, fill: true, pointRadius: 0 }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: { mode: 'index' },
                    plugins: { legend: { position: 'top', labels: { boxWidth: 12 } } },
                    scales: {
                        y: { ticks: { callback: v => formatBps(v) } },
                        x: { ticks: { maxTicksLimit: 10 } }
                    }
                }
            });
        })
        .catch(() => { if (loading) loading.style.display = 'none'; });
}

function formatBps(bps) {
    if (bps >= 1e9) return (bps/1e9).toFixed(1) + ' Gbps';
    if (bps >= 1e6) return (bps/1e6).toFixed(1) + ' Mbps';
    if (bps >= 1e3) return (bps/1e3).toFixed(0) + ' Kbps';
    return bps + ' bps';
}
</script>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
