<?php

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

/**
 * Licence management via the Freemius SDK.
 *
 * The doig_fs() helper is bootstrapped in the main plugin file before any
 * require_once calls, so it is always available by the time this class is used.
 *
 * is_premium() returns true when the current install is running the premium
 * build AND has a valid, active Freemius licence. During local development,
 * add the following to wp-config.php to test premium features without a real
 * licence transaction:
 *
 *   define( 'WP_FS__DEV_MODE', true );
 *   define( 'WP_FS__SKIP_EMAIL_ACTIVATION', true );
 *   define( 'WP_FS__dynamic-og-image-generator_SECRET_KEY', 'sk_...' );
 *
 * Then activate a test licence from the Freemius developer dashboard.
 */
class DOIG_License {

	/**
	 * Production proxy base URL. Used by proxy_base_url() when no override
	 * constant is defined in wp-config.php.
	 */
	const PROD_PROXY_URL = 'https://screenshots.plugupp.com';

	/**
	 * Returns the proxy base URL the plugin should talk to for all
	 * outbound calls (submit, poll, health, usage). Honours the
	 * DOIG_PROXY_URL wp-config constant when defined, so a test install
	 * can be pointed at a non-production proxy without editing plugin
	 * code.
	 *
	 * The constant is read at every call rather than cached so a unit
	 * test (or a hot reload during development) can change it via
	 * runkit-style harnesses. The cost is one defined() check per call,
	 * which is negligible.
	 *
	 * Trailing slash is stripped so callers append `/v1/...` cleanly.
	 *
	 * @return string
	 */
	public static function proxy_base_url() {
		if ( defined( 'DOIG_PROXY_URL' ) ) {
			return rtrim( (string) DOIG_PROXY_URL, '/' );
		}
		return self::PROD_PROXY_URL;
	}

	/**
	 * Returns true if this install is pointing at a non-production proxy
	 * (i.e. DOIG_PROXY_URL is defined in wp-config.php). Used by the
	 * admin UI to surface a "Test environment" notice so the override is
	 * impossible to miss when a support agent, developer, or operator
	 * is looking at the admin screens.
	 *
	 * @return bool
	 */
	public static function is_test_proxy() {
		return defined( 'DOIG_PROXY_URL' );
	}

	/**
	 * Returns true if the current site has an active Premium licence and is
	 * running the premium build of the plugin.
	 *
	 * @return bool
	 */
	public static function is_premium() {
		if ( function_exists( 'doig_fs' ) ) {
			return doig_fs()->can_use_premium_code();
		}
		return false;
	}

	/**
	 * Returns true if the site is connected to the PlugUpp screenshot server.
	 *
	 * Connection requires the Freemius SDK to be in the "registered" state
	 * (the user completed activation) and to have produced either a licence
	 * with a secret_key (Premium) or a site with a secret_key (Free tier).
	 * Without either, the proxy submission has no licence_key to authenticate
	 * with and no site_id to track per-site quota - submissions would 422.
	 *
	 * Free wp.org-compliant builds let users skip activation, which is the
	 * scenario this guard catches.
	 *
	 * @return bool
	 */
	public static function is_connected() {
		if ( ! function_exists( 'doig_fs' ) ) {
			return false;
		}
		$fs = doig_fs();
		if ( ! is_object( $fs ) || ! method_exists( $fs, 'is_registered' ) ) {
			return false;
		}
		if ( ! $fs->is_registered() ) {
			return false;
		}
		// Need a usable licence_key (Premium licence secret_key, or Free
		// tier site secret_key). DOIG_Screenshot::get_licence_key() returns
		// empty when neither is available.
		return '' !== DOIG_Screenshot::get_licence_key();
	}

	/**
	 * Returns true if the user has completed the Freemius opt-in form but
	 * has not yet clicked the email-confirmation link. During this window
	 * `is_registered()` is false but Freemius considers the install in a
	 * "pending activation" state - the user is waiting on their own inbox,
	 * not waiting on us. The setup banner branches on this so we don't
	 * tell a user who already opted in to "Activate now" again (which
	 * would loop them back to the same opt-in form).
	 *
	 * Wrapped with method_exists guards so older SDK builds that lack the
	 * method degrade cleanly to false (banner shows the default "Activate"
	 * state, same behaviour as before this helper existed).
	 *
	 * @return bool
	 */
	public static function is_pending_activation() {
		if ( ! function_exists( 'doig_fs' ) ) {
			return false;
		}
		$fs = doig_fs();
		if ( ! is_object( $fs ) || ! method_exists( $fs, 'is_pending_activation' ) ) {
			return false;
		}
		return (bool) $fs->is_pending_activation();
	}

	/**
	 * URL to the Freemius activation / opt-in flow. Used by the Settings
	 * page setup banner and the sidebar guard message.
	 *
	 * Picks the right URL based on Freemius state:
	 *
	 * - is_anonymous() == true  -> get_reconnect_url(). The user has
	 *   already explicitly skipped the opt-in; the bare activation URL
	 *   is a no-op (it just returns to the same Settings page). The
	 *   reconnect URL adds fs_action=reset_anonymous_mode which clears
	 *   the skip flag and re-shows the opt-in screen.
	 *
	 * - otherwise -> get_activation_url(). Fresh installs and
	 *   pending-activation states both land on the opt-in screen
	 *   naturally.
	 *
	 * @return string
	 */
	public static function activation_url() {
		if ( ! function_exists( 'doig_fs' ) ) {
			return admin_url( 'plugins.php' );
		}
		$fs = doig_fs();
		if ( ! is_object( $fs ) ) {
			return admin_url( 'plugins.php' );
		}
		if ( method_exists( $fs, 'is_anonymous' ) && $fs->is_anonymous() && method_exists( $fs, 'get_reconnect_url' ) ) {
			return (string) $fs->get_reconnect_url();
		}
		if ( method_exists( $fs, 'get_activation_url' ) ) {
			return (string) $fs->get_activation_url();
		}
		return admin_url( 'plugins.php' );
	}
}
