<?php
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

/*
Plugin Name: Smart Convert – Currency & Unit Conversion
Plugin URI: https://petrnovak.cz/plugins/
Description: A conversion engine featuring daily updated exchange rates for 153 currencies and 105 physical units. Includes automatic visitor currency detection via IP, high-performance object caching, custom output templates, and native Gutenberg block support.
Author: Petr Novák
Version: 1.0.2
Author URI: https://www.petrnovak.cz/
Text Domain: smart-convert-currency-unit-conversion
Domain Path: /languages
Requires at least: 5.4
Requires PHP: 7.2
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/

// === CONSTANT DEFINITIONS ===
// Define absolute file paths and URLs for use throughout the plugin.
// This ensures maintainability and compatibility across different server directory structures.
define( 'SMART_CONVERT_PLUGIN_DIR', dirname( __FILE__ ) );
define( 'SMART_CONVERT_PLUGIN_URL', plugins_url( '', __FILE__ ) );
define( 'SMART_CONVERT_INCLUDES_DIR', SMART_CONVERT_PLUGIN_DIR . '/includes' );
define( 'SMART_CONVERT_ADMIN_DIR', SMART_CONVERT_PLUGIN_DIR . '/admin' );
define( 'SMART_CONVERT_VERSION', '1.0.2' );

// === TEXTDOMAIN INITIALIZATION ===
// WordPress loads text domain automatically from plugin headers and language packs.
// Keep JSON script translations on core locale resolution.
// Fallback logic is handled at mofile level for PHP strings only.
add_filter( 'load_textdomain_mofile', 'smart_convert_currency_unit_conversion_filter_mofile_fallback', 10, 2 );
add_action( 'plugins_loaded', 'smart_convert_currency_unit_conversion_force_textdomain_load', 1 );

/**
 * Provide robust locale fallback for this plugin (e.g. cs -> cs_CZ, es_CR -> es_ES).
 *
 * @param string $locale Current plugin locale chosen by WordPress.
 * @param string $domain Text domain.
 * @return string
 */
function smart_convert_currency_unit_conversion_filter_plugin_locale( $locale, $domain ) {
	if ( 'smart-convert-currency-unit-conversion' !== $domain ) {
		return $locale;
	}
	if ( ! is_string( $locale ) || '' === $locale ) {
		return $locale;
	}

	$global_dir = trailingslashit( WP_LANG_DIR ) . 'plugins/';
	$plugin_dir = trailingslashit( SMART_CONVERT_PLUGIN_DIR ) . 'languages/';
	$base_name  = $domain . '-';

	$exact_global = $global_dir . $base_name . $locale . '.mo';
	$exact_plugin = $plugin_dir . $base_name . $locale . '.mo';
	if ( file_exists( $exact_global ) || file_exists( $exact_plugin ) ) {
		return $locale;
	}

	$lang = strtolower( strtok( $locale, '_' ) );
	if ( '' === $lang ) {
		return $locale;
	}

	$lang_defaults = array(
		'cs' => 'cs_CZ',
		'es' => 'es_ES',
		'pt' => 'pt_BR',
		'en' => 'en_US',
		'fr' => 'fr_FR',
		'de' => 'de_DE',
		'it' => 'it_IT',
		'ru' => 'ru_RU',
		'pl' => 'pl_PL',
		'nl' => 'nl_NL',
		'tr' => 'tr_TR',
		'id' => 'id_ID',
		'ja' => 'ja',
	);

	if ( isset( $lang_defaults[ $lang ] ) ) {
		$mapped_locale = $lang_defaults[ $lang ];
		$map_global    = $global_dir . $base_name . $mapped_locale . '.mo';
		$map_plugin    = $plugin_dir . $base_name . $mapped_locale . '.mo';
		if ( file_exists( $map_global ) || file_exists( $map_plugin ) ) {
			return $mapped_locale;
		}
	}

	$matches = array();
	$glob_1  = glob( $global_dir . $base_name . $lang . '_*.mo' );
	$glob_2  = glob( $plugin_dir . $base_name . $lang . '_*.mo' );
	if ( is_array( $glob_1 ) ) {
		$matches = array_merge( $matches, $glob_1 );
	}
	if ( is_array( $glob_2 ) ) {
		$matches = array_merge( $matches, $glob_2 );
	}
	if ( empty( $matches ) ) {
		return $locale;
	}

	sort( $matches, SORT_NATURAL | SORT_FLAG_CASE );
	$first = basename( $matches[0] );
	if ( 0 !== strpos( $first, $base_name ) || '.mo' !== substr( $first, -3 ) ) {
		return $locale;
	}

	$fallback_locale = substr( $first, strlen( $base_name ), -3 );
	return ( is_string( $fallback_locale ) && '' !== $fallback_locale ) ? $fallback_locale : $locale;
}

