<?php
/**
 * Premium feature gating for Admin Color Customizer.
 *
 * @package WP_PowerSuite\AdminColorCustomizer
 */

namespace WP_PowerSuite\AdminColorCustomizer;

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

class FeatureGate {

	/** @var list<string> */
	public const PREMIUM_MODES = [
		'force_all',
		'force_by_role',
	];

	public static function isPremiumLicensed(): bool {
		return function_exists( 'wp_powersuite_freemium_unlocked' ) && wp_powersuite_freemium_unlocked( 'admin-color-customizer' );
	}

	/**
	 * 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;
		}

		$mode = sanitize_key( (string) ( $settings['mode'] ?? 'global_default' ) );
		if ( in_array( $mode, self::PREMIUM_MODES, true ) ) {
			$settings['mode'] = 'global_default';
		}

		$settings['custom_schemes'] = [];
		$settings['role_schemes']    = [];

		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;
		}

		$mode = sanitize_key( (string) ( $settings['mode'] ?? 'global_default' ) );
		if ( in_array( $mode, self::PREMIUM_MODES, true ) ) {
			$existing_mode = sanitize_key( (string) ( $existing['mode'] ?? 'global_default' ) );
			$settings['mode'] = in_array( $existing_mode, self::PREMIUM_MODES, true )
				? $existing_mode
				: 'global_default';
		}

		$settings['custom_schemes'] = isset( $existing['custom_schemes'] ) && is_array( $existing['custom_schemes'] )
			? $existing['custom_schemes']
			: [];
		$settings['role_schemes'] = isset( $existing['role_schemes'] ) && is_array( $existing['role_schemes'] )
			? $existing['role_schemes']
			: [];

		return $settings;
	}
}
