<?php
/**
 * Premium feature gating for Redirect After Login.
 *
 * @package RedirectAfterLogin
 */

namespace RedirectAfterLogin;

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

class FeatureGate {

	/**
	 * Settings whose implementation lives in the Pro overlay (not in Lite).
	 *
	 * @var list<string>
	 */
	public const OVERLAY_SETTING_KEYS = [
		'enable_role_redirects',
	];

	public static function isOverlaySetting( string $key ): bool {
		return $key === 'role_redirects' || in_array( $key, self::OVERLAY_SETTING_KEYS, true );
	}

	public static function isPremiumLicensed(): bool {
		return function_exists( 'wp_powersuite_freemium_unlocked' ) && wp_powersuite_freemium_unlocked( 'redirect-after-login' );
	}

	/**
	 * Disable per-role redirects at runtime when the overlay is locked.
	 *
	 * @param array<string, mixed> $settings Normalized module settings.
	 * @return array<string, mixed>
	 */
	public static function applyPremiumTierLimits( array $settings ): array {
		if ( self::isPremiumLicensed() ) {
			return $settings;
		}

		$settings['enable_role_redirects'] = false;

		return $settings;
	}

	/**
	 * Ignore submitted overlay fields when the license is inactive (preserve stored values).
	 *
	 * @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;
		}

		$existing_roles = isset( $existing['role_redirects'] ) && is_array( $existing['role_redirects'] )
			? $existing['role_redirects']
			: [];
		$has_role_urls  = false;
		foreach ( $existing_roles as $url ) {
			if ( is_string( $url ) && trim( $url ) !== '' ) {
				$has_role_urls = true;
				break;
			}
		}

		if ( array_key_exists( 'enable_role_redirects', $existing ) ) {
			$settings['enable_role_redirects'] = ! empty( $existing['enable_role_redirects'] );
		} else {
			$settings['enable_role_redirects'] = $has_role_urls;
		}
		$settings['role_redirects'] = $existing_roles;

		return $settings;
	}
}
