<?php
/**
 * MikroTik API Poller — Executa via cron a cada 60s
 * Coleta dados via REST API do RouterOS: PPPoE, interfaces, recursos
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/includes/mikrotik_api.php';
require_once __DIR__ . '/includes/bandwidth.php';

$pdo = db();

$stmt = $pdo->query("SELECT * FROM nms_devices WHERE active = 1 AND api_enabled = 1 AND type = 'mikrotik'");
$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');

    $api = new MikrotikApi($device);

    // == 1. Recursos do sistema ==
    $res = $api->getSystemResource();
    if (!$res) {
        $pdo->prepare("UPDATE nms_devices SET last_status='offline', last_check_at=? WHERE id=?")
            ->execute([$now, $deviceId]);
        continue;
    }

    $cpuLoad   = isset($res['cpu-load']) ? (int)$res['cpu-load'] : null;
    $totalMem  = isset($res['total-memory']) ? MikrotikApi::parseMemory($res['total-memory']) : 0;
    $freeMem   = isset($res['free-memory'])  ? MikrotikApi::parseMemory($res['free-memory'])  : 0;
    $memPct    = ($totalMem > 0) ? (int)round((($totalMem - $freeMem) / $totalMem) * 100) : null;
    $uptimeSec = isset($res['uptime']) ? MikrotikApi::uptimeToSeconds($res['uptime']) : null;

    $pdo->prepare("
        UPDATE nms_devices
        SET last_status='online', last_check_at=?, last_cpu=?, last_memory_pct=?, uptime_seconds=?
        WHERE id=?
    ")->execute([$now, $cpuLoad, $memPct, $uptimeSec, $deviceId]);

    // Salva métricas históricas
    $pdo->prepare("
        INSERT INTO nms_device_metrics (device_id, cpu_pct, memory_pct, uptime_seconds, recorded_at)
        VALUES (?, ?, ?, ?, ?)
    ")->execute([$deviceId, $cpuLoad, $memPct, $uptimeSec, $now]);

    // == 2. Interfaces ==
    $ifaces = $api->getInterfaces();
    if (is_array($ifaces)) {
        $upsert = $pdo->prepare("
            INSERT INTO nms_interfaces (device_id, if_index, if_name, if_alias, if_speed_bps, last_status, last_polled_at)
            VALUES (:device_id, :if_index, :if_name, :if_alias, :if_speed_bps, :last_status, :last_polled_at)
            ON DUPLICATE KEY UPDATE
                if_name      = VALUES(if_name),
                if_alias     = VALUES(if_alias),
                last_status  = VALUES(last_status),
                last_polled_at = VALUES(last_polled_at)
        ");
        foreach ($ifaces as $i => $iface) {
            $upsert->execute([
                ':device_id'    => $deviceId,
                ':if_index'     => $i + 1,
                ':if_name'      => $iface['name'] ?? "if{$i}",
                ':if_alias'     => $iface['comment'] ?? null,
                ':if_speed_bps' => isset($iface['actual-mtu']) ? null : null, // MikroTik não retorna speed direto
                ':last_status'  => ($iface['running'] ?? false) ? 'up' : 'down',
                ':last_polled_at' => $now,
            ]);
        }
    }

    // == 3. Clientes PPPoE ativos ==
    $pppoe = $api->getPppoeActive();
    if (is_array($pppoe)) {
        // Remove snapshot anterior do device
        $pdo->prepare("DELETE FROM nms_pppoe_clients WHERE device_id = ? AND DATE(snapshot_at) = CURDATE()")
            ->execute([$deviceId]);

        $ins = $pdo->prepare("
            INSERT INTO nms_pppoe_clients (device_id, username, caller_id, address, uptime_seconds, interface, service, rx_bytes, tx_bytes, snapshot_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        foreach ($pppoe as $client) {
            $upSec = isset($client['uptime']) ? MikrotikApi::uptimeToSeconds($client['uptime']) : null;
            $ins->execute([
                $deviceId,
                $client['name'] ?? '',
                $client['caller-id'] ?? null,
                $client['address'] ?? null,
                $upSec,
                $client['interface'] ?? null,
                $client['service'] ?? null,
                isset($client['bytes-in'])  ? (int)$client['bytes-in']  : null,
                isset($client['bytes-out']) ? (int)$client['bytes-out'] : null,
                $now,
            ]);
        }
    }
}

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