<?php
/**
 * Premium feature gating for Custom Taxonomy Order.
 *
 * @package CustomTaxonomyOrder
 */

namespace CustomTaxonomyOrder;

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

class FeatureGate {

	/** @var list<string> */
	public const FREE_TAXONOMIES = [ 'category', 'post_tag' ];

	/** @var list<string> */
	public const PREMIUM_KEYS = [
		'apply_archives',
		'apply_menus',
		'apply_admin',
	];

	public static function isPremiumLicensed(): bool {
		return function_exists( 'wp_powersuite_freemium_unlocked' ) && wp_powersuite_freemium_unlocked( 'custom-taxonomy-order' );
	}

	public static function isFreeTaxonomy( string $taxonomy ): bool {
		return in_array( sanitize_key( $taxonomy ), self::FREE_TAXONOMIES, true );
	}

	/**
	 * License page when Pro is installed, otherwise the public purchase URL.
	 */
	public static function upsellUrl(): string {
		if ( function_exists( 'wp_powersuite_premium_upsell_url' ) ) {
			return wp_powersuite_premium_upsell_url();
		}

		return defined( 'WP_POWERSUITE_PRODUCT_URL' ) ? WP_POWERSUITE_PRODUCT_URL : 'https://wppowersuite.com/';
	}

	/**
	 * @param array<string, mixed> $settings
	 * @return array<string, mixed>
	 */
	public static function applyPremiumTierLimits( array $settings ): array {
		if ( self::isPremiumLicensed() ) {
			return $settings;
		}

		foreach ( self::PREMIUM_KEYS as $key ) {
			$settings[ $key ] = false;
		}

		$taxonomies = isset( $settings['taxonomies'] ) && is_array( $settings['taxonomies'] )
			? $settings['taxonomies']
			: [];
		$settings['taxonomies'] = array_values(
			array_filter(
				$taxonomies,
				static fn( $taxonomy ): bool => self::isFreeTaxonomy( (string) $taxonomy )
			)
		);

		return $settings;
	}

	/**
	 * @param array<string, mixed> $settings Sanitized settings about to be saved.
	 * @param array<string, mixed> $existing Previously stored settings.
	 * @return array<string, mixed>
	 */
	public static function preservePremiumSettingsOnSave( array $settings, array $existing ): array {
		if ( self::isPremiumLicensed() ) {
			return $settings;
		}

		foreach ( self::PREMIUM_KEYS as $key ) {
			$settings[ $key ] = ! empty( $existing[ $key ] );
		}

		$submitted = isset( $settings['taxonomies'] ) && is_array( $settings['taxonomies'] )
			? $settings['taxonomies']
			: [];
		$existing_taxonomies = isset( $existing['taxonomies'] ) && is_array( $existing['taxonomies'] )
			? $existing['taxonomies']
			: [];

		$free_submitted = array_values(
			array_filter(
				$submitted,
				static fn( $taxonomy ): bool => self::isFreeTaxonomy( (string) $taxonomy )
			)
		);
		$premium_existing = array_values(
			array_filter(
				$existing_taxonomies,
				static fn( $taxonomy ): bool => ! self::isFreeTaxonomy( (string) $taxonomy )
			)
		);

		$settings['taxonomies'] = array_values( array_unique( array_merge( $free_submitted, $premium_existing ) ) );

		return $settings;
	}
}
