<?php
/**
 * Plain-text helpers for unit price / Grundpreis output.
 *
 * @package PhoenixWP\PriceLabels
 */

declare(strict_types=1);

namespace PhoenixWP\PriceLabels\Compliance;

defined( 'ABSPATH' ) || exit;

/**
 * Normalizes and formats unit price strings for PDF labels.
 */
final class Unit_Price_Text {

	/**
	 * Strips HTML and normalizes whitespace for label output.
	 */
	public static function normalize( string $text ): string {
		$text = html_entity_decode( wp_strip_all_tags( $text ), ENT_QUOTES, 'UTF-8' );
		$text = preg_replace( '/\s+/u', ' ', $text ) ?? $text;

		return trim( $text );
	}

	/**
	 * Formats a PAngV-style line: "1 kg = 200,00 €" (DE-friendly).
	 *
	 * @param float  $unit_price Price per reference unit.
	 * @param float  $base       Reference quantity (e.g. 1 or 100).
	 * @param string $unit       Unit label (e.g. kg, ml).
	 */
	public static function format_line( float $unit_price, float $base, string $unit ): string {
		$base_label = self::format_base_label( $base, $unit );
		$price      = html_entity_decode( wp_strip_all_tags( wc_price( $unit_price ) ), ENT_QUOTES, 'UTF-8' );

		/* translators: %1$s: reference quantity + unit (e.g. 1 kg), %2$s: formatted price. */
		return sprintf( __( '%1$s = %2$s', 'phoenix-price-labels-for-woocommerce' ), $base_label, $price );
	}

	/**
	 * Formats "price / base unit" style used by German Market and Germanized.
	 *
	 * @param float  $unit_price Price per reference unit.
	 * @param float  $base       Reference quantity.
	 * @param string $unit       Unit label.
	 */
	public static function format_per_unit( float $unit_price, float $base, string $unit ): string {
		$price      = html_entity_decode( wp_strip_all_tags( wc_price( $unit_price ) ), ENT_QUOTES, 'UTF-8' );
		$base_label = self::format_base_label( $base, $unit );

		/* translators: %1$s: formatted unit price, %2$s: reference quantity + unit. */
		return sprintf( __( '%1$s / %2$s', 'phoenix-price-labels-for-woocommerce' ), $price, $base_label );
	}

	/**
	 * Builds a human-readable base quantity label.
	 */
	private static function format_base_label( float $base, string $unit ): string {
		$base = $base > 0 ? $base : 1.0;

		if ( function_exists( 'wc_format_localized_decimal' ) ) {
			$amount = wc_format_localized_decimal( (string) $base );
		} else {
			$amount = (string) $base;
		}

		return trim( $amount . ' ' . $unit );
	}
}
