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

use SpaethTech\UCRM\SDK\Enums\ClientServiceWidgets;
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 = $plugin->getConfig();

$provisioner_url = $config->get("provisioner_url");

if ($server->addCSP("default-src", $provisioner_url))
{
    $server->clearTwigCache();
    $logger->debug("Added CSP connect-src for $provisioner_url");
}

$server->moveClientServiceWidget(
    ClientServiceWidgets::PLUGIN_WIDGETS,
    ClientServiceWidgets::PREPAID_PERIODS
);

// Perform another registration to the provisioner.
$server->register($plugin, $plugin->getConfig()->get("provisioner_url"));

// Workflow Trigger
$response = $plugin->executeWorkflow("plugin/enabled", [], true);

// # region WebHook

// $ucrmDB = $server->getUcrmDB();
// $unmsDB = $server->getUnmsDB();

// $name = $plugin->getName();

// $hook = [
//     "url" => "http://localhost/crm/_plugins/$name/public.php?route=/webhook",
//     "is_active" => 1,
//     "any_event" => 0,
//     //"verify_ssl_certificate" => 1,
//     "verify_ssl_certificate" => 0,
// ];

// $query = $ucrmDB->query(<<<SQL
//     SELECT * FROM webhook_address
//     -- WHERE url = '{$hook["url"]}';
//     WHERE url LIKE '%/crm/_plugins/$name/public.php?route=/webhook';
//     SQL
// )->fetchAll();

// if (count($query) === 0)
// {
//     $query = $ucrmDB->prepare(<<<SQL
//         INSERT INTO webhook_address
//         ( url, is_active, any_event, verify_ssl_certificate )
//         VALUES
//         ( :url, :is_active, :any_event, :verify_ssl_certificate );
//         SQL
//     );
//     $query->execute($hook);

//     $webhook_address_id = $ucrmDB->lastInsertId();

//     $ucrmDB->exec(<<<SQL
//         INSERT INTO webhook_address_webhook_event_type
//         ( webhook_address_id, webhook_event_type_id )
//         VALUES
//         ( $webhook_address_id, 19 ), -- service.activate
//         ( $webhook_address_id, 20 ), -- service.add
//         ( $webhook_address_id, 21 ), -- service.archive
//         --( $webhook_address_id, 22 ), -- service.edit
//         ( $webhook_address_id, 23 ), -- service.end
//         ( $webhook_address_id, 24 ), -- service.postpone
//         ( $webhook_address_id, 25 ), -- service.suspend
//         ( $webhook_address_id, 26 ); -- service.suspend_cancel
//         SQL
//     );

//     $logger->debug("WebHook has been installed.");
// }
// else
// {
//     $ucrmDB->exec(<<<SQL
//         UPDATE webhook_address
//         SET deleted_at = DEFAULT
//         WHERE url LIKE '%/crm/_plugins/$name/public.php?route=/webhook';
//         SQL
//     );

//     $logger->debug("WebHook has been reactivated.");
// }

// # endregion