<?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_is_license_valid' ) && wp_powersuite_is_license_valid();
	}

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

if ( function_exists( 'add_filter' ) ) {
	add_filter(
		'wp_powersuite_pro_module_save_unlocked',
		static function ( $unlocked, string $module_id ) {
			if ( $module_id !== 'redirect-after-login' ) {
				return $unlocked;
			}

			return FeatureGate::isPremiumLicensed();
		},
		10,
		2
	);

	add_filter(
		'wp_powersuite_preserve_pro_settings_on_save',
		static function ( $settings, string $module_id, $existing ) {
			if ( $module_id !== 'redirect-after-login' || ! is_array( $settings ) ) {
				return $settings;
			}

			return FeatureGate::preservePremiumSettingsOnSave( $settings, is_array( $existing ) ? $existing : [] );
		},
		10,
		3
	);
}
