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

ini_set("display_errors", 0);
ini_set("log_errors", 1);
ini_set("error_log", __DIR__ . "/data/plugin.log");
error_reporting(E_ALL);

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

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

$server = new Server();
$params = $server->getParams();

$plugin = new Plugin($server);
$logger = $plugin->getLogger();
$config = $plugin->getConfig();
$ucrmDB = $server->getUcrmDB();

function get_services(): array
{
  global $ucrmDB;

  // return $ucrmDB->query(<<<SQL
  //       SELECT "service_id", "status", "superseded_by_service_id", "deleted_at", "active_from", "active_to"
  //         FROM "service";
  //       SQL
  // )->fetchAll();

  $services = $ucrmDB->query(<<<SQL
    SELECT "service_id", "status", "superseded_by_service_id", "deleted_at", "active_from", "active_to"
      FROM "service";
    SQL
  )->fetchAll();

  foreach ($services as &$service) {
    $service["attributes"] = $ucrmDB->query(<<<SQL
          SELECT "attribute_id", "value"
            FROM "service_attribute"
           WHERE "service_id" = {$service['service_id']};
        SQL
    )->fetchAll();
  }

  return $services;
}

set_error_handler(function ($level, $message, $file, $line) {
  $fatal =
    $level === E_ERROR ||
    $level === E_PARSE ||
    $level === E_CORE_ERROR ||
    $level === E_COMPILE_ERROR ||
    $level === E_USER_ERROR;

  $warning =
    $level === E_WARNING ||
    $level === E_USER_WARNING ||
    $level === E_DEPRECATED ||
    $level === E_USER_DEPRECATED;

  $server = new Server();
  $plugin = new Plugin($server);
  $plugin->executeWorkflow("plugin/error", [
    "error" => [
      "type" => "error",
      "fatal" => $fatal,
      "warning" => $warning,
      "level" => $level,
      "message" => $message,
      "file" => $file,
      "line" => $line
    ]
  ]);

  if ($fatal) {
    exit;
  }
});

set_exception_handler(function ($exception) {
  $server = new Server();
  $plugin = new Plugin($server);
  $plugin->executeWorkflow("plugin/error", [
    "error" => [
      "type" => "exception",
      "fatal" => true,
      "warning" => false,
      "level" => $exception->getCode() ?? 0,
      "message" => $exception->getMessage(),
      "file" => $exception->getFile(),
      "line" => $exception->getLine()
    ]
  ]);
  exit;
  // $plugin->getLogger()->error("Exception", [
  //     "exception" => $exception->getMessage()
  // ]);
});

//file_get_contents(__DIR__ . "/data/test.txt");
//throw new Exception("Test Exception");




