<?php
/**
 * MikroTik Client helper (RouterOS API)
 *
 * Reads connection settings from DB table `mikrotik_settings` (first row).
 * Expected columns (from backups):
 *   host, username, password, api_port, queue_parent, cut_speed, limit_speed
 */

require_once __DIR__ . '/../routeros_api.class.php';

function mt_get_settings(mysqli $conn): array
{
    $res = $conn->query("SELECT * FROM mikrotik_settings ORDER BY id ASC LIMIT 1");
    $s = $res ? $res->fetch_assoc() : null;

    // Safe defaults if settings row does not exist yet
    if (!$s) {
        return [
            'host' => '192.168.88.1',
            'username' => 'admin',
            'password' => 'admin',
            'api_port' => 8728,
            'queue_parent' => '',
            'cut_speed' => '0/0',
            'limit_speed' => '512k/512k',
            'subscriber_interface' => '',
            'wan_interface' => '',
        ];
    }

    // Add optional fields if missing
    if (!isset($s['subscriber_interface'])) $s['subscriber_interface'] = '';
    if (!isset($s['wan_interface'])) $s['wan_interface'] = '';

    // Normalize port
    $port = (int)($s['api_port'] ?? 8728);
    if ($port <= 0) $port = 8728;
    $s['api_port'] = $port;

    return $s;
}

function mt_connect(mysqli $conn)
{
    $s = mt_get_settings($conn);
    $api = new RouterosAPI();
    $api->port = (int)($s['api_port'] ?? 8728);
    $api->timeout = 5;

    if ($api->connect($s['host'], $s['username'], $s['password'])) {
        return $api;
    }
    return false;
}

function mt_disconnect($api): void
{
    if ($api && method_exists($api, 'disconnect')) {
        $api->disconnect();
    }
}

function mt_list_interfaces($api): array
{
    $rows = $api->comm('/interface/print');
    $out = [];
    if (is_array($rows)) {
        foreach ($rows as $r) {
            if (!empty($r['name'])) {
                $out[] = $r['name'];
            }
        }
    }
    sort($out);
    return $out;
}

function mt_monitor_traffic($api, string $interface): array
{
    // Returns: rx-bits-per-second, tx-bits-per-second
    $rows = $api->comm('/interface/monitor-traffic', [
        'interface' => $interface,
        'once' => '',
    ]);

    if (!is_array($rows) || !isset($rows[0])) {
        return ['rx_bps' => 0, 'tx_bps' => 0];
    }

    $r = $rows[0];
    return [
        'rx_bps' => (int)($r['rx-bits-per-second'] ?? 0),
        'tx_bps' => (int)($r['tx-bits-per-second'] ?? 0),
    ];
}
