<?php
/**
 * LicenseManager — Freemius SDK wrapper.
 * Implemented in Phase 10 (premium layer).
 *
 * @package Relatedly\Premium
 * @since   2.0.0
 */

namespace Relatedly\Premium;

defined( 'ABSPATH' ) || exit;

/**
 * Wraps premium license checks.
 *
 * @since 2.0.0
 */
class LicenseManager {

	/**
	 * Fallback checkout URL used when the Freemius SDK is unavailable.
	 *
	 * @since 2.3.2
	 * @var string
	 */
	private const FALLBACK_CHECKOUT_URL = 'https://checkout.freemius.com/plugin/32038/';

	/**
	 * Check if a valid premium license is active.
	 *
	 * @since 2.0.0
	 * @since 2.1.0 Uses the Freemius SDK when available.
	 */
	public static function is_valid(): bool {
		if ( function_exists( 'relatedly_fs' ) ) {
			$fs = relatedly_fs();

			if ( is_object( $fs ) && method_exists( $fs, 'can_use_premium_code' ) ) {
				return (bool) $fs->can_use_premium_code();
			}
		}

		return (bool) apply_filters( 'relatedly_is_premium', false );
	}

	/**
	 * Get the public upgrade checkout URL.
	 *
	 * @since 2.3.2
	 * @return string
	 */
	public static function checkout_url(): string {
		$url = self::FALLBACK_CHECKOUT_URL;

		if ( function_exists( 'relatedly_fs' ) ) {
			$fs = relatedly_fs();

			if ( is_object( $fs ) && method_exists( $fs, 'checkout_url' ) ) {
				$checkout_url = $fs->checkout_url();

				if ( is_string( $checkout_url ) && '' !== $checkout_url ) {
					$url = $checkout_url;
				}
			}
		}

		/**
		 * Filter the upgrade checkout URL used by Pro upsell links.
		 *
		 * @since 2.3.2
		 * @param string $url Checkout URL.
		 */
		$filtered_url = apply_filters( 'relatedly_checkout_url', $url );

		return is_string( $filtered_url ) && '' !== $filtered_url ? esc_url_raw( $filtered_url ) : self::FALLBACK_CHECKOUT_URL;
	}
}
