<?php

declare(strict_types=1);

namespace Australcode\Rewards\Infrastructure\Licensing;

use Australcode\Rewards\Service\Licensing\FreemiusGateway;

defined( 'ABSPATH' ) || exit;

/**
 * Production adapter of {@see FreemiusGateway} over the real Freemius SDK.
 *
 * Delegates to the global acrwd_fs() instance. Defensive against the SDK being
 * absent: if acrwd_fs() returns null (e.g. a build without `composer install`),
 * every method degrades to "Free" (no premium, no plan, no quota) instead of
 * fataling — the plugin keeps working as free.
 */
final class FreemiusSdkGateway implements FreemiusGateway {

	/**
	 * The SDK instance, or null if unavailable.
	 *
	 * @return \Freemius|null
	 */
	private function fs() {
		return function_exists( 'acrwd_fs' ) ? acrwd_fs() : null;
	}

	public function can_use_premium_code(): bool {
		$fs = $this->fs();
		return null !== $fs && $fs->can_use_premium_code();
	}

	public function license_quota(): ?int {
		$fs = $this->fs();
		if ( null === $fs ) {
			return null;
		}

		$license = $fs->_get_license();
		if ( empty( $license ) || $license->is_unlimited() ) {
			return null;
		}

		return (int) $license->quota;
	}

	public function upgrade_url(): string {
		$fs = $this->fs();
		if ( null !== $fs ) {
			return (string) $fs->get_upgrade_url();
		}
		// SDK absent (build without composer install): fall back to the native
		// Freemius pricing slug nested under the plugin menu.
		return admin_url( 'admin.php?page=acrwd-pricing' );
	}
}