/**
 * Fallback .mo resolver for cases where WordPress requests non-existing locale files.
 *
 * @param string $mofile Full path to requested mofile.
 * @param string $domain Text domain.
 * @return string
 */
function smart_convert_currency_unit_conversion_filter_mofile_fallback( $mofile, $domain ) {
	if ( 'smart-convert-currency-unit-conversion' !== $domain ) {
		return $mofile;
	}
	if ( file_exists( $mofile ) ) {
		return $mofile;
	}

	$global_dir = trailingslashit( WP_LANG_DIR ) . 'plugins/';
	$plugin_dir = trailingslashit( SMART_CONVERT_PLUGIN_DIR ) . 'languages/';
	$base_name  = 'smart-convert-currency-unit-conversion-';

	$current_locale = function_exists( 'determine_locale' ) ? determine_locale() : get_locale();
	if ( ! is_string( $current_locale ) || '' === $current_locale ) {
		return $mofile;
	}

	$lang = strtolower( strtok( $current_locale, '_' ) );
	if ( '' === $lang ) {
		return $mofile;
	}

	$candidates = array(
		$global_dir . $base_name . $current_locale . '.mo',
		$plugin_dir . $base_name . $current_locale . '.mo',
	);

	$lang_defaults = array(
		'cs' => 'cs_CZ',
		'es' => 'es_ES',
		'pt' => 'pt_BR',
		'en' => 'en_US',
		'fr' => 'fr_FR',
		'de' => 'de',
		'it' => 'it_IT',
		'ru' => 'ru_RU',
		'pl' => 'pl_PL',
		'nl' => 'nl_NL',
		'tr' => 'tr_TR',
		'id' => 'id_ID',
		'ja' => 'ja',
	);
	if ( isset( $lang_defaults[ $lang ] ) ) {
		$mapped = $lang_defaults[ $lang ];
		$candidates[] = $global_dir . $base_name . $mapped . '.mo';
		$candidates[] = $plugin_dir . $base_name . $mapped . '.mo';
	}

	$glob_global = glob( $global_dir . $base_name . $lang . '_*.mo' );
	$glob_plugin = glob( $plugin_dir . $base_name . $lang . '_*.mo' );
	if ( is_array( $glob_global ) ) {
		$candidates = array_merge( $candidates, $glob_global );
	}
	if ( is_array( $glob_plugin ) ) {
		$candidates = array_merge( $candidates, $glob_plugin );
	}

	$candidates = array_values( array_unique( $candidates ) );
	foreach ( $candidates as $candidate ) {
		if ( is_string( $candidate ) && '' !== $candidate && file_exists( $candidate ) ) {
			return $candidate;
		}
	}

	return $mofile;
}

/**
 * Force-load plugin translations from the best available locale file.
 *
 * This protects admin translations from stale or incorrect global language packs.
 *
 * @return void
 */
function smart_convert_currency_unit_conversion_force_textdomain_load() {
	$domain = 'smart-convert-currency-unit-conversion';

	$current_locale = function_exists( 'determine_locale' ) ? determine_locale() : get_locale();
	if ( ! is_string( $current_locale ) || '' === $current_locale ) {
		return;
	}

	$preferred_mofile = smart_convert_currency_unit_conversion_resolve_locale_mofile( $current_locale, $domain );
	if ( '' === $preferred_mofile ) {
		return;
	}

	unload_textdomain( $domain );
	load_textdomain( $domain, $preferred_mofile );
}

/**
 * Resolve preferred mofile path for current locale (with fallbacks).
 *
 * @param string $locale Locale code.
 * @param string $domain Text domain.
 * @return string
 */
