<?php
/**
 * Fixed context for the public WordPress.org Free package.
 *
 * Reports the physically installed Free package and reads only a redacted subset
 * of historical metadata so an in-place downgrade does not destroy support
 * references. Historical values never alter the active package or its features.
 *
 * This file does not contact a product-license service, validate product keys,
 * schedule commercial tasks, or unlock separately distributed functionality.
 */

if (!defined('ABSPATH')) {
  exit;
}

if (!function_exists('custausu_free_package_sanitize_plan')) {
  function custausu_free_package_sanitize_plan(
    $plan,
    bool $allow_freemium = true
  ): string {
    $plan = sanitize_key((string)$plan);
    if ($plan === 'base') {
      $plan = 'advanced';
    }
    $allowed = $allow_freemium
      ? ['freemium', 'advanced', 'premium']
      : ['advanced', 'premium'];
    return in_array($plan, $allowed, true) ? $plan : '';
  }
}

if (!function_exists('custausu_free_package_plan_rank')) {
  function custausu_free_package_plan_rank(string $plan): int {
    return match (custausu_free_package_sanitize_plan($plan, true)) {
      'premium' => 30,
      'advanced' => 20,
      'freemium' => 10,
      default => 0,
    };
  }
}

if (!function_exists('custausu_free_package_clean_datetime')) {
  function custausu_free_package_clean_datetime($value): string {
    $value = sanitize_text_field((string)$value);
    return strlen($value) <= 40 ? $value : substr($value, 0, 40);
  }
}

if (!function_exists('custausu_free_package_clean_support_context')) {
  function custausu_free_package_clean_support_context($value): array {
    if (!is_array($value)) {
      return [];
    }

    $out = [];
    foreach (
      ['reference', 'customer_reference', 'order_reference', 'support_reference', 'case_id']
      as $key
    ) {
      if (!array_key_exists($key, $value)) {
        continue;
      }
      $clean = sanitize_text_field((string)$value[$key]);
      if ($clean !== '') {
        $out[$key] = substr($clean, 0, 190);
      }
    }
    return $out;
  }
}

if (!function_exists('custausu_free_package_key_tail_from_value')) {
  function custausu_free_package_key_tail_from_value($value): string {
    $value = strtoupper(preg_replace('/[^A-Z0-9]/i', '', (string)$value));
    if (strlen($value) < 4) {
      return '';
    }
    return sanitize_text_field(substr($value, -4));
  }
}

if (!function_exists('custausu_free_package_historical_key_tail')) {
  /**
   * Return only the last four safe characters of a historical product key.
   * The complete key never leaves this compatibility boundary.
   */
  function custausu_free_package_historical_key_tail(): string {
    $states = [
      get_option('cas_license_state', []),
      get_option('cas_license_client_state', []),
    ];

    foreach ($states as $state) {
      if (!is_array($state)) {
        continue;
      }
      $containers = [$state];
      if (isset($state['license']) && is_array($state['license'])) {
        $containers[] = $state['license'];
      }
      foreach ($containers as $container) {
        foreach (['license_key_tail', 'key_tail', 'tail'] as $key) {
          $tail = custausu_free_package_key_tail_from_value($container[$key] ?? '');
          if ($tail !== '') {
            return $tail;
          }
        }
        foreach (['license_key', 'key', 'stored_license_key'] as $key) {
          $tail = custausu_free_package_key_tail_from_value($container[$key] ?? '');
          if ($tail !== '') {
            return $tail;
          }
        }
      }
    }

    return '';
  }
}

if (!function_exists('custausu_free_package_stored_compatibility_state')) {
  /**
   * Read a redacted subset of historical state for support/downgrade continuity.
   * No value returned here can enable a feature in the Free package.
   */
  function custausu_free_package_stored_compatibility_state(): array {
    $primary = get_option('cas_license_state', []);
    $primary = is_array($primary) ? $primary : [];

    $legacy = get_option('cas_license_client_state', []);
    $legacy = is_array($legacy) ? $legacy : [];

    $stored = is_array($primary['license'] ?? null)
      ? $primary['license']
      : [];
    $fallback = is_array($legacy['license'] ?? null)
      ? $legacy['license']
      : $legacy;

    if ($stored === [] && is_array($fallback)) {
      $stored = $fallback;
    }

    $status = sanitize_key((string)($stored['status'] ?? 'none'));
    if (!in_array($status, ['none', 'active', 'expired', 'revoked', 'invalid'], true)) {
      $status = 'none';
    }

    $previous_plan = custausu_free_package_sanitize_plan($stored['plan'] ?? '', false);
    $support_context = custausu_free_package_clean_support_context(
      $stored['support_context'] ?? $legacy['support_context'] ?? []
    );

    return [
      'schema_version' => 1,
      'effective_plan' => 'freemium',
      'entitlement_mode' => 'freemium',
      'license' => [
        'status' => $status,
        'key' => '',
        'license_key_tail' => custausu_free_package_historical_key_tail(),
        'plan' => $previous_plan,
        'license_type' => sanitize_key((string)($stored['license_type'] ?? '')),
        'issued_at' => custausu_free_package_clean_datetime($stored['issued_at'] ?? ''),
        'expires_at' => custausu_free_package_clean_datetime($stored['expires_at'] ?? ''),
        'checked_at' => custausu_free_package_clean_datetime($stored['checked_at'] ?? ''),
        'source' => 'passive_downgrade_compatibility',
        'support_context' => $support_context,
      ],
    ];
  }
}

if (!function_exists('custausu_free_package_runtime_context')) {
  function custausu_free_package_runtime_context(): array {
    return custausu_free_package_stored_compatibility_state();
  }
}

if (!function_exists('custausu_free_package_support_context')) {
  function custausu_free_package_support_context(): array {
    $state = custausu_free_package_stored_compatibility_state();
    $historical = is_array($state['license'] ?? null) ? $state['license'] : [];

    return [
      'source' => 'public_free_package',
      'package' => [
        'edition' => function_exists('custausu_edition')
          ? custausu_edition()
          : 'freemium_wporg',
        'plan' => 'freemium',
        'separate_package_runtime_available' => false,
      ],
      'stored_compatibility' => [
        'present' => ($historical['status'] ?? 'none') !== 'none'
          || ($historical['plan'] ?? '') !== ''
          || !empty($historical['support_context']),
        'previous_status' => (string)($historical['status'] ?? 'none'),
        'previous_plan' => (string)($historical['plan'] ?? ''),
        'checked_at' => (string)($historical['checked_at'] ?? ''),
      ],
      'remote_requests' => false,
      'scheduled_validation' => false,
    ];
  }
}

if (!function_exists('custausu_free_package_plan')) {
  function custausu_free_package_plan(): string {
    return 'freemium';
  }
}

if (!function_exists('custausu_free_package_clear_legacy_schedules')) {
  /**
   * Remove a stale event left by an in-place downgrade. The Free package does
   * not contain the callback or client that originally scheduled this event.
   */
  function custausu_free_package_clear_legacy_schedules(): void {
    wp_clear_scheduled_hook('cas_license_client_auto_validate');
  }
}

add_action('plugins_loaded', 'custausu_free_package_clear_legacy_schedules', 1);
