<?php
/**
 * Resolves Grundpreis from admin-configured product 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_Settings;
use PhoenixWP\PriceLabels\Compliance\Unit_Price_Text;
use WC_Product;

defined( 'ABSPATH' ) || exit;

/**
 * Fallback when shops use custom meta keys for PAngV data.
 */
final class Manual_Meta_Provider implements Unit_Price_Provider_Interface {

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

	public function resolve( WC_Product $product ): ?string {
		if ( ! Unit_Price_Settings::has_manual_mapping() ) {
			return null;
		}

		$settings = Unit_Price_Settings::get();

		if ( '' !== $settings['formatted_meta'] ) {
			$formatted = trim( (string) $product->get_meta( $settings['formatted_meta'] ) );
			if ( '' !== $formatted ) {
				return Unit_Price_Text::normalize( $formatted );
			}
		}

		$unit = '' !== $settings['unit_meta']
			? trim( (string) $product->get_meta( $settings['unit_meta'] ) )
			: '';

		$unit_price = '' !== $settings['unit_price_meta']
			? $this->read_float_meta( $product, $settings['unit_price_meta'] )
			: 0.0;

		$base           = '' !== $settings['base_amount_meta']
			? $this->read_float_meta( $product, $settings['base_amount_meta'] )
			: 0.0;
		$product_amount = '' !== $settings['product_amount_meta']
			? $this->read_float_meta( $product, $settings['product_amount_meta'] )
			: 0.0;

		if ( $unit_price <= 0 && $product_amount > 0 && '' !== $unit ) {
			$display = (float) wc_get_price_to_display( $product );
			$base    = $base > 0 ? $base : 1.0;

			if ( $display > 0 ) {
				$unit_price = ( $display / $product_amount ) * $base;
			}
		}

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

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

	private function read_float_meta( WC_Product $product, string $key ): float {
		$value = $product->get_meta( $key );

		return is_numeric( $value ) ? (float) $value : 0.0;
	}
}
