<?php
/**
 * Premium feature gating for Temporary Login.
 *
 * @package TemporaryLogin
 */

namespace TemporaryLogin;

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

class FeatureGate {

	public const FREE_EXPIRY_TYPE = 'day';

	/** @var list<string> */
	private const PREMIUM_EXPIRY_TYPES = [
		'hour',
		'3_hours',
		'3_days',
		'week',
		'month',
		'custom',
	];

	public static function isPremiumLicensed(): bool {
		return function_exists( 'wp_powersuite_is_license_valid' ) && wp_powersuite_is_license_valid();
	}

	/**
	 * @param array<string, mixed> $args Login create arguments.
	 * @return array<string, mixed>
	 */
	public static function applyFreeTierCreateArgs( array $args ): array {
		if ( self::isPremiumLicensed() ) {
			return $args;
		}

		$args['expiry_type'] = self::FREE_EXPIRY_TYPE;
		unset( $args['expiry_date'] );
		$args['single_use']      = false;
		$args['max_uses']        = 0;
		$args['ip_restriction']  = '';
		$args['bind_user_agent'] = false;

		return $args;
	}

	/**
	 * Preserve premium login fields on update when license is inactive.
	 *
	 * @param array<string, mixed> $args  Sanitized update arguments.
	 * @param object               $login Existing login row.
	 * @return array<string, mixed>
	 */
	public static function applyFreeTierUpdateArgs( array $args, object $login ): array {
		if ( self::isPremiumLicensed() ) {
			return $args;
		}

		if ( isset( $args['expiry_type'] ) ) {
			$expiry_type = sanitize_key( (string) $args['expiry_type'] );
			if ( $expiry_type !== self::FREE_EXPIRY_TYPE ) {
				unset( $args['expiry_type'], $args['expiry_date'] );
			} else {
				$args['expiry_type'] = self::FREE_EXPIRY_TYPE;
				unset( $args['expiry_date'] );
			}
		}

		$args['single_use']      = ! empty( $login->single_use );
		$args['max_uses']        = isset( $login->max_uses ) ? absint( $login->max_uses ) : 0;
		$args['ip_restriction']  = is_string( $login->ip_restriction ?? null ) ? $login->ip_restriction : '';
		$args['bind_user_agent'] = ! empty( $login->bind_user_agent );

		return $args;
	}

	public static function isPremiumExpiryType( string $type ): bool {
		return in_array( sanitize_key( $type ), self::PREMIUM_EXPIRY_TYPES, true );
	}
}
