<?php
/**
 * Multisite network-level API key fallbacks.
 *
 * @package AIAltTextGenerator
 * @since 1.9.0
 */

namespace AIAltTextGenerator;

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

/**
 * @since 1.9.0
 */
class NetworkSettings {

	private const OPTION_PREFIX = 'wpps_network_ai_alt_text_';

	public static function isMultisite(): bool {
		return is_multisite();
	}

	public static function canManageNetworkKeys(): bool {
		return self::isMultisite() && current_user_can( 'manage_network_options' );
	}

	/**
	 * Resolve a site value with optional network fallback.
	 */
	public static function resolve( string $site_value, string $field ): string {
		if ( $site_value !== '' ) {
			return $site_value;
		}

		if ( ! self::isMultisite() ) {
			return '';
		}

		$settings = Settings::get();
		if ( empty( $settings['use_network_api_keys'] ) ) {
			return '';
		}

		$value = get_site_option( self::OPTION_PREFIX . sanitize_key( $field ), '' );

		return is_string( $value ) ? trim( $value ) : '';
	}

	public static function update( string $field, string $value ): bool {
		if ( ! self::canManageNetworkKeys() ) {
			return false;
		}

		return (bool) update_site_option( self::OPTION_PREFIX . sanitize_key( $field ), $value );
	}

	public static function getNetworkKey( string $field ): string {
		if ( ! self::isMultisite() ) {
			return '';
		}

		$value = get_site_option( self::OPTION_PREFIX . sanitize_key( $field ), '' );

		return is_string( $value ) ? trim( $value ) : '';
	}

	public static function isNetworkKeyConfigured( string $field ): bool {
		return self::getNetworkKey( $field ) !== '';
	}

	/** @return list<string> */
	public static function keyFields(): array {
		return [ 'api_key', 'gemini_api_key', 'claude_api_key' ];
	}
}
