<?php
/**
 * Simple Queue helpers for MikroTik (RouterOS API)
 */

require_once __DIR__ . '/mikrotik_client.php';

function mt_fetch_simple_queues($api): array
{
    $rows = $api->comm('/queue/simple/print');
    return is_array($rows) ? $rows : [];
}

function mt_find_queue_by_target(array $queues, string $ip): ?array
{
    $ip = trim($ip);
    if ($ip === '') return null;

    foreach ($queues as $q) {
        // target can be "IP" or "IP/32" or list
        $target = (string)($q['target'] ?? '');
        if ($target === '') continue;
        $parts = preg_split('/[,\s]+/', $target);
        foreach ($parts as $p) {
            $p = trim($p);
            if ($p === '') continue;
            $p = preg_replace('#/\d+$#', '', $p);
            if ($p === $ip) {
                return $q;
            }
        }
    }
    return null;
}

function mt_queue_disable($api, string $queueId, bool $disable): bool
{
    $api->comm('/queue/simple/set', [
        'numbers' => $queueId,
        'disabled' => $disable ? 'yes' : 'no',
    ]);
    return true;
}

function mt_queue_set_limit($api, string $queueId, string $maxLimit, string $name = null, string $parent = null): bool
{
    $payload = [
        'numbers' => $queueId,
        'max-limit' => $maxLimit,
    ];
    if ($name !== null) $payload['name'] = $name;
    if ($parent !== null && $parent !== '') $payload['parent'] = $parent;
    $api->comm('/queue/simple/set', $payload);
    return true;
}

function mt_queue_add($api, string $targetIp, string $maxLimit, string $name = '', string $parent = ''): bool
{
    $payload = [
        'name' => $name !== '' ? $name : $targetIp,
        'target' => $targetIp,
        'max-limit' => $maxLimit,
    ];
    if ($parent !== '') $payload['parent'] = $parent;
    $api->comm('/queue/simple/add', $payload);
    return true;
}

function mt_parse_queue_bytes(?string $bytesField): array
{
    // RouterOS returns bytes as "rx/tx"
    if (!$bytesField) return ['rx' => 0, 'tx' => 0];
    $parts = explode('/', trim($bytesField));
    if (count($parts) !== 2) return ['rx' => 0, 'tx' => 0];
    return ['rx' => (int)$parts[0], 'tx' => (int)$parts[1]];
}
