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

use SpaethTech\UCRM\SDK\Configs\PluginConfig;
use SpaethTech\UCRM\SDK\Plugin;
use SpaethTech\UCRM\SDK\Server;

require_once __DIR__ . "/bootstrap.php";

$server = new Server();
$params = $server->getParams();
$plugin = new Plugin($server);
$logger = $plugin->getLogger();

$config_new = $plugin->getConfig();
$config_old = file_exists($old_file = "data/config.json.bak")
    ? new PluginConfig($plugin, $old_file)
    : $config_new;

$new_url = $config_new->get("provisioner_url");

if (($old_url = $config_old->get("provisioner_url")) !== $new_url)
{
    $updated = false;

    if ($server->delCSP("default-src", $old_url))
    {
        $logger->debug("Deleted old CSP default-src for $old_url");
        $updated = true;
    }

    if ($server->addCSP("default-src", $new_url))
    {
        $logger->debug("Added CSP default-src for $new_url");
        $updated = true;
    }

    if ($updated)
    {
        $server->clearTwigCache();
        $logger->debug("Cleared Twig cache");
    }
}

copy("data/config.json", $old_file);

if (($nat_ip = $config_new->get("nat_ip")) !== null) {
    $nat_port = $config_new->get("nat_port") ?? "443";
    $server->setPublicUrl("https://$nat_ip:$nat_port");
}

// Perform another registration as the Provisioner URL may have changed.
$server->register($plugin, $new_url);

// Workflow Trigger
$response = $plugin->executeWorkflow("plugin/configured", [
    "config_old" => $config_old->toArray(),
    "config_new" => $config_new->toArray(),
], true);
