<?php

$stmt = $pdo->prepare("SELECT akun,id_setting_mikrotik FROM pelanggan WHERE id = :id");
$stmt->execute(['id' => $page[1]]);
$isi = $stmt->fetch(PDO::FETCH_ASSOC);
$user = $isi['akun'];

$stmt = $pdo->prepare("SELECT * FROM setting_mikrotik WHERE id = :id");
$stmt->execute(['id' => $isi['id_setting_mikrotik']]);
$mik = $stmt->fetch(PDO::FETCH_ASSOC);

$API = new RouterosAPI(); // Inisialisasi objek API
$API->debug = false; // Ubah ke true untuk debugging jika ada masalah

if ($API->connect2($mik['ip_address'], $mik['username'], $mik['password'], $mik['port_api'])) {
    try {
        // Ambil daftar pengguna PPP aktif
        $API->write('/ppp/active/print');
        $activeUsers = $API->read();

        if (!empty($activeUsers)) {
            $trafikData = []; // Array untuk menyimpan data trafik

            foreach ($activeUsers as $user) {
                $interface = $user['.id']; // ID unik antarmuka PPP
                $usernamePPP = $user['name']; // Nama pengguna PPP
                
                // Ambil data trafik dari antarmuka terkait
                $API->write('/interface/monitor-traffic', false);
                $API->write('=interface=' . $user['.id'], false);
                $API->write('=once=');
                $trafficStats = $API->read();

                // Parsing trafik untuk antarmuka pengguna
                if (!empty($trafficStats)) {
                    $trafikData[] = [
                        'username' => $usernamePPP,
                        'tx' => $trafficStats[0]['tx-bits-per-second'] ?? 0, // Trafik TX
                        'rx' => $trafficStats[0]['rx-bits-per-second'] ?? 0  // Trafik RX
                    ];
                }
            }

            // Mengirimkan data trafik sebagai JSON
            header('Content-Type: application/json');
            echo json_encode(['status' => 'success', 'data' => $trafikData]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'No active PPP users found']);
        }
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    } finally {
        $API->disconnect(); // Tutup koneksi
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Failed to connect to MikroTik']);
}
?>
