<?php
/**
 * Resolves Grundpreis by trying registered providers in priority order.
 *
 * @package PhoenixWP\PriceLabels
 */

declare(strict_types=1);

namespace PhoenixWP\PriceLabels\Compliance;

use PhoenixWP\PriceLabels\Compliance\Providers\German_Market_Provider;
use PhoenixWP\PriceLabels\Compliance\Providers\Germanized_Provider;
use PhoenixWP\PriceLabels\Compliance\Providers\Legacy_Meta_Provider;
use PhoenixWP\PriceLabels\Compliance\Providers\Manual_Meta_Provider;
use PhoenixWP\PriceLabels\Compliance\Providers\Pangv_Meta_Provider;
use WC_Product;

defined( 'ABSPATH' ) || exit;

/**
 * Orchestrates plugin-native and manual unit price sources.
 */
final class Unit_Price_Resolver {

	/**
	 * @var Unit_Price_Provider_Interface[]|null
	 */
	private static ?array $providers = null;

	/**
	 * Returns the first non-empty unit price string from the provider chain.
	 */
	public static function resolve( WC_Product $product ): string {
		foreach ( self::get_providers() as $provider ) {
			$text = $provider->resolve( $product );

			if ( is_string( $text ) && '' !== trim( $text ) ) {
				/**
				 * Filters resolved unit price text from a specific provider.
				 *
				 * @param string                        $text     Resolved text.
				 * @param WC_Product                    $product  Product.
				 * @param Unit_Price_Provider_Interface $provider Provider instance.
				 */
				$text = (string) apply_filters(
					'phoenix_wp_price_labels_unit_price_from_provider',
					$text,
					$product,
					$provider
				);

				if ( '' !== trim( $text ) ) {
					return trim( $text );
				}
			}
		}

		return '';
	}

	/**
	 * @return Unit_Price_Provider_Interface[]
	 */
	private static function get_providers(): array {
		if ( null !== self::$providers ) {
			return self::$providers;
		}

		if ( Unit_Price_Settings::is_manual_only() ) {
			self::$providers = array( new Manual_Meta_Provider() );
		} else {
			self::$providers = array(
				new German_Market_Provider(),
				new Germanized_Provider(),
				new Pangv_Meta_Provider(),
				new Manual_Meta_Provider(),
				new Legacy_Meta_Provider(),
			);
		}

		/**
		 * Filters the unit price provider chain.
		 *
		 * @param Unit_Price_Provider_Interface[] $providers Provider instances.
		 */
		self::$providers = (array) apply_filters( 'phoenix_wp_price_labels_unit_price_providers', self::$providers );

		return self::$providers;
	}
}
