<?php

namespace FuseCommerce\Services;

/**
 * Currency Service
 *
 * Handles currency formatting and settings from WooCommerce
 */
class CurrencyService {

	/**
	 * Get WooCommerce currency settings
	 *
	 * @return array Currency configuration
	 */
	public function getCurrencySettings(): array {
		return [
			'code'               => get_woocommerce_currency(),
			'symbol'             => html_entity_decode( get_woocommerce_currency_symbol() ),
			'position'           => get_option( 'woocommerce_currency_pos', 'left' ),
			'thousand_separator' => get_option( 'woocommerce_price_thousand_sep', ',' ),
			'decimal_separator'  => get_option( 'woocommerce_price_decimal_sep', '.' ),
			'decimals'           => get_option( 'woocommerce_price_num_decimals', 2 ),
		];
	}

	/**
	 * Get currency symbol
	 *
	 * @return string Currency symbol (e.g., $, €, £)
	 */
	public function getCurrencySymbol(): string {
		return html_entity_decode( get_woocommerce_currency_symbol() );
	}

	/**
	 * Format a price according to WooCommerce settings
	 *
	 * @param float $price Price to format
	 * @param bool $include_html Whether to include HTML wrapper
	 * @return string Formatted price
	 */
	public function formatPrice( float $price, bool $include_html = false ): string {
		if ( $include_html ) {
			return wc_price( $price );
		}

		$settings = $this->getCurrencySettings();

		// Format the number
		$formatted_price = number_format(
			$price,
			$settings['decimals'],
			$settings['decimal_separator'],
			$settings['thousand_separator']
		);

		// Add currency symbol based on position
		switch ( $settings['position'] ) {
			case 'left':
				return $settings['symbol'] . $formatted_price;
			case 'right':
				return $formatted_price . $settings['symbol'];
			case 'left_space':
				return $settings['symbol'] . ' ' . $formatted_price;
			case 'right_space':
				return $formatted_price . ' ' . $settings['symbol'];
			default:
				return $settings['symbol'] . $formatted_price;
		}
	}

	/**
	 * Format a price range according to WooCommerce settings
	 *
	 * @param float $min_price Minimum price
	 * @param float $max_price Maximum price
	 * @param bool $include_html Whether to include HTML wrapper
	 * @return string Formatted price range
	 */
	public function formatPriceRange( float $min_price, float $max_price, bool $include_html = false ): string {
		$formatted_min = $this->formatPrice( $min_price, $include_html );
		$formatted_max = $this->formatPrice( $max_price, $include_html );

		if ( $formatted_min === $formatted_max ) {
			return $formatted_min;
		}

		return $formatted_min . ' - ' . $formatted_max;
	}
}
