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

use GuzzleHttp\Client;
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;

$body = file_get_contents("php://input");
$json = json_decode($body, true);
$path = "plugin/{$json['entity']}/{$json['changeType']}";
$data = [ ...$data, "data" => $json ];

// TODO: Use the incoming webhook to make the information passed to the Workflow
// a little simpler.


if($json["entity"] === "service")
{
    switch($json["changeType"])
    {
        // Created (immediate activation)
        case "insert":
            $prev = null;
            $curr = $json["extraData"]["entity"];
            // status: 1 // Active
            break;

        // Delete = suspend, end, archive


        case "archive": // delete
            $prev = null;
            $curr = $json["extraData"]["entity"];
            // status: 2 // Ended
            break;
        case "end":
            $prev = null;
            $curr = $json["extraData"]["entity"];
            // status: 2 // Ended
            break;

        case "suspend":
            $prev = $json["extraData"]["entityBeforeEdit"]; // status: 4 // Prepared blocked
            $curr = $json["extraData"]["entity"]; // status: 5 // Obsolete
            break;

    }

}







try
{
    $head = new Client();
    $auth = $plugin->getAuth();

    $response = $head->put("$provisioner_url/api/v2/webhook/$path", [
        "headers" => [
            "Content-Type" => "application/json",
            "X-Auth-Token" => $auth->getXAuthToken(),
        ],
        "json" => $data,
    ]);

    //$body = $response->getBody()->getContents();
    //$body = json_decode($body, true);
    die();
}
catch (GuzzleException $e) {
    $message = match ($e->getCode()) {
        400 => "Bad Request",
        401 => "Unauthorized Instance",
        403 => "Service Plan Not Supported",
        404 => "Provisioner Not Found",
        default => "Provisioner Error",
    };
    $logger->error("Webhook Error", [$path, $e->getMessage()]);
    /*
    ?><script>
    message = "<?php echo $message; ?>";
    updateMessage(message);
    if (route === "client/service") {
        hideWidget();
        console.error(message, "(Widget Hidden)");
    }
    </script><?php
    */
    die();
}




// 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!");
// }