function smart_convert_currency_unit_conversion_resolve_locale_mofile( $locale, $domain ) {
	$global_dir = trailingslashit( WP_LANG_DIR ) . 'plugins/';
	$plugin_dir = trailingslashit( SMART_CONVERT_PLUGIN_DIR ) . 'languages/';
	$base_name  = $domain . '-';

	$paths = array();
	$paths[] = $plugin_dir . $base_name . $locale . '.mo';
	$paths[] = $global_dir . $base_name . $locale . '.mo';

	$lang = strtolower( strtok( $locale, '_' ) );
	if ( '' !== $lang ) {
		$defaults = array(
			'cs' => 'cs_CZ',
			'es' => 'es_ES',
			'pt' => 'pt_BR',
			'en' => 'en_US',
			'fr' => 'fr_FR',
			'de' => 'de',
			'it' => 'it_IT',
			'ru' => 'ru_RU',
			'pl' => 'pl_PL',
			'nl' => 'nl_NL',
			'tr' => 'tr_TR',
			'id' => 'id_ID',
			'ja' => 'ja',
		);
		if ( isset( $defaults[ $lang ] ) ) {
			$mapped = $defaults[ $lang ];
			$paths[] = $plugin_dir . $base_name . $mapped . '.mo';
			$paths[] = $global_dir . $base_name . $mapped . '.mo';
		}

		$plugin_matches = glob( $plugin_dir . $base_name . $lang . '_*.mo' );
		$global_matches = glob( $global_dir . $base_name . $lang . '_*.mo' );
		if ( is_array( $plugin_matches ) && ! empty( $plugin_matches ) ) {
			sort( $plugin_matches, SORT_NATURAL | SORT_FLAG_CASE );
			$paths = array_merge( $paths, $plugin_matches );
		}
		if ( is_array( $global_matches ) && ! empty( $global_matches ) ) {
			sort( $global_matches, SORT_NATURAL | SORT_FLAG_CASE );
			$paths = array_merge( $paths, $global_matches );
		}
	}

	$paths = array_values( array_unique( $paths ) );
	foreach ( $paths as $path ) {
		if ( is_string( $path ) && '' !== $path && file_exists( $path ) ) {
			return $path;
		}
	}

	return '';
}

// === CORE FILE INCLUSION ===
// Load essential plugin components.
// - smart-convert-currency-unit-conversion-database.php: Handles custom table creation and SQL interaction.
// - smart-convert-currency-unit-conversion-cron.php: Manages scheduled tasks (e.g., fetching exchange rates).
// - smart-convert-currency-unit-conversion-shortcode.php: Registers the [smart-convert] shortcode for frontend display.
// - smart-convert-currency-unit-conversion-geolocation.php: Handles IP-based currency detection.
// - admin/: Contains the logic for the backend settings interface.
require_once( SMART_CONVERT_INCLUDES_DIR . '/smart-convert-currency-unit-conversion-database.php' );
require_once( SMART_CONVERT_INCLUDES_DIR . '/smart-convert-currency-unit-conversion-cron.php' );
require_once( SMART_CONVERT_INCLUDES_DIR . '/smart-convert-currency-unit-conversion-i18n-map.php' );
require_once( SMART_CONVERT_INCLUDES_DIR . '/smart-convert-currency-unit-conversion-shortcode.php' );
require_once( SMART_CONVERT_INCLUDES_DIR . '/smart-convert-currency-unit-conversion-geolocation.php' );
require_once( SMART_CONVERT_ADMIN_DIR . '/class-smart-convert-currency-unit-conversion-admin.php' );

// =================================================================
// === ACTIVATION HOOK - Setup Routine ===
// =================================================================

// Register the function to be executed when the plugin is activated by the user.
register_activation_hook( __FILE__, 'smart_convert_currency_unit_conversion_plugin_activation_routine' );

/**
 * Executes the plugin setup sequence upon activation.
 *
 * This function orchestrates the initialization process:
 * 1. Creates necessary custom database tables.
 * 2. Populates default configuration settings based on the server locale.
 * 3. Sets a transient flag to redirect the user to an onboarding/welcome page.
 *
 * @since 1.0.0
 * @return void
 */
function smart_convert_currency_unit_conversion_plugin_activation_routine() {
    // 1. Database Schema Setup:
    // Execute the table creation logic defined in smart-convert-currency-unit-conversion-database.php.
    if ( function_exists( 'smart_convert_currency_unit_conversion_create_tables' ) ) {
        smart_convert_currency_unit_conversion_create_tables();
    }
    
    // 2. Default Options Configuration:
    // Configure the plugin defaults (currency, units, formatting) based on the WordPress site language.
    // Note: To comply with WordPress.org guidelines, we do not fetch external API data here.
    // External connections require explicit user consent via the Onboarding flow.
    smart_convert_currency_unit_conversion_set_default_options_on_activation();

    // 3. UX - Welcome Redirect:
    // Set a transient 'smart_convert_currency_unit_conversion_welcome_redirect' valid for 60 seconds.
    // This flag is checked by the admin class to redirect the user to the settings page
    // immediately after activation, ensuring they consent to external data fetching.
    set_transient( 'smart_convert_currency_unit_conversion_welcome_redirect', true, 60 );
}

