<?php
/**
 * SNMP Poller — Executa via cron a cada 60s
 * Coleta CPU, RAM, Uptime e tráfego de interfaces via SNMP
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/includes/snmp.php';
require_once __DIR__ . '/includes/bandwidth.php';

$pdo = db();

// Busca todos devices ativos com SNMP habilitado
$stmt = $pdo->query("SELECT * FROM nms_devices WHERE active = 1 AND snmp_enabled = 1");
$devices = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($devices)) {
    exit(0);
}

foreach ($devices as $device) {
    $deviceId = (int)$device['id'];
    $now = date('Y-m-d H:i:s');

    // == 1. Coleta métricas do sistema ==
    $cpu    = nms_get_cpu($device);
    $memPct = nms_get_memory_pct($device);
    $uptime = nms_get_uptime($device);
    $status = ($cpu !== null || $uptime !== null) ? 'online' : 'offline';

    // Atualiza status e métricas no device
    $pdo->prepare("
        UPDATE nms_devices
        SET last_status = ?, last_check_at = ?, last_cpu = ?, last_memory_pct = ?, uptime_seconds = ?
        WHERE id = ?
    ")->execute([$status, $now, $cpu, $memPct, $uptime, $deviceId]);

    // Salva histórico de métricas
    if ($status === 'online') {
        $pdo->prepare("
            INSERT INTO nms_device_metrics (device_id, cpu_pct, memory_pct, uptime_seconds, recorded_at)
            VALUES (?, ?, ?, ?, ?)
        ")->execute([$deviceId, $cpu, $memPct, $uptime, $now]);
    }

    if ($status === 'offline') {
        continue;
    }

    // == 2. Coleta interfaces ==
    $interfaces = nms_get_interfaces($device);
    if (empty($interfaces)) {
        continue;
    }

    // Busca valores anteriores de octetos para calcular delta
    $prevStmt = $pdo->prepare("SELECT id, if_index, last_in_octets, last_out_octets, last_polled_at FROM nms_interfaces WHERE device_id = ?");
    $prevStmt->execute([$deviceId]);
    $prevData = [];
    foreach ($prevStmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $prevData[$row['if_index']] = $row;
    }

    $upsertIface = $pdo->prepare("
        INSERT INTO nms_interfaces (device_id, if_index, if_name, if_alias, if_speed_bps, last_status, last_in_bps, last_out_bps, last_in_octets, last_out_octets, last_polled_at)
        VALUES (:device_id, :if_index, :if_name, :if_alias, :if_speed_bps, :last_status, :last_in_bps, :last_out_bps, :last_in_octets, :last_out_octets, :last_polled_at)
        ON DUPLICATE KEY UPDATE
            if_name        = VALUES(if_name),
            if_alias       = VALUES(if_alias),
            if_speed_bps   = VALUES(if_speed_bps),
            last_status    = VALUES(last_status),
            last_in_bps    = VALUES(last_in_bps),
            last_out_bps   = VALUES(last_out_bps),
            last_in_octets = VALUES(last_in_octets),
            last_out_octets= VALUES(last_out_octets),
            last_polled_at = VALUES(last_polled_at)
    ");

    $insBw = $pdo->prepare("
        INSERT INTO nms_bandwidth_history (interface_id, in_bps, out_bps, recorded_at)
        VALUES (?, ?, ?, ?)
    ");

    foreach ($interfaces as $idx => $iface) {
        $prev      = $prevData[$idx] ?? null;
        $inBps     = null;
        $outBps    = null;

        if ($prev && $prev['last_polled_at']) {
            $deltaSeconds = round((strtotime($now) - strtotime($prev['last_polled_at'])));
            if ($deltaSeconds > 0) {
                $inBps  = calculate_bps($prev['last_in_octets'],  $iface['in_octets'],  $deltaSeconds);
                $outBps = calculate_bps($prev['last_out_octets'], $iface['out_octets'], $deltaSeconds);
            }
        }

        $upsertIface->execute([
            ':device_id'    => $deviceId,
            ':if_index'     => $iface['if_index'],
            ':if_name'      => $iface['if_name'],
            ':if_alias'     => $iface['if_alias'],
            ':if_speed_bps' => $iface['if_speed_bps'],
            ':last_status'  => $iface['status'],
            ':last_in_bps'  => $inBps,
            ':last_out_bps' => $outBps,
            ':last_in_octets'  => $iface['in_octets'],
            ':last_out_octets' => $iface['out_octets'],
            ':last_polled_at'  => $now,
        ]);

        // Registra histórico de banda se tiver dados calculados
        if ($inBps !== null || $outBps !== null) {
            // Busca o ID da interface recém inserida/atualizada
            $ifIdStmt = $pdo->prepare("SELECT id FROM nms_interfaces WHERE device_id = ? AND if_index = ?");
            $ifIdStmt->execute([$deviceId, $idx]);
            $ifId = $ifIdStmt->fetchColumn();
            if ($ifId) {
                $insBw->execute([$ifId, $inBps ?? 0, $outBps ?? 0, $now]);
            }
        }
    }
}

echo "[" . date('H:i:s') . "] SNMP Poller concluído. " . count($devices) . " device(s) processado(s).\n";
