<?php
$initialDir = getcwd();
chdir(__DIR__ . '/../');

require_once __DIR__ . '/../vendor/autoload.php';

use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;
use GuzzleHttp\Client;

$config = PluginConfigManager::create()->loadConfig();
$ipServer = $config['ipserver'] ?? 'localhost';
$unmsToken = $config['unmsApiToken'] ?? '';

if (empty($unmsToken)) {
    echo "Error: UNMS API Token is missing.\n";
    exit(1);
}

$unmsClient = new Client([
    'base_uri' => "https://{$ipServer}/nms/api/v2.1/",
    'verify' => false,
    'headers' => [
        'X-Auth-Token' => $unmsToken
    ]
]);

try {
    echo "=== FETCHING DEVICES FROM UISP ===\n";
    $response = $unmsClient->get("devices");
    $devices = json_decode($response->getBody()->getContents(), true);
    
    echo "Total devices retrieved: " . count($devices) . "\n\n";
    
    $count = 0;
    foreach ($devices as $idx => $dev) {
        if ($count >= 10) break;
        $count++;
        
        echo "Device #$idx:\n";
        echo " - Name: " . ($dev['identification']['name'] ?? 'N/A') . "\n";
        echo " - Role: " . ($dev['identification']['role'] ?? 'N/A') . "\n";
        echo " - Site ID: " . ($dev['identification']['site']['id'] ?? 'N/A') . "\n";
        echo " - Site Name: " . ($dev['identification']['site']['name'] ?? 'N/A') . "\n";
        
        // Parent Site structure
        if (isset($dev['identification']['site']['parent'])) {
            echo "   - Parent Site Name: " . ($dev['identification']['site']['parent']['name'] ?? 'N/A') . "\n";
        } else {
            echo "   - Parent Site structure: NOT PRESENT\n";
        }
        
        // apDevice structure
        if (isset($dev['attributes']['apDevice'])) {
            echo "   - apDevice Name: " . ($dev['attributes']['apDevice']['name'] ?? 'N/A') . "\n";
            echo "   - apDevice ID: " . ($dev['attributes']['apDevice']['id'] ?? 'N/A') . "\n";
        } else {
            echo "   - apDevice structure: NOT PRESENT\n";
        }
        echo "--------------------------------------\n";
    }
} catch (\Exception $e) {
    echo "Error calling UISP API: " . $e->getMessage() . "\n";
}
