<?php
/**
 * Shared Multisite Network-Level Captcha Settings
 *
 * Roadmap item #32: allow super-admins to set reCAPTCHA / Turnstile keys at
 * the network level so child sites inherit safe defaults instead of rendering
 * empty widgets.
 *
 * Resolution order inside a module's `getSettings()`:
 *   1. Site-level override (from `wp_options`, non-empty)
 *   2. Network option `wpps_network_<module>_<field>` (multisite only)
 *   3. Empty string
 *
 * The helper is inert on single-site installs — `is_multisite()` short-circuits
 * before any `get_site_option()` call happens.
 *
 * @package WP_PowerSuite\Captcha\Shared
 * @since 1.1.0
 */

namespace WP_PowerSuite\Captcha\Shared;

/**
 * Network-level settings helper.
 */
final class NetworkSettings {

	/** @var list<string> */
	private const ENCRYPTED_FIELDS = [ 'secret_key', 'failsafe_recaptcha_secret_key' ];

	/**
	 * Resolve a key with network fallback.
	 *
	 * @param string $site_value Current site-level value.
	 * @param string $module_id  Module id (e.g. `google-recaptcha`).
	 * @param string $field      Field name (e.g. `site_key`).
	 * @return string
	 */
	public static function resolve( string $site_value, string $module_id, string $field ): string {
		if ( $site_value !== '' ) {
			return $site_value;
		}
		if ( ! is_multisite() ) {
			return '';
		}
		$option_name = 'wpps_network_' . sanitize_key( $module_id ) . '_' . sanitize_key( $field );
		$value = get_site_option( $option_name, '' );
		if ( ! is_string( $value ) || $value === '' ) {
			return '';
		}

		if ( in_array( $field, self::ENCRYPTED_FIELDS, true ) ) {
			$cipher_key = 'wpps_' . sanitize_key( $module_id ) . '_v1';
			return SecretCipher::decrypt( $value, $cipher_key );
		}

		return $value;
	}

	/**
	 * Update a network-level field. Caller is responsible for capability checks.
	 *
	 * @param string $module_id Module id.
	 * @param string $field     Field name.
	 * @param string $value     New value (already sanitized/encrypted).
	 */
	public static function update( string $module_id, string $field, string $value ): bool {
		if ( ! is_multisite() ) {
			return false;
		}
		$option_name = 'wpps_network_' . sanitize_key( $module_id ) . '_' . sanitize_key( $field );
		return (bool) update_site_option( $option_name, $value );
	}
}
