<?php
namespace PayCal\Connector;

defined('ABSPATH') || exit;

class EventClient {
  private const RATE_LIMIT_PREFIX = 'paycal_connector_event_';

  public static function send(string $event, array $details = []): array {
    $settings = ConnectorStore::get();

    if (empty($settings['platform_url']) || empty($settings['public_key']) || empty($settings['access_token'])) {
      \paycal_debug_log('[PayCal] Connector event skipped: missing Platform URL, public key or access token.');
      return ['ok' => false, 'message' => 'Missing connector event credentials'];
    }

    if (!function_exists('wp_remote_post')) {
      \paycal_debug_log('[PayCal] Connector event skipped: WordPress HTTP API unavailable.');
      return ['ok' => false, 'message' => 'WordPress HTTP API unavailable'];
    }

    $payload = self::safe_payload($event, $details);
    $rate_key = self::RATE_LIMIT_PREFIX . md5(wp_json_encode($payload));
    if (get_transient($rate_key)) {
      return ['ok' => true, 'rate_limited' => true];
    }
    set_transient($rate_key, 1, 5 * MINUTE_IN_SECONDS);

    $response = wp_remote_post(rtrim($settings['platform_url'], '/') . '/wp-json/paycal/v1/connector-event', [
      'timeout' => 10,
      'headers' => [
        'Accept' => 'application/json',
        'Content-Type' => 'application/json',
        'X-PayCal-Public-Key' => (string) $settings['public_key'],
        'X-PayCal-Token' => (string) $settings['access_token'],
      ],
      'body' => wp_json_encode($payload),
    ]);

    if (is_wp_error($response)) {
      \paycal_debug_log('[PayCal] Connector event failed: ' . $response->get_error_message());
      return ['ok' => false, 'message' => $response->get_error_message()];
    }

    $code = (int) wp_remote_retrieve_response_code($response);
    if ($code < 200 || $code >= 300) {
      \paycal_debug_log('[PayCal] Connector event returned HTTP ' . $code);
      return ['ok' => false, 'code' => $code];
    }

    return ['ok' => true, 'code' => $code];
  }

  private static function safe_payload(string $event, array $details): array {
    $last_sync = class_exists(SyncClient::class) ? SyncClient::last_sync() : [];
    $site_url = home_url('/');
    $domain = wp_parse_url($site_url, PHP_URL_HOST);

    $payload = [
      'event' => sanitize_text_field($event),
      'domain' => sanitize_text_field((string) $domain),
      'site_url' => esc_url_raw($site_url),
      'plugin_version' => defined('PAYCAL_VERSION') ? PAYCAL_VERSION : 'unknown',
      'last_sync' => sanitize_text_field((string) ($last_sync['synced_at'] ?? '')),
    ];

    foreach (['merchant_status', 'license_status', 'last_connection_result', 'error_code', 'message'] as $key) {
      if (isset($details[$key]) && is_scalar($details[$key]) && (string) $details[$key] !== '') {
        $payload[$key] = sanitize_text_field((string) $details[$key]);
      }
    }

    if (!empty($details['last_sync']) && is_scalar($details['last_sync'])) {
      $payload['last_sync'] = sanitize_text_field((string) $details['last_sync']);
    }

    return $payload;
  }
}
