<?php
/**
 * Connects DreamFast Commerce Float feature gates to Freemius.
 *
 * @package DreamFast_CF
 */

namespace DreamFast\CommerceFloat;

defined( 'ABSPATH' ) || exit;

/**
 * Freemius integration hooks.
 */
class Freemius_Bridge {

	/**
	 * Register filters.
	 */
	public static function init() {
		add_filter( 'dreamfast_cf_is_pro', array( __CLASS__, 'filter_is_pro' ), 5 );
		add_filter( 'dreamfast_cf_upgrade_url', array( __CLASS__, 'filter_upgrade_url' ), 5 );
	}

	/**
	 * Whether the SDK helper is available.
	 *
	 * @return bool
	 */
	public static function is_available() {
		return function_exists( 'dreamfast_cf_fs' );
	}

	/**
	 * Get the Freemius SDK instance.
	 *
	 * @return \Freemius|null
	 */
	public static function fs() {
		if ( ! self::is_available() ) {
			return null;
		}

		return dreamfast_cf_fs();
	}

	/**
	 * Whether Freemius allows premium code on this site.
	 *
	 * @return bool
	 */
	public static function is_licensed() {
		$fs = self::fs();
		if ( ! $fs ) {
			return false;
		}

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

		if ( method_exists( $fs, 'can_use_premium_code__premium_only' ) ) {
			return (bool) $fs->can_use_premium_code__premium_only();
		}

		if ( method_exists( $fs, 'is_paying' ) ) {
			return (bool) $fs->is_paying();
		}

		return false;
	}

	/**
	 * Unlock Pro feature gates when Freemius says the site is licensed.
	 *
	 * @param bool $is_pro Existing Pro state.
	 * @return bool
	 */
	public static function filter_is_pro( $is_pro ) {
		if ( $is_pro ) {
			return true;
		}

		return self::is_licensed();
	}

	/**
	 * Use Freemius checkout URL for upgrade buttons when available.
	 *
	 * @param string $url Default upgrade URL.
	 * @return string
	 */
	public static function filter_upgrade_url( $url ) {
		$fs = self::fs();
		if ( $fs && method_exists( $fs, 'get_upgrade_url' ) ) {
			$upgrade_url = $fs->get_upgrade_url();
			if ( is_string( $upgrade_url ) && '' !== $upgrade_url ) {
				return $upgrade_url;
			}
		}

		return $url;
	}
}
