<?php
/**
 * License helpers. One place decides whether the site has an active Pro
 * license and what token to authenticate service calls with, so the rest of
 * the plugin never touches the Freemius SDK directly.
 *
 * @package UpdateGuardian
 */

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

/**
 * Whether the site may use Pro features (a paid, non-expired license).
 *
 * We ship a single codebase (the same build lives on WordPress.org), so we
 * check the license/payment state directly. can_use_premium_code() alone is
 * false on the org-compliant build even with a valid license, so it can't be
 * the gate here.
 *
 * @return bool
 */
function upguard_is_pro() {
	if ( ! function_exists( 'upguard_fs' ) ) {
		return false;
	}
	$fs = upguard_fs();
	return $fs->is_paying() || $fs->has_active_valid_license() || $fs->can_use_premium_code();
}

/**
 * The token to authenticate service calls with.
 *
 * Prefers the active Freemius license key so the hosted service can tie usage
 * to a real subscription. Falls back to a manually entered key, which is handy
 * for local development before a license exists.
 *
 * @return string
 */
function upguard_service_token() {
	if ( function_exists( 'upguard_fs' ) && upguard_fs()->is_registered() ) {
		$license = upguard_fs()->_get_license();
		if ( $license && ! empty( $license->secret_key ) ) {
			return $license->secret_key;
		}
	}
	return (string) get_option( Upguard_Client::OPT_LICENSE, '' );
}

/**
 * The active Freemius license id, so the service can verify the license.
 * Empty when unlicensed (dev mode on the service accepts the fallback token).
 *
 * @return string
 */
function upguard_license_id() {
	if ( function_exists( 'upguard_fs' ) && upguard_fs()->is_registered() ) {
		$license = upguard_fs()->_get_license();
		if ( $license && ! empty( $license->id ) ) {
			return (string) $license->id;
		}
	}
	return '';
}
