<?php

/**
 * Multi-currency compatibility - keeps displayed prices in sync with active currency-conversion plugins.
 *
 * @link       https://nudgesells.com
 * @since      1.0.0
 *
 * @package    NudgeSells
 * @subpackage NudgeSells/includes
 */

if (! defined('ABSPATH')) {
	exit;
}

/**
 * NudgeSells_Currency
 *
 * Adjusts widget price output so it stays consistent with whichever multi-currency plugin, if any, is active.
 *
 * @since      1.0.0
 * @package    NudgeSells
 * @subpackage NudgeSells/includes
 * @author     NudgeSells <support@nudgesells.com>
 */
class NudgeSells_Currency
{

	/**
	 * Convert.
	 *
	 * @param mixed $amount
	 *
	 * @return mixed
	 * @since 1.0.0
	 */
	public static function convert($amount)
	{
		$amount = (float) $amount;
		if ($amount <= 0) {
			return $amount;
		}

		if (has_filter('wcml_raw_price_amount')) {
			$converted = apply_filters('wcml_raw_price_amount', $amount);
			if (is_numeric($converted)) {
				return (float) $converted;
			}
		}

		if (isset($GLOBALS['WOOCS']) && is_object($GLOBALS['WOOCS'])) {
			$woocs = $GLOBALS['WOOCS'];
			if (method_exists($woocs, 'raw_woocommerce_price')) {
				return (float) $woocs->raw_woocommerce_price($amount);
			}
			if (method_exists($woocs, 'process_value')) {
				return (float) $woocs->process_value($amount);
			}
		}

		if (has_filter('wc_aelia_cs_convert') && function_exists('get_woocommerce_currency')) {
			$base    = get_option('woocommerce_currency');
			$current = get_woocommerce_currency();
			if ($current && $base && $current !== $base) {
				$converted = apply_filters('wc_aelia_cs_convert', $amount, $base, $current);
				if (is_numeric($converted)) {
					return (float) $converted;
				}
			}
		}

		return (float) apply_filters('nudgesells_convert_currency_amount', $amount);
	}
}
