<?php

namespace Ugcify\License;

defined( 'ABSPATH' ) || exit;

/**
 * License plan feature gating for UGC Commerce.
 *
 * Pricing tiers
 * ─────────────────────────────────────────────────────────────────────────────
 * FREE     ($0/yr)    – Up to 50 UGC items, grid-only gallery, admin uploads
 *                       only, basic moderation, no AI / social import.
 *
 * GROWTH   ($99/yr)   – Unlimited uploads, customer upload form, product
 *                       tagging, social hashtag import, email automation.
 *
 * PRO      ($199/yr)  – Everything in Growth + AI image auto-tagging, advanced
 *                       email integration (Mail Mint), remove plugin branding.
 *
 * BUSINESS ($299/yr)  – Everything in Pro + A/B testing suite, influencer /
 *                       contributor portal, advanced gamification & rewards,
 *                       multi-site support.
 * ─────────────────────────────────────────────────────────────────────────────
 *
 * @since 1.0.0
 * @package Ugcify\License
 */
class LicenseHelper {

	// =========================================================================
	// General license helpers
	// =========================================================================

	/**
	 * Whether a paid license is currently active.
	 *
	 * @return bool
	 */
	public static function is_pro_active() {
		return Licensing::is_license_valid();
	}

	/**
	 * Get the active license key.
	 *
	 * @return string|false License key or false if not set.
	 */
	public static function get_license_key() {
		return get_option( 'ugcify_pro_license_key', false );
	}

	/**
	 * Generic "license required" error message.
	 *
	 * @return string
	 */
	public static function get_license_error_message() {
		return __( 'This feature requires an active UGC Commerce license. Please activate your license to use pro features.', 'ugcify' );
	}

	/**
	 * URL of the license management page inside the WordPress admin.
	 *
	 * @return string
	 */
	public static function get_license_activation_url() {
		return admin_url( 'admin.php?page=ugcify#/license' );
	}

	/**
	 * Output an admin notice inviting the user to activate their license.
	 *
	 * @param string $feature_name Optional feature name to include in the message.
	 */
	public static function display_license_notice( $feature_name = '' ) {
		$message = ! empty( $feature_name )
			/* translators: %s: Feature name requiring a license. */
			? sprintf( __( '%s requires an active UGC Commerce license.', 'ugcify' ), $feature_name )
			: self::get_license_error_message();

		$activation_url = self::get_license_activation_url();
		?>
		<div class="notice notice-warning is-dismissible">
			<p>
				<?php echo esc_html( $message ); ?>
				<a href="<?php echo esc_url( $activation_url ); ?>" class="button button-primary">
					<?php esc_html_e( 'Activate License', 'ugcify' ); ?>
				</a>
			</p>
		</div>
		<?php
	}

	/**
	 * Check the license and queue an admin notice if it is not valid.
	 *
	 * @param string $feature_name
	 * @return bool True when the license is valid.
	 */
	public static function check_license_or_show_notice( $feature_name = '' ) {
		if ( self::is_pro_active() ) {
			return true;
		}
		add_action(
			'admin_notices',
			function () use ( $feature_name ) {
				self::display_license_notice( $feature_name );
			}
		);
		return false;
	}

	/**
	 * Send a WP REST / AJAX error response when the license is not valid.
	 *
	 * @param string $feature_name
	 */
	public static function ajax_license_error( $feature_name = '' ) {
		wp_send_json_error(
			array(
				'message'     => ! empty( $feature_name )
					/* translators: %s: Feature name requiring a license. */
					? sprintf( __( '%s requires an active UGC Commerce license.', 'ugcify' ), $feature_name )
					: self::get_license_error_message(),
				'license_url' => self::get_license_activation_url(),
			)
		);
	}

	/**
	 * Check license for AJAX-style requests; sends error JSON and returns false
	 * when not valid.
	 *
	 * @param string $feature_name
	 * @return bool
	 */
	public static function check_license_for_ajax( $feature_name = '' ) {
		if ( ! self::is_pro_active() ) {
			self::ajax_license_error( $feature_name );
			return false;
		}
		return true;
	}

	/**
	 * Get the HTML status badge for display in the admin.
	 *
	 * @return string
	 */
	public static function get_status_badge() {
		if ( self::is_pro_active() ) {
			return '<span class="ugcify-pro-status active">' . __( 'Pro Active', 'ugcify' ) . '</span>';
		}

		$activation_url = self::get_license_activation_url();
		return '<span class="ugcify-pro-status inactive">' .
			__( 'Pro Inactive', 'ugcify' ) .
			'</span> <a href="' . esc_url( $activation_url ) . '" class="button-link">' .
			__( 'Activate', 'ugcify' ) .
			'</a>';
	}