/**
 * Configures default plugin settings based on the WordPress locale.
 *
 * This function attempts to "smart guess" the best settings for the user
 * (e.g., Metric vs Imperial, Currency, Date Format) based on the `get_locale()` return value.
 *
 * Logic Hierarchy:
 * 1. Checks if options already exist (preserves user customization).
 * 2. Sets a "Universal/US" baseline (Imperial units).
 * 3. Overrides with "Metric" defaults for non-US locales.
 * 4. Applies specific formatting rules for distinct regions (EU, Americas, Asia, etc.).
 *
 * @since 1.0.0
 * @return void
 */
function smart_convert_currency_unit_conversion_set_default_options_on_activation() {
    // Guard clause: If the main option array already exists in the database,
    // do not overwrite it. This preserves settings if the plugin is deactivated and reactivated.
    if ( get_option( 'smart_convert_currency_unit_conversion_option_name' ) !== false ) {
        return;
    }

    $locale = get_locale(); // Returns the WP locale code (e.g., 'cs_CZ', 'en_US', 'de_DE').

    // === 1. UNIVERSAL BASELINE (US Standard / Imperial) ===
    // We start with US defaults as a fallback.
    $defaults = array(
        'smart_convert_currency_unit_conversion_default_currency'     => 'USD',
        'auto_currency_from_ip'    => '0', 
        'smart_convert_currency_unit_conversion_date_format'          => 'F j, Y', 
        'smart_convert_currency_unit_conversion_separator_thousands'  => ',',
        'smart_convert_currency_unit_conversion_separator_decimals'   => '.',
        'smart_convert_currency_unit_conversion_default_temperature'  => 'F',
        'smart_convert_currency_unit_conversion_default_length_long'  => 'ft',
        'smart_convert_currency_unit_conversion_default_length_short' => 'in',
        'smart_convert_currency_unit_conversion_default_speed'        => 'mph',
        'smart_convert_currency_unit_conversion_default_distance'     => 'mi',
        'smart_convert_currency_unit_conversion_default_weight'       => 'lb',
        'smart_convert_currency_unit_conversion_default_area'         => 'sqmi',
        'smart_convert_currency_unit_conversion_spread'               => '0', 
        'smart_convert_currency_unit_conversion_spread_msg_enable'    => '0',
        'smart_convert_currency_unit_conversion_bubble_color'         => '#424242',
        'smart_convert_currency_unit_conversion_bubble_font'          => '#ffffff',
        // CRITICAL: External data fetching is disabled by default (GDPR/Privacy/WP.org compliance).
        // The user must enable this in the settings/onboarding.
        'smart_convert_currency_unit_conversion_enable_external_data' => '0' 
    );

    // === 2. METRIC SYSTEM OVERRIDE ===
    // If the locale is NOT 'en_US', we assume the rest of the world uses the Metric system.
    // Note: Liberia and Myanmar also use Imperial/Mixed, but 'en_US' is the primary filter here.
    if ( $locale !== 'en_US' ) {
        $defaults['smart_convert_currency_unit_conversion_default_temperature']  = 'C';
        $defaults['smart_convert_currency_unit_conversion_default_length_long']  = 'm';
        $defaults['smart_convert_currency_unit_conversion_default_length_short'] = 'cm';
        $defaults['smart_convert_currency_unit_conversion_default_speed']        = 'kph';
        $defaults['smart_convert_currency_unit_conversion_default_distance']     = 'km';
        $defaults['smart_convert_currency_unit_conversion_default_weight']       = 'kg';
        $defaults['smart_convert_currency_unit_conversion_default_area']         = 'sqkm';
        $defaults['smart_convert_currency_unit_conversion_date_format']          = 'd.m.Y'; 
    }

    // === 3. REGIONAL SPECIFICS (Currency and Number Formatting) ===
    // Fine-tune currency codes and number separators for specific countries/regions.
    switch ( $locale ) {

        // ==========================================
        // === CENTRAL & EASTERN EUROPE ===
        // ==========================================
        
        // Czech Republic
        case 'cs_CZ':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'CZK';
            $defaults['smart_convert_currency_unit_conversion_date_format']       = 'j. n. Y';
            // Use Non-Breaking Space (NBSP - \xC2\xA0) for thousands.
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = "\xC2\xA0"; 
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = ',';
            break;
            
        // Slovakia
        case 'sk_SK':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'EUR';
            $defaults['smart_convert_currency_unit_conversion_date_format']       = 'j. n. Y';
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = "\xC2\xA0";
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = ',';
            break;

        // Poland
        case 'pl_PL':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'PLN';
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = "\xC2\xA0";
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = ',';
            break;

        // Hungary
        case 'hu_HU':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'HUF';
            $defaults['smart_convert_currency_unit_conversion_date_format']       = 'Y. F j.';
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = "\xC2\xA0";
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = ',';
            break;

        // Ukraine
        case 'uk_UA':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'UAH';
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = "\xC2\xA0";
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = ',';
            break;

        // Russia & CIS (Common format)
        case 'ru_RU':
        case 'be_BY': // Belarus
        case 'kk_KZ': // Kazakhstan
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = ( $locale === 'ru_RU' ) ? 'RUB' : ( ( $locale === 'be_BY' ) ? 'BYN' : 'KZT' );
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = "\xC2\xA0";
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = ',';
            break;

        // ==========================================
        // === EUROZONE & WESTERN EUROPE ===
        // ==========================================
        
        // Eurozone (German/French/Dutch/Italian/Spanish/Portuguese/etc.)
        // These countries generally use '.' for thousands and ',' for decimals.
        case 'de_DE': // Germany
        case 'de_AT': // Austria
        case 'it_IT': // Italy
        case 'es_ES': // Spain
        case 'nl_NL': // Netherlands
        case 'nl_BE': // Belgium (Flemish)
        case 'pt_PT': // Portugal
        case 'el_GR': // Greece
        case 'fi_FI': // Finland
        case 'sl_SI': // Slovenia
        case 'et_EE': // Estonia
        case 'lv_LV': // Latvia
        case 'lt_LT': // Lithuania
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'EUR';
            $defaults['smart_convert_currency_unit_conversion_date_format']       = 'd.m.Y'; // Common DE format, overridden for others if needed below
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = '.';
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = ',';
            
            // Adjust specific date formats
            if ( strpos( $locale, 'nl_' ) === 0 ) $defaults['smart_convert_currency_unit_conversion_date_format'] = 'j-n-Y';
            if ( strpos( $locale, 'it_' ) === 0 || strpos( $locale, 'es_' ) === 0 ) $defaults['smart_convert_currency_unit_conversion_date_format'] = 'd/m/Y';
            break;

        // France & Belgium (French) - Special separator case
        case 'fr_FR':
        case 'fr_BE':
        case 'fr_LU':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'EUR';
            $defaults['smart_convert_currency_unit_conversion_date_format']       = 'd/m/Y';
            // France uses NBSP for thousands
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = "\xC2\xA0";
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = ',';
            break;

        // Switzerland (Special formatting)
        case 'de_CH':
        case 'fr_CH':
        case 'it_CH':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'CHF';
            // Swiss use apostrophe for thousands
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = "'";
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = '.';
            break;

        // Sweden
        case 'sv_SE':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'SEK';
            $defaults['smart_convert_currency_unit_conversion_date_format']       = 'Y-m-d';
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = "\xC2\xA0";
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = ',';
            break;
            
        // Turkey
        case 'tr_TR':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'TRY';
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = '.';
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = ',';
            break;

        // ==========================================
        // === ANGLOPHONE WORLD ===
        // ==========================================

        // United Kingdom
        case 'en_GB':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'GBP';
            $defaults['smart_convert_currency_unit_conversion_date_format']       = 'd F Y';
            // UK uses Miles/MPH despite being largely metric otherwise
            $defaults['smart_convert_currency_unit_conversion_default_speed']     = 'mph';
            $defaults['smart_convert_currency_unit_conversion_default_distance']  = 'mi';
            break;

        // Ireland
        case 'en_IE':
        case 'ga_IE':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'EUR';
            $defaults['smart_convert_currency_unit_conversion_default_speed']     = 'kph'; // Ireland uses metric speed limits
            $defaults['smart_convert_currency_unit_conversion_default_distance']  = 'km';
            break;

        // Australia
        case 'en_AU':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'AUD';
            $defaults['smart_convert_currency_unit_conversion_date_format']       = 'j F Y';
            break;

        // Canada
        case 'en_CA':
        case 'fr_CA': // French Canada
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'CAD';
            $defaults['smart_convert_currency_unit_conversion_date_format']       = 'Y-m-d';
            // Canada uses a mix in colloquial usage, but we default to official Metric settings set above.
            break;

        // New Zealand
        case 'en_NZ':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'NZD';
            break;

        // South Africa
        case 'en_ZA':
        case 'af_ZA':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'ZAR';
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = "\xC2\xA0"; // Space
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = ',';
            break;

        // ==========================================
        // === LATIN AMERICA & BRIC ===
        // ==========================================

        // Brazil
        case 'pt_BR':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'BRL';
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = '.';
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = ',';
            break;

        // Mexico (US-style formatting)
        case 'es_MX':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'MXN';
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = ',';
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = '.';
            break;

        // Argentina, Chile, Colombia, Uruguay, Venezuela (EU-style formatting)
        // Groups multiple cases to avoid 'goto' statements while keeping code DRY.
        case 'es_AR':
        case 'es_CL':
        case 'es_CO':
        case 'es_UY':
        case 'es_VE':
            // Common formatting for these regions
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = '.';
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = ',';
            $defaults['smart_convert_currency_unit_conversion_date_format']         = 'd/m/Y';

            // Map specific currency to locale
            $latam_currencies = array(
                'es_AR' => 'ARS',
                'es_CL' => 'CLP',
                'es_CO' => 'COP',
                'es_UY' => 'UYU',
                'es_VE' => 'VES',
            );

            // Assign currency if locale exists in map
            if ( array_key_exists( $locale, $latam_currencies ) ) {
                $defaults['smart_convert_currency_unit_conversion_default_currency'] = $latam_currencies[ $locale ];
            }
            break;

        // Peru (Mixed/US style)
        case 'es_PE':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'PEN';
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = ',';
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = '.';
            break;

        // ==========================================
        // === ASIA & PACIFIC ===
        // ==========================================

        // Japan
        case 'ja_JP':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'JPY';
            $defaults['smart_convert_currency_unit_conversion_date_format']       = 'Y年n月j日';
            break;

        // China (Mainland)
        case 'zh_CN':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'CNY';
            $defaults['smart_convert_currency_unit_conversion_date_format']       = 'Y-m-d';
            break;

        // Taiwan
        case 'zh_TW':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'TWD';
            break;

        // Hong Kong
        case 'zh_HK':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'HKD';
            break;

        // Indonesia
        case 'id_ID':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'IDR';
            $defaults['smart_convert_currency_unit_conversion_separator_thousands'] = '.';
            $defaults['smart_convert_currency_unit_conversion_separator_decimals']  = ',';
            break;
            
        // India (English)
        case 'en_IN':
        case 'hi_IN':
            $defaults['smart_convert_currency_unit_conversion_default_currency'] = 'INR';
            // India uses a unique grouping system (Lakhs/Crores), but standard ',' is the closest approximation here.
            break;
    }

    // Save the computed default settings to the WordPress database.
    update_option( 'smart_convert_currency_unit_conversion_option_name', $defaults );
}


