<?php
/**
 * Resolves Grundpreis from generic WooCommerce meta keys.
 *
 * @package PhoenixWP\PriceLabels
 */

declare(strict_types=1);

namespace PhoenixWP\PriceLabels\Compliance\Providers;

use PhoenixWP\PriceLabels\Compliance\Unit_Price_Provider_Interface;
use PhoenixWP\PriceLabels\Compliance\Unit_Price_Text;
use WC_Product;

defined( 'ABSPATH' ) || exit;

/**
 * Last-resort meta keys used by assorted plugins and custom fields.
 */
final class Legacy_Meta_Provider implements Unit_Price_Provider_Interface {

	public function get_id(): string {
		return 'legacy_meta';
	}

	public function resolve( WC_Product $product ): ?string {
		if ( method_exists( $product, 'get_unit_price' ) ) {
			$value = (float) $product->get_unit_price();
			$unit  = method_exists( $product, 'get_unit_price_unit' )
				? trim( (string) $product->get_unit_price_unit() )
				: '';

			if ( $value > 0 && '' !== $unit ) {
				return Unit_Price_Text::format_per_unit( $value, 1.0, $unit );
			}
		}

		$amount = $this->read_first_float(
			$product,
			array( '_unit_price', '_unit_price_raw', '_price_per_unit' )
		);

		$base = $this->read_first_float(
			$product,
			array( '_unit_price_units', '_base_price', '_unit_price_base' )
		);

		$unit = $this->read_first_string(
			$product,
			array( '_unit', '_unit_price_unit', '_unit_label' )
		);

		if ( $amount <= 0 || '' === $unit ) {
			return null;
		}

		return Unit_Price_Text::format_per_unit( $amount, $base > 0 ? $base : 1.0, $unit );
	}

	/**
	 * @param string[] $keys Meta keys in priority order.
	 */
	private function read_first_float( WC_Product $product, array $keys ): float {
		foreach ( $keys as $key ) {
			$value = $product->get_meta( $key );
			if ( is_numeric( $value ) && (float) $value > 0 ) {
				return (float) $value;
			}
		}

		return 0.0;
	}

	/**
	 * @param string[] $keys Meta keys in priority order.
	 */
	private function read_first_string( WC_Product $product, array $keys ): string {
		foreach ( $keys as $key ) {
			$value = trim( (string) $product->get_meta( $key ) );
			if ( '' !== $value ) {
				return $value;
			}
		}

		return '';
	}
}
