<?php
namespace PayCal\Licensing;

defined('ABSPATH') || exit;

class LicenseStore {
  const OPTION = 'paycal_license_data';

  public static function get(): array {
    $data = get_option(self::OPTION, []);
    return is_array($data) ? $data : [];
  }

  public static function set(array $data): void {
    update_option(self::OPTION, self::sanitize_data($data, self::get()), false);
  }

  public static function replace(array $data): void {
    update_option(self::OPTION, self::sanitize_data($data, []), false);
  }

  public static function clear(): void {
    delete_option(self::OPTION);
  }

  public static function license_key(): string {
    $key = (string) (self::get()['license_key'] ?? '');
    if (class_exists(LicenseClient::class) && LicenseClient::looks_like_connector_credential($key)) {
      return '';
    }
    return $key;
  }

  public static function entitlements(): array {
    return (array) (self::get()['modules'] ?? []);
  }

  public static function expires_at(): string {
    return (string) (self::get()['expires_at'] ?? '');
  }

  public static function last_validated(): int {
    return (int) (self::get()['validated_at'] ?? 0);
  }

  public static function grace_until(): int {
    return (int) (self::get()['grace_until'] ?? 0);
  }

  public static function is_in_grace(): bool {
    $gu = self::grace_until();
    return $gu > 0 && time() <= $gu;
  }

  public static function mark_invalid_with_grace(int $days = 7): void {
    $data = self::get();
    $data['valid'] = false;
    $data['grace_until'] = time() + ($days * DAY_IN_SECONDS);
    self::set($data);
  }

  private static function sanitize_data(array $data, array $current): array {
    return [
      'license_key' => sanitize_text_field((string) ($data['license_key'] ?? $current['license_key'] ?? '')),
      'valid' => !empty($data['valid']),
      'plan' => sanitize_text_field((string) ($data['plan'] ?? $current['plan'] ?? '')),
      'expires_at' => sanitize_text_field((string) ($data['expires_at'] ?? $current['expires_at'] ?? '')),
      'modules' => array_values(array_filter(array_map('sanitize_text_field', (array) ($data['modules'] ?? $current['modules'] ?? [])))),
      'validated_at' => (int) ($data['validated_at'] ?? $current['validated_at'] ?? 0),
      'grace_until' => (int) ($data['grace_until'] ?? $current['grace_until'] ?? 0),
      'disabled' => !empty($data['disabled']),
    ];
  }
}
