<?php

/**
 * Currency logic handling with optimized performance
 *
 * @package Kubelio\Core
 * @since 1.0.0
 */

namespace Kubelio\Core;

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

class Currency {

	/**
	 * Cached currency data for the current request
	 * @var array|null
	 */
	private static $cached_list = null;

	/**
	 * Get unified currency data from custom settings
	 * 
	 * @return array
	 */
	public static function get_list() {
		if (null !== self::$cached_list) {
			return self::$cached_list;
		}

		$switcher_on = get_theme_mod('currency_switcher', false);

		if (!$switcher_on || ! class_exists('WOOCS')) {
			return self::$cached_list = array();
		}

		$display_format = get_theme_mod('currency_format', '{{currency}} {{symbol}}');
		$current        = get_woocommerce_currency();
		$processed_list = self::get_fox_source($current);

		if (empty($processed_list)) {
			return self::$cached_list = array();
		}

		// Consolidate and Generate Labels
		if (!isset($processed_list[$current])) {
			$current = key($processed_list);
		}

		$output = array(
			'list'      => $processed_list,
			'current'   => $current,
			'symbol'    => isset($processed_list[$current]['symbol']) ? $processed_list[$current]['symbol'] : '',
			'flag'      => isset($processed_list[$current]['flag']) ? $processed_list[$current]['flag'] : '',
			'country'   => isset($processed_list[$current]['country']) ? $processed_list[$current]['country'] : '',
			'url_param' => 'currency',
			'show_flag' => get_theme_mod('currency_flag', true),
		);

		// Apply Labels formatting
		$output['label'] = self::format_label($output['current'], $output['symbol'], $output['country'], $display_format);

		foreach ($output['list'] as $code => $data) {
			$output['list'][$code]['label'] = self::format_label($code, $data['symbol'], $data['country'], $display_format);
		}

		return self::$cached_list = apply_filters('kubelio_currency_list', $output);
	}

	/**
	 * Fetch data from FOX/WOOCS Plugin
	 */
	private static function get_fox_source(&$current) {
		global $WOOCS;
		$list = array();
		
		$woocs_instance = (isset($WOOCS)) ? $WOOCS : ( (class_exists('WOOCS') && method_exists('WOOCS', 'instance')) ? \WOOCS::instance() : null );

		if ($woocs_instance) {
			$current        = $woocs_instance->current_currency;
			$woocs_data     = $woocs_instance->get_currencies();
			$wc_currencies  = function_exists('get_woocommerce_currencies') ? get_woocommerce_currencies() : array();

			foreach ($woocs_data as $code => $data) {
				$list[$code] = array(
					'symbol'  => isset($data['symbol']) ? $data['symbol'] : $code,
					'country' => self::get_clean_country_name($code, $wc_currencies),
					'flag'    => isset($data['flag']) ? $data['flag'] : '',
				);
			}
		}
		return $list;
	}

	/**
	 * Clean country names from WooCommerce raw currency names
	 */
	private static function get_clean_country_name($code, $wc_currencies) {
		$name = isset($wc_currencies[$code]) ? $wc_currencies[$code] : $code;
		$name = html_entity_decode($name, ENT_QUOTES, 'UTF-8');
		
		$clean = trim(preg_replace('/(\s?\(.*|\s?dollars?|\s?pounds?|\s?rupiah\s?|\s?euro\s?|\s?yen\s?|\s?won\s?|\s?baht\s?)/i', '', $name));
		return str_replace('Indonesian', 'Indonesia', $clean);
	}

	/**
	 * Format label using placeholders
	 */
	private static function format_label($code, $symbol, $country, $format) {
		return trim(str_replace(
			array('{{country}}', '{{currency}}', '{{symbol}}'),
			array($country, $code, $symbol),
			$format
		));
	}
}