// === UPDATE HANDLER ===
// Handle logic immediately following a plugin update/upgrade.
// This ensures that if the plugin structure or data requirements change,
// the system attempts to refresh necessary data (like exchange rates).
add_action( 'upgrader_process_complete', function( $upgrader, $options ) {
    $action = isset( $options['action'] ) ? $options['action'] : '';
    $type   = isset( $options['type'] )   ? $options['type']   : '';
    $plugins = isset( $options['plugins'] ) ? (array) $options['plugins'] : array();

    // Only proceed if the action is 'update' and the type is 'plugin'.
    if ( $action === 'update' && $type === 'plugin' ) {
        // Check if THIS specific plugin was the one updated.
        if ( in_array( plugin_basename( __FILE__ ), $plugins, true ) ) {
            // Schedule a single event to update currency rates shortly (10s) after the update finishes.
            // Note: The callback function 'smart_convert_currency_unit_conversion_update_currency_hook' (defined in smart-convert-currency-unit-conversion-cron.php) 
            // will internally check 'smart_convert_currency_unit_conversion_enable_external_data' before making API calls.
            if ( ! wp_next_scheduled( 'smart_convert_currency_unit_conversion_update_currency_hook' ) ) {
                wp_schedule_single_event( time() + 10, 'smart_convert_currency_unit_conversion_update_currency_hook' );
            }
        }
    }
}, 10, 2 );

// === ADMIN CLASS INSTANTIATION ===
// If the current request is within the WP Admin dashboard, instantiate the admin controller.
if ( is_admin() ) {
	$smart_convert_currency_unit_conversion = new smart_convert_currency_unit_conversion();
}