<?php declare(strict_types=1);
/**
 * @author Ryan Spaeth <rspaeth@spaethtech.com>
 * @copyright 2025 - Spaeth Technologies, Archous Networks
 */

use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\GuzzleException;


if (!defined("PUBLIC_PAGE") || !PUBLIC_PAGE)
    die("This page is not accessible from outside the plugin.");

global $server;
global $plugin;
global $config;
global $data;

if ($config->get("all_services"))
    return;

// TODO: Add to configuration?
// $client = $server->getUcrmClient();
// $response = $client->get("service-plans?servicePlanType=internet");
// $service_plans = json_decode($response->getBody()->getContents(), true);
// dump($service_plans);

try
{
    $rest = $server->getUcrmClient();

    $response = $rest->get("clients/services/{$_GET["_serviceId"]}");
    $service = json_decode($response->getBody()->getContents(), true);

    $response = $rest->get("clients/{$service["clientId"]}");
    $client = json_decode($response->getBody()->getContents(), true);

    //$response = $client->get("organizations/{$client["organizationId"]}");
    //$organization = json_decode($response->getBody()->getContents(), true);



    $rest = $server->getUnmsClient();

    $response = $rest->get("devices?siteId={$service["unmsClientSiteId"]}");
    $devices = json_decode($response->getBody()->getContents(), true);



    // NOTE: We include only what we need, to prevent HTTP 414 - URI Too Long!
    // $data["service"] = [
    //     "id" => $service["id"],
    //     "attributes" => $service["attributes"],
    //     "service_plan_id" => $service["servicePlanId"],
    // ];
    $data["service"] = $service;

    // $data["client"] = [
    //     "id" => $client["id"],
    //     "organization" => $client["organizationName"],
    //     "name" => $client["firstName"] . " " . $client["lastName"],
    //     "company" => $client["companyName"] ?? "",
    //     "address" => $client["fullAddress"],
    //     "contacts" => $client["contacts"],
    // ];
    $data["client"] = $client;

    // $data["devices"] = array_map(function($device) {
    //     return [
    //         "id" => $device["identification"]["id"],
    //         "name" => $device["identification"]["name"],
    //         "mac" => strtoupper($device["identification"]["mac"] ?? ""),

    //     ];
    // }, $devices);
    $data["devices"] = $devices;
}
catch (GuzzleException $e)
{
    //dump($e);
    die("An error occurred!");
}




