<?php
namespace GlpiPlugin\Wbstore;

if (!defined('GLPI_ROOT')) {
   die("Sorry. You can't access this file directly");
}

/**
 * Sends events to:
 * 1) Portal-WB (same API base) /events
 * 2) External webhook: https://webhook.wbuarque.com.br/webhook/wbstore
 */
class Webhook {

   public static function event(string $event, array $data = []): void {
      $payload = [
         'event' => $event,
         'ts'    => gmdate('c'),
         'client'=> self::clientContext(),
         'glpi'  => self::glpiContext(),
         'data'  => $data,
      ];

      // Portal-WB
      try {
         $client = new StoreClient();
         $client->postRaw('/events', $payload);
      } catch (\Throwable $e) {
         error_log('[wbstore] event portal error: ' . $e->getMessage());
      }

      // External webhook
      try {
         $url = 'https://webhook.wbuarque.com.br/webhook/wbstore';
         Utils::httpPostJson($url, $payload, ((int)Config::get('ssl_verify', 1)) === 1);
      } catch (\Throwable $e) {
         error_log('[wbstore] event webhook error: ' . $e->getMessage());
      }
   }

   public static function clientContext(): array {
      return [
         'name'        => (string)Config::get('client_name', ''),
         'email'       => (string)Config::get('client_email', ''),
         'phone'       => (string)Config::get('client_phone', ''),
         'company'     => (string)Config::get('client_company', ''),
         'license_key' => (string)Config::get('license_key', ''),
         'plan'        => (string)Config::get('client_plan', ''),
      ];
   }

   public static function glpiContext(): array {
      $base = Utils::glpiUrl();
      $notify = '';
      if (is_string($base) && $base !== '') {
         $notify = rtrim($base, '/') . '/plugins/wbstore/front/notify.php';
      }

      return [
         'instance_id'  => (string)Config::get('instance_id', ''),
         'domain'       => (string)(trim((string)Config::get('domain','')) !== '' ? Config::get('domain','') : Utils::currentDomain()),
         'url'          => $base,
         'notify_url'   => $notify,
         'portal_token' => (string)Config::get('portal_token',''),
         'glpi_version' => defined('GLPI_VERSION') ? GLPI_VERSION : '',
         'php_version'  => PHP_VERSION,
      ];
   }
}
