<?php
namespace PayCal\Licensing;

use PayCal\Connector\ConnectorStore;

defined('ABSPATH') || exit;

class LicenseClient {
  const ENDPOINT = 'https://paycal.online/wp-json/paycal/v1/license/validate';

  public static function looks_like_connector_credential(string $value): bool {
    $value = trim($value);
    return (bool) preg_match('/^(mrc_|trm_|pk_)/i', $value);
  }

  public static function validate_remote(string $license_key): array {
    $license_key = trim($license_key);
    if ($license_key === '') {
      return ['ok' => false, 'error' => 'License key is required', 'reason' => 'missing'];
    }

    if (self::looks_like_connector_credential($license_key)) {
      return ['ok' => false, 'error' => 'זה נראה כמו נתון חיבור של PayCal, לא מפתח רישוי. יש להזין אותו בהגדרות Merchant / Terminal.'];
    }

    if (!function_exists('wp_remote_post')) {
      \paycal_debug_log('[PayCal] WordPress HTTP API unavailable during license validation.');
      return ['ok' => false, 'error' => 'WordPress HTTP API unavailable', 'reason' => 'transport'];
    }

    $endpoint = self::endpoint();
    $response = wp_remote_post($endpoint, [
      'timeout' => 15,
      'headers' => ['Accept' => 'application/json'],
      'body' => [
        'license_token' => $license_key,
        'license_key' => $license_key,
        'site_url'    => home_url(),
        'domain'      => wp_parse_url(home_url('/'), PHP_URL_HOST),
        'plugin_version' => defined('PAYCAL_VERSION') ? PAYCAL_VERSION : 'unknown',
      ],
    ]);

    if (is_wp_error($response)) {
      \paycal_debug_log('[PayCal] License validation failed: ' . $response->get_error_message());
      return ['ok' => false, 'error' => $response->get_error_message(), 'reason' => 'transport'];
    }

    $code = (int) wp_remote_retrieve_response_code($response);
    $body = (string) wp_remote_retrieve_body($response);
    $json = json_decode($body, true);

    if ($code < 200 || $code >= 300 || !is_array($json)) {
      \paycal_debug_log('[PayCal] Bad response from license server. HTTP ' . $code);
      return ['ok' => false, 'error' => 'Bad response from license server', 'reason' => 'bad_response'];
    }

    if (empty($json['valid'])) {
      return ['ok' => false, 'error' => 'License invalid', 'reason' => 'invalid'];
    }

    return [
      'ok' => true,
      'data' => [
        'valid'        => true,
        'license_key'  => $license_key,
        'plan'         => (string)($json['plan'] ?? ''),
        'expires_at'   => (string)($json['expires_at'] ?? ''),
        'modules'      => (array) ($json['modules'] ?? []),
        'validated_at' => time(),
        'grace_until'  => 0,
      ],
    ];
  }

  private static function endpoint(): string {
    $base = '';
    if (class_exists(ConnectorStore::class)) {
      $settings = ConnectorStore::get();
      $base = (string) ($settings['platform_url'] ?? '');
    }
    if ($base === '') {
      return self::ENDPOINT;
    }
    return rtrim($base, '/') . '/wp-json/paycal/v1/license/validate';
  }
}