	/**
	 * Execute a callback only if pro is active.
	 *
	 * @param callable $callback
	 * @param mixed    ...$args
	 * @return mixed|null
	 */
	public static function if_pro_active( $callback, ...$args ) {
		if ( self::is_pro_active() && is_callable( $callback ) ) {
			return call_user_func_array( $callback, $args );
		}
		return null;
	}

	// =========================================================================
	// Expiry helpers
	// =========================================================================

	/**
	 * Number of days remaining on the license.
	 *
	 * @return int
	 */
	public static function get_remaining_days() {
		$license_data = Licensing::get_license_data();
		if ( ! empty( $license_data['end_date'] ) ) {
			return ProFunctions::get_license_remaining_days( $license_data['end_date'] );
		}
		return 0;
	}

	/**
	 * Get stored license data.
	 *
	 * @return array
	 */
	public static function get_license_data() {
		return Licensing::get_license_data();
	}

	/**
	 * Whether the license expires within 7 days.
	 *
	 * @return bool
	 */
	public static function is_license_expiring_soon() {
		$remaining_days = self::get_remaining_days();
		return $remaining_days > 0 && $remaining_days <= 7;
	}

	// =========================================================================
	// Plan helpers
	// =========================================================================

	/**
	 * Return the raw plan slug stored in license data.
	 * Defaults to 'free' when nothing is set.
	 *
	 * @return string
	 */
	public static function get_license_plan() {
		$license_data = Licensing::get_license_data();
		$plan         = isset( $license_data['plan'] ) ? $license_data['plan'] : '';
		return $plan ? $plan : 'free';
	}

	/**
	 * Full plan-slug → feature-array mapping.
	 *
	 * Every alias that the license server might return is listed here so that
	 * feature checks never fail due to a naming variant.
	 *
	 * @return array<string, array>
	 */
	public static function get_plan_features() {
		return apply_filters(
			'ugcify_pro_plan_features',
			array(
				// ── Free tier ──────────────────────────────────────────────
				'free'             => self::get_free_plan_features(),

				// ── Growth tier ────────────────────────────────────────────
				'growth'           => self::get_growth_plan_features(),
				'growth-annual'    => self::get_growth_plan_features(),
				'growth_annual'    => self::get_growth_plan_features(),
				'growthannual'     => self::get_growth_plan_features(),
				'growth-lifetime'  => self::get_growth_plan_features(),
				'growth_lifetime'  => self::get_growth_plan_features(),
				'growthlifetime'   => self::get_growth_plan_features(),

				// ── Pro tier ───────────────────────────────────────────────
				'pro'              => self::get_pro_plan_features(),
				'pro-annual'       => self::get_pro_plan_features(),
				'pro_annual'       => self::get_pro_plan_features(),
				'proannual'        => self::get_pro_plan_features(),
				'pro-lifetime'     => self::get_pro_plan_features(),
				'pro_lifetime'     => self::get_pro_plan_features(),
				'prolifetime'      => self::get_pro_plan_features(),

				// ── Business tier ──────────────────────────────────────────
				'business'           => self::get_business_plan_features(),
				'business-annual'    => self::get_business_plan_features(),
				'business_annual'    => self::get_business_plan_features(),
				'businessannual'     => self::get_business_plan_features(),
				'business-lifetime'  => self::get_business_plan_features(),
				'business_lifetime'  => self::get_business_plan_features(),
				'businesslifetime'   => self::get_business_plan_features(),
			)
		);
	}

	// =========================================================================
	// Per-plan feature arrays
	// =========================================================================

	/**
	 * Free plan features (base plugin capabilities — no paid license required).
	 *
	 * @return array
	 */
	public static function get_free_plan_features() {
		return array(
			'ugcify_item_limit'             => 50,
			'gallery_layouts'            => array( 'grid' ),
			'customer_upload_form'       => false,
			'basic_moderation'           => true,
			'product_tagging'            => false,
			'social_import'              => false,
			'email_automation'           => false,
			'ai_auto_tagging'            => false,
			'advanced_email_integration' => false,
			'remove_branding'            => false,
			'ab_testing'                 => false,
			'influencer_portal'          => false,
			'advanced_gamification'      => false,
			'multi_site'                 => false,
			'site_license'               => 1,
			'fraud_management'           => false,
			'review_request_email'       => false,
			'block_studio_advanced'      => false,
			'block_studio_reels'         => false,
			'block_studio_gallery'       => false,
			'unlimited_reviews'          => false,
			'image_edit'                 => false,
			's3_storage'                 => false,
		);
	}

