<?php
/**
 * Document currency formatter.
 *
 * A single place that turns a numeric amount into a display string using a
 * currency symbol and placement (D-08). By default it reads the same
 * wrenchpress_settings option array as the rest of the plugin through
 * WrenchPress_Settings_Page::get(), so the symbol is never hard-coded. Callers
 * that render a frozen document pass the symbol and placement captured in that
 * document's branding snapshot so historical reprints stay immune to a later
 * currency-setting change (INV-03 freeze-on-issue).
 *
 * Document-scoped by design: this helper feeds the generated invoice/estimate
 * template (07-06). The work-order admin screen keeps its own bare number_format
 * calls (A4); this class does not touch them.
 *
 * @package WrenchPress
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class WrenchPress_Money
 */
class WrenchPress_Money {

	/**
	 * Format an amount with the configured currency symbol and placement.
	 *
	 * The amount is always rendered with exactly two decimals via number_format
	 * regardless of whether it arrives as a float or a numeric string. When
	 * $symbol or $placement is null the value is read live from the settings
	 * option, so a shop that changes either sees the new formatting immediately.
	 * When both are supplied (for example the frozen branding snapshot of an
	 * issued document) the settings option is never read and the frozen currency
	 * is used verbatim, so a later settings change cannot rewrite a reprint.
	 *
	 * @param float|int|string $amount    Numeric amount to format.
	 * @param string|null      $symbol    Currency symbol, or null to read live.
	 * @param string|null      $placement 'before' or 'after', or null to read live.
	 * @return string Amount with the currency symbol placed before or after.
	 */
	public static function format_money( $amount, $symbol = null, $placement = null ) {
		$number = number_format( (float) $amount, 2 );

		if ( null === $symbol || null === $placement ) {
			$settings  = WrenchPress_Settings_Page::get();
			$symbol    = ( null !== $symbol ) ? (string) $symbol : (string) $settings['currency_symbol'];
			$placement = ( null !== $placement ) ? (string) $placement : (string) $settings['currency_placement'];
		} else {
			$symbol    = (string) $symbol;
			$placement = (string) $placement;
		}

		return 'after' === $placement ? $number . $symbol : $symbol . $number;
	}
}