	/**
	 * Growth plan features ($99/year).
	 *
	 * @return array
	 */
	public static function get_growth_plan_features() {
		return array(
			'ugcify_item_limit'             => -1,
			'gallery_layouts'            => array( 'grid', 'masonry', 'slider', 'carousel' ),
			'customer_upload_form'       => true,
			'basic_moderation'           => true,
			'product_tagging'            => true,
			'social_import'              => true,
			'email_automation'           => false,
			'ai_auto_tagging'            => false,
			'advanced_email_integration' => false,
			'remove_branding'            => false,
			'ab_testing'                 => false,
			'influencer_portal'          => false,
			'advanced_gamification'      => false,
			'multi_site'                 => false,
			'site_license'               => 1,
			'fraud_management'           => true,
			'review_request_email'       => true,
			'block_studio_advanced'      => true,
			'block_studio_reels'         => true,
			'block_studio_gallery'       => true,
			'unlimited_reviews'          => true,
			'image_edit'                 => true,
			's3_storage'                 => true,
		);
	}

	/**
	 * Pro plan features ($199/year).
	 *
	 * @return array
	 */
	public static function get_pro_plan_features() {
		return array(
			'ugcify_item_limit'             => -1,
			'gallery_layouts'            => array( 'grid', 'masonry', 'slider', 'carousel' ),
			'customer_upload_form'       => true,
			'basic_moderation'           => true,
			'product_tagging'            => true,
			'social_import'              => true,
			'email_automation'           => true,
			'ai_auto_tagging'            => true,
			'advanced_email_integration' => true,
			'remove_branding'            => true,
			'ab_testing'                 => false,
			'influencer_portal'          => false,
			'advanced_gamification'      => false,
			'multi_site'                 => false,
			'site_license'               => 1,
			'fraud_management'           => true,
			'review_request_email'       => true,
			'block_studio_advanced'      => true,
			'block_studio_reels'         => true,
			'block_studio_gallery'       => true,
			'unlimited_reviews'          => true,
			'image_edit'                 => true,
			's3_storage'                 => true,
		);
	}

	/**
	 * Business plan features ($299/year).
	 *
	 * @return array
	 */
	public static function get_business_plan_features() {
		return array(
			'ugcify_item_limit'             => -1,
			'gallery_layouts'            => array( 'grid', 'masonry', 'slider', 'carousel' ),
			'customer_upload_form'       => true,
			'basic_moderation'           => true,
			'product_tagging'            => true,
			'social_import'              => true,
			'email_automation'           => true,
			'ai_auto_tagging'            => true,
			'advanced_email_integration' => true,
			'remove_branding'            => true,
			'ab_testing'                 => true,
			'influencer_portal'          => true,
			'advanced_gamification'      => true,
			'multi_site'                 => true,
			'site_license'               => 'unlimited',
			'fraud_management'           => true,
			'review_request_email'       => true,
			'block_studio_advanced'      => true,
			'block_studio_reels'         => true,
			'block_studio_gallery'       => true,
			'unlimited_reviews'          => true,
			'image_edit'                 => true,
			's3_storage'                 => true,
		);
	}

	// =========================================================================
	// Feature-check helpers
	// =========================================================================

	/**
	 * Check whether a specific feature is available on the active license plan.
	 *
	 * Returns false when no valid license is present. For numeric features
	 * (e.g. ugcify_item_limit, site_license) the raw value is returned; for
	 * boolean features true/false is returned.
	 *
	 * @param string $feature_name Feature key.
	 * @return bool|int|string|array Feature value, or false when not available.
	 */
	public static function is_feature_enabled( $feature_name ) {
		if ( ! self::is_pro_active() ) {
			return false;
		}

		$current_plan  = self::get_license_plan();
		$plan_features = self::get_plan_features();

		if ( ! isset( $plan_features[ $current_plan ] ) ) {
			$plan_features[ $current_plan ] = self::get_free_plan_features();
		}

		return isset( $plan_features[ $current_plan ][ $feature_name ] )
			? $plan_features[ $current_plan ][ $feature_name ]
			: false;
	}

	/**
	 * Return the canonical minimum plan required to enable a feature.
	 *
	 * Returns one of: 'free', 'growth', 'pro', 'business'.
	 *
	 * @param string $feature_name
	 * @return string
	 */
	public static function get_required_plan_for_feature( $feature_name ) {
		$tier_order = array( 'free', 'growth', 'pro', 'business' );

		$tier_slugs = array(
			'free'     => array( 'free' ),
			'growth'   => array(
				'growth', 'growth-annual', 'growth_annual', 'growthannual',
				'growth-lifetime', 'growth_lifetime', 'growthlifetime',
			),
			'pro'      => array(
				'pro', 'pro-annual', 'pro_annual', 'proannual',
				'pro-lifetime', 'pro_lifetime', 'prolifetime',
			),
			'business' => array(
				'business', 'business-annual', 'business_annual', 'businessannual',
				'business-lifetime', 'business_lifetime', 'businesslifetime',
			),
		);

		$plan_features = self::get_plan_features();

		foreach ( $tier_order as $tier ) {
			$representative_slug = $tier_slugs[ $tier ][0];
			if (
				isset( $plan_features[ $representative_slug ][ $feature_name ] ) &&
				$plan_features[ $representative_slug ][ $feature_name ]
			) {
				return $tier;
			}
		}

		return 'growth';
	}
}
