<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.WP.EnqueuedResourceParameters
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable WordPress.DB.PreparedSQLPlaceholders
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable PluginCheck.Security.DirectDB
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum

/**
 * GT BOGO Engine — Multi-Currency (Enterprise)
 *
 * @package GT_BOGO_Engine
 * @since   3.11.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_options' ) ) {
	return;
}

$is_pro       = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;
$message      = '';
$message_type = '';

// Detect currency plugins
$has_wpml     = defined( 'WCML_VERSION' );
$has_aelia    = class_exists( 'Aelia\WC\CurrencySwitcher\Plugin' );
$has_wmc      = class_exists( 'WOOMULTI_CURRENCY' );
$has_curcy    = class_exists( 'WOOMC\App' );
$has_currency = $has_wpml || $has_aelia || $has_wmc || $has_curcy;
$base_curr    = get_woocommerce_currency();

// Full currency list
$all_currencies = array(
	// Major Global
	'USD' => 'US Dollar',
	'EUR' => 'Euro',
	'GBP' => 'British Pound',
	'JPY' => 'Japanese Yen',
	'CHF' => 'Swiss Franc',
	'CNY' => 'Chinese Yuan',
	'HKD' => 'Hong Kong Dollar',
	// Americas
	'CAD' => 'Canadian Dollar',
	'MXN' => 'Mexican Peso',
	'BRL' => 'Brazilian Real',
	'ARS' => 'Argentine Peso',
	'CLP' => 'Chilean Peso',
	'COP' => 'Colombian Peso',
	'PEN' => 'Peruvian Sol',
	'UYU' => 'Uruguayan Peso',
	'BOB' => 'Bolivian Boliviano',
	'PYG' => 'Paraguayan Guarani',
	'VES' => 'Venezuelan Bolivar',
	'GTQ' => 'Guatemalan Quetzal',
	'HNL' => 'Honduran Lempira',
	'NIO' => 'Nicaraguan Cordoba',
	'CRC' => 'Costa Rican Colon',
	'PAB' => 'Panamanian Balboa',
	'DOP' => 'Dominican Peso',
	'CUP' => 'Cuban Peso',
	'TTD' => 'Trinidad and Tobago Dollar',
	'BBD' => 'Barbadian Dollar',
	'JMD' => 'Jamaican Dollar',
	'HTG' => 'Haitian Gourde',
	'BSD' => 'Bahamian Dollar',
	'BZD' => 'Belize Dollar',
	'GYD' => 'Guyanese Dollar',
	'SRD' => 'Surinamese Dollar',
	'AWG' => 'Aruban Florin',
	// Europe
	'SEK' => 'Swedish Krona',
	'NOK' => 'Norwegian Krone',
	'DKK' => 'Danish Krone',
	'PLN' => 'Polish Zloty',
	'CZK' => 'Czech Koruna',
	'HUF' => 'Hungarian Forint',
	'RON' => 'Romanian Leu',
	'BGN' => 'Bulgarian Lev',
	'HRK' => 'Croatian Kuna',
	'RSD' => 'Serbian Dinar',
	'BAM' => 'Bosnia and Herzegovina Mark',
	'MKD' => 'Macedonian Denar',
	'ALL' => 'Albanian Lek',
	'MDL' => 'Moldovan Leu',
	'UAH' => 'Ukrainian Hryvnia',
	'BYN' => 'Belarusian Ruble',
	'ISK' => 'Icelandic Krona',
	'RUB' => 'Russian Ruble',
	'GEL' => 'Georgian Lari',
	'AMD' => 'Armenian Dram',
	'AZN' => 'Azerbaijani Manat',
	'TRY' => 'Turkish Lira',
	'CHF' => 'Swiss Franc',
	// Middle East & Africa
	'AED' => 'UAE Dirham',
	'SAR' => 'Saudi Riyal',
	'QAR' => 'Qatari Riyal',
	'KWD' => 'Kuwaiti Dinar',
	'BHD' => 'Bahraini Dinar',
	'OMR' => 'Omani Rial',
	'JOD' => 'Jordanian Dinar',
	'LBP' => 'Lebanese Pound',
	'ILS' => 'Israeli New Shekel',
	'EGP' => 'Egyptian Pound',
	'MAD' => 'Moroccan Dirham',
	'TND' => 'Tunisian Dinar',
	'DZD' => 'Algerian Dinar',
	'LYD' => 'Libyan Dinar',
	'SDG' => 'Sudanese Pound',
	'ETB' => 'Ethiopian Birr',
	'KES' => 'Kenyan Shilling',
	'TZS' => 'Tanzanian Shilling',
	'UGX' => 'Ugandan Shilling',
	'RWF' => 'Rwandan Franc',
	'BIF' => 'Burundian Franc',
	'DJF' => 'Djiboutian Franc',
	'SOS' => 'Somali Shilling',
	'MWK' => 'Malawian Kwacha',
	'ZMW' => 'Zambian Kwacha',
	'ZWL' => 'Zimbabwean Dollar',
	'ZAR' => 'South African Rand',
	'BWP' => 'Botswana Pula',
	'NAD' => 'Namibian Dollar',
	'SZL' => 'Swazi Lilangeni',
	'LSL' => 'Lesotho Loti',
	'MZN' => 'Mozambican Metical',
	'AOA' => 'Angolan Kwanza',
	'CDF' => 'Congolese Franc',
	'XAF' => 'Central African CFA Franc',
	'XOF' => 'West African CFA Franc',
	'GHS' => 'Ghanaian Cedi',
	'NGN' => 'Nigerian Naira',
	'XOF' => 'West African CFA Franc',
	'GMD' => 'Gambian Dalasi',
	'GNF' => 'Guinean Franc',
	'SLL' => 'Sierra Leonean Leone',
	'LRD' => 'Liberian Dollar',
	'CVE' => 'Cape Verdean Escudo',
	'STN' => 'Sao Tome and Principe Dobra',
	'MRU' => 'Mauritanian Ouguiya',
	'MUR' => 'Mauritian Rupee',
	'SCR' => 'Seychellois Rupee',
	'KMF' => 'Comorian Franc',
	'MGA' => 'Malagasy Ariary',
	'ERN' => 'Eritrean Nakfa',
	// Asia Pacific
	'AUD' => 'Australian Dollar',
	'NZD' => 'New Zealand Dollar',
	'SGD' => 'Singapore Dollar',
	'MYR' => 'Malaysian Ringgit',
	'THB' => 'Thai Baht',
	'IDR' => 'Indonesian Rupiah',
	'PHP' => 'Philippine Peso',
	'KRW' => 'South Korean Won',
	'TWD' => 'New Taiwan Dollar',
	'INR' => 'Indian Rupee',
	'PKR' => 'Pakistani Rupee',
	'BDT' => 'Bangladeshi Taka',
	'LKR' => 'Sri Lankan Rupee',
	'NPR' => 'Nepalese Rupee',
	'BTN' => 'Bhutanese Ngultrum',
	'MVR' => 'Maldivian Rufiyaa',
	'MMK' => 'Myanmar Kyat',
	'KHR' => 'Cambodian Riel',
	'LAK' => 'Lao Kip',
	'VND' => 'Vietnamese Dong',
	'MNT' => 'Mongolian Tugrik',
	'KZT' => 'Kazakhstani Tenge',
	'UZS' => 'Uzbekistani Som',
	'TJS' => 'Tajikistani Somoni',
	'KGS' => 'Kyrgyzstani Som',
	'TMT' => 'Turkmenistani Manat',
	'AFN' => 'Afghan Afghani',
	'IRR' => 'Iranian Rial',
	'IQD' => 'Iraqi Dinar',
	'SYP' => 'Syrian Pound',
	'YER' => 'Yemeni Rial',
	'PGK' => 'Papua New Guinean Kina',
	'FJD' => 'Fijian Dollar',
	'SBD' => 'Solomon Islands Dollar',
	'VUV' => 'Vanuatu Vatu',
	'WST' => 'Samoan Tala',
	'TOP' => 'Tongan Paanga',
	'XPF' => 'CFP Franc',
);

// Save currency settings
if ( $is_pro && isset( $_POST['gtbogo_save_currency'] ) && check_admin_referer( 'gtbogo_currency', 'gtbogo_cur_nonce' ) ) {
	$raw       = (array) ( $_POST['currencies'] ?? array() ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- keys and values sanitized in foreach
	$overrides = array();
	foreach ( $raw as $code => $data ) {
		$code = strtoupper( sanitize_text_field( $code ) );
		if ( ! isset( $all_currencies[ $code ] ) ) {
			continue;
		}
		$overrides[ $code ] = array(
			'enabled'       => ! empty( $data['enabled'] ),
			'threshold'     => floatval( $data['threshold'] ?? 0 ),
			'min_cart'      => floatval( $data['min_cart'] ?? 0 ),
			'discount_cap'  => floatval( $data['discount_cap'] ?? 0 ),
			'rate_override' => floatval( $data['rate_override'] ?? 0 ),
			'note'          => sanitize_text_field( $data['note'] ?? '' ),
		);
	}
	// Save global settings
	update_option( 'gtbogo_currency_overrides', $overrides );
	update_option( 'gtbogo_currency_rounding', sanitize_text_field( $_POST['currency_rounding'] ?? 'none' ) );
	update_option( 'gtbogo_currency_fallback', sanitize_text_field( $_POST['currency_fallback'] ?? 'base' ) );
	update_option( 'gtbogo_currency_auto_rate', isset( $_POST['currency_auto_rate'] ) );
	if ( function_exists( 'gt_bogo_log' ) ) {
		gt_bogo_log( 'Currency settings updated', count( $overrides ) . ' currency overrides saved', 'success' );
	}
	delete_transient( 'gtbogo_active_rules' );
	delete_transient( 'gtbogo_active_rules_summary' );
	$message      = 'Multi-currency settings saved.';
	$message_type = 'success';
}

$overrides     = get_option( 'gtbogo_currency_overrides', array() );
$rounding      = get_option( 'gtbogo_currency_rounding', 'none' );
$fallback_mode = get_option( 'gtbogo_currency_fallback', 'base' );
$auto_rate     = get_option( 'gtbogo_currency_auto_rate', false );

// Enabled count
$enabled_count = count( array_filter( $overrides, fn( $o ) => ! empty( $o['enabled'] ) ) );

// Current rate (WooCommerce or plugin)
$current_rate = 1.0;
if ( $has_aelia && method_exists( 'Aelia\WC\CurrencySwitcher\Plugin', 'instance' ) ) {
	// Would use Aelia rate API here
}

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">💱 Multi-Currency</h1>
		<p class="gt-page-subtitle">Per-currency BOGO thresholds, discount caps, and cart minimums — precision pricing for global stores</p>
	</div>
	<span class="gt-badge <?php echo esc_html( $has_currency ) ? 'gt-badge-active' : 'gt-badge-free'; ?>">
		<?php echo esc_html( $has_currency ) ? '● Currency Plugin Detected' : '○ No Currency Plugin'; ?>
	</span>
</div>
<?php
if ( $message ) :
	?>
	<div class="gt-notice gt-notice-<?php echo esc_attr( $message_type ); ?> gt-animate-in">✓ <?php echo esc_html( $message ); ?></div><?php endif; ?>

<?php if ( ! $is_pro ) : ?>
<div class="gt-pro-gate gt-animate-in">
	<span class="gt-pro-gate-icon">💱</span>
	<h2>PRO License Required</h2>
	<p>Multi-Currency support ensures BOGO threshold rules fire correctly in every currency your store operates in — with per-currency caps, minimums, and rate overrides.</p>
	<div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px;max-width:480px;margin:24px auto 0">
		<?php foreach ( array( 'Per-currency threshold overrides', 'Discount caps per currency', 'Cart minimum overrides', 'Compatible with WPML, Aelia, WooMultiCurrency' ) as $f ) : ?>
		<div style="display:flex;align-items:flex-start;gap:8px;text-align:left"><span style="color:#e10000;font-weight:700">—</span><span style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html( $f ); ?></span></div>
		<?php endforeach; ?>
	</div>
	<div style="margin-top:24px;display:flex;justify-content:center;gap:12px">
		<a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">Purchase PRO — $499/yr</a>
	</div>
</div>
<?php else : ?>

<!-- METRICS -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:20px">
	<div class="gt-metric" style="--gt-metric-c:#e10000">
		<span class="gt-metric-icon">💱</span>
		<div class="gt-metric-label">Base Currency</div>
		<div class="gt-metric-value"><?php echo esc_html( $base_curr ); ?></div>
		<div class="gt-metric-trend">WooCommerce store currency</div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#22c55e">
		<span class="gt-metric-icon">✅</span>
		<div class="gt-metric-label">Active Overrides</div>
		<div class="gt-metric-value"><?php echo esc_html( $enabled_count ); ?></div>
		<div class="gt-metric-trend">Currencies configured</div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#3b82f6">
		<span class="gt-metric-icon">🔌</span>
		<div class="gt-metric-label">Plugin Status</div>
		<div class="gt-metric-value" style="font-size:16px"><?php echo esc_html( $has_currency ) ? 'Detected' : 'Manual'; ?></div>
		<div class="gt-metric-trend"><?php echo esc_html( $has_wpml ) ? 'WPML' : ( $has_aelia ? 'Aelia' : ( $has_wmc ? 'WooMultiCurrency' : ( $has_curcy ? 'Curcy' : 'No plugin — manual mode' ) ) ); ?></div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#8b5cf6">
		<span class="gt-metric-icon">🌍</span>
		<div class="gt-metric-label">Available Currencies</div>
		<div class="gt-metric-value"><?php echo esc_html( count( $all_currencies ) ); ?></div>
		<div class="gt-metric-trend">Configurable</div>
	</div>
</div>

<!-- PLUGIN DETECTION -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">🔌 Currency Plugin Detection</h2></div>
	<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px">
		<?php
		foreach ( array(
			array( 'WPML WooCommerce Multilingual', $has_wpml, 'Full switching' ),
			array( 'Aelia Currency Switcher', $has_aelia, 'Full switching' ),
			array( 'WooMultiCurrency', $has_wmc, 'Full switching' ),
			array( 'Curcy — Multi Currency', $has_curcy, 'Full switching' ),
		) as $p ) :
			?>
		<div style="padding:14px;border-radius:10px;border:1px solid <?php echo esc_html( $p[1] ) ? 'rgba(34,197,94,0.3)' : 'var(--gt-border)'; ?>;background:<?php echo esc_html( $p[1] ) ? 'rgba(34,197,94,0.04)' : 'rgba(255,255,255,0.01)'; ?>">
			<div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:4px"><?php echo esc_html( $p[0] ); ?></div>
			<div style="font-size:13px;color:<?php echo esc_html( $p[1] ) ? '#86efac' : '#94a3b8'; ?>"><?php echo esc_html( $p[1] ) ? '✓ Active' : '○ Not Found'; ?></div>
		</div>
		<?php endforeach; ?>
	</div>
	<?php if ( ! $has_currency ) : ?>
	<div style="margin-top:12px;padding:12px 16px;background:rgba(59,130,246,0.06);border-radius:8px;font-size:13px;color:var(--gt-soft);line-height:1.6">
		ℹ️ No currency switcher plugin detected. You can still manually configure per-currency thresholds below — they will apply when WooCommerce processes orders in those currencies via your payment gateway.
	</div>
	<?php endif; ?>
</div>

<!-- GLOBAL SETTINGS -->
<form method="post" action="">
	<?php wp_nonce_field( 'gtbogo_currency', 'gtbogo_cur_nonce' ); ?>

<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">⚙️ Global Currency Settings</h2></div>
	<div class="gt-setting-row">
		<div>
			<div class="gt-setting-label">Price Rounding Mode</div>
			<div class="gt-setting-desc">How converted threshold values are rounded. "Psychological" rounds to nearest .99 (e.g. $49.99). "Clean" rounds to nearest whole number.</div>
		</div>
		<select name="currency_rounding" class="gt-select" style="width:200px">
			<option value="none"          <?php selected( $rounding, 'none' ); ?>>No Rounding</option>
			<option value="round"         <?php selected( $rounding, 'round' ); ?>>Round to Whole Number</option>
			<option value="psychological" <?php selected( $rounding, 'psychological' ); ?>>Psychological (.99)</option>
			<option value="floor"         <?php selected( $rounding, 'floor' ); ?>>Floor (always round down)</option>
		</select>
	</div>
	<div class="gt-setting-row">
		<div>
			<div class="gt-setting-label">Fallback Behaviour</div>
			<div class="gt-setting-desc">What happens for currencies without an override configured.</div>
		</div>
		<select name="currency_fallback" class="gt-select" style="width:200px">
			<option value="base"     <?php selected( $fallback_mode, 'base' ); ?>>Use Base Currency Threshold</option>
			<option value="disable"  <?php selected( $fallback_mode, 'disable' ); ?>>Disable BOGO for Unconfigured Currencies</option>
			<option value="convert"  <?php selected( $fallback_mode, 'convert' ); ?>>Auto-Convert from Base Rate</option>
		</select>
	</div>
	<div class="gt-setting-row" style="border:none">
		<div>
			<div class="gt-setting-label">Auto-Convert Thresholds</div>
			<div class="gt-setting-desc">Automatically calculate threshold overrides using live exchange rates from WooCommerce's currency conversion. Overrides your manual values when enabled.</div>
		</div>
		<label class="gt-toggle"><input type="checkbox" name="currency_auto_rate" value="1" <?php checked( $auto_rate ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
</div>

<!-- CURRENCY OVERRIDE TABLE -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">💱 Per-Currency Overrides</h2>
		<span class="gt-text-soft" style="font-size:13px">Base: <strong style="color:var(--gt-white)"><?php echo esc_html( $base_curr ); ?></strong> · <?php echo esc_html( $enabled_count ); ?> active override<?php echo $enabled_count !== 1 ? 's' : ''; ?></span>
	</div>

	<div style="margin-bottom:12px">
		<input type="text" id="curr-search" class="gt-input" placeholder="Search currencies..." style="max-width:300px"
				oninput="document.querySelectorAll('.gt-curr-row').forEach(r=>r.style.display=r.dataset.name.toLowerCase().includes(this.value.toLowerCase())||r.dataset.code.toLowerCase().includes(this.value.toLowerCase())?'':'none')">
	</div>

	<div style="overflow-x:auto">
		<table class="gt-table">
			<thead>
				<tr>
					<th>Currency</th>
					<th>Enable</th>
					<th>BOGO Threshold Override</th>
					<th>Min Cart Total</th>
					<th>Discount Cap</th>
					<th>Rate Override</th>
					<th>Note</th>
				</tr>
			</thead>
			<tbody>
			<?php
			foreach ( $all_currencies as $code => $name ) :
				if ( $code === $base_curr ) {
					continue;
				}
				$ov         = $overrides[ $code ] ?? array(
					'enabled'       => false,
					'threshold'     => 0,
					'min_cart'      => 0,
					'discount_cap'  => 0,
					'rate_override' => 0,
					'note'          => '',
				);
				$is_enabled = ! empty( $ov['enabled'] );
				?>
			<tr class="gt-curr-row" data-name="<?php echo esc_attr( strtolower( $name ) ); ?>" data-code="<?php echo esc_attr( strtolower( $code ) ); ?>"
				style="opacity:<?php echo esc_html( $is_enabled ) ? '1' : '0.5'; ?>;transition:opacity 0.2s">
				<td>
					<div style="font-weight:700;color:var(--gt-white);font-family:'DM Mono',monospace;font-size:13px"><?php echo esc_html( $code ); ?></div>
					<div style="font-size:13px;color:var(--gt-subtle)"><?php echo esc_html( $name ); ?></div>
				</td>
				<td style="text-align:center">
					<label class="gt-toggle">
						<input type="checkbox" name="currencies[<?php echo esc_attr( $code ); ?>][enabled]" value="1"
								<?php checked( $is_enabled ); ?>
								onchange="this.closest('tr').style.opacity=this.checked?'1':'0.5'">
						<span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
					</label>
				</td>
				<td>
					<div style="display:flex;align-items:center;gap:6px">
						<span style="font-size:13px;color:var(--gt-subtle)"><?php echo esc_html( $code ); ?></span>
						<input type="number" name="currencies[<?php echo esc_attr( $code ); ?>][threshold]"
								class="gt-input" style="width:110px" min="0" step="0.01"
								value="<?php echo esc_attr( $ov['threshold'] ?? 0 ); ?>" placeholder="0.00" id="gtbogo_0_00" aria-label="0.00">
					</div>
					<div style="font-size:13px;color:var(--gt-subtle);margin-top:3px">Min cart for BOGO to fire</div>
				</td>
				<td>
					<input type="number" name="currencies[<?php echo esc_attr( $code ); ?>][min_cart]"
							class="gt-input" style="width:100px" min="0" step="0.01"
							value="<?php echo esc_attr( $ov['min_cart'] ?? 0 ); ?>" placeholder="0.00" id="gtbogo_0_00" aria-label="0.00">
					<div style="font-size:13px;color:var(--gt-subtle);margin-top:3px">Absolute cart floor</div>
				</td>
				<td>
					<input type="number" name="currencies[<?php echo esc_attr( $code ); ?>][discount_cap]"
							class="gt-input" style="width:100px" min="0" step="0.01"
							value="<?php echo esc_attr( $ov['discount_cap'] ?? 0 ); ?>" placeholder="No cap" id="gtbogo_no_cap" aria-label="No cap">
					<div style="font-size:13px;color:var(--gt-subtle);margin-top:3px">Max discount in this currency</div>
				</td>
				<td>
					<input type="number" name="currencies[<?php echo esc_attr( $code ); ?>][rate_override]"
							class="gt-input" style="width:100px" min="0" step="0.0001"
							value="<?php echo esc_attr( $ov['rate_override'] ?? 0 ); ?>" placeholder="Auto" id="gtbogo_auto" aria-label="Auto">
					<div style="font-size:13px;color:var(--gt-subtle);margin-top:3px">1 <?php echo esc_html( $base_curr ); ?> = ? <?php echo esc_html( $code ); ?></div>
				</td>
				<td>
					<input type="text" name="currencies[<?php echo esc_attr( $code ); ?>][note]"
							class="gt-input" style="width:130px"
							value="<?php echo esc_attr( $ov['note'] ?? '' ); ?>" placeholder="Internal note" id="gtbogo_internal_note" aria-label="Internal note">
				</td>
			</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
	</div>

	<div style="margin-top:20px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px">
		<div class="gt-text-soft" style="font-size:13px">
			Threshold overrides apply to cart-value BOGO rules. Percentage-discount rules are currency-agnostic. Discount caps prevent runaway discounts in high-exchange-rate currencies.
		</div>
		<button type="submit" name="gtbogo_save_currency" class="gt-btn gt-btn-primary" style="padding:12px 32px">💾 Save Currency Settings</button>
	</div>
</div>
</form>

<!-- FIELD GUIDE -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">📖 Field Reference</h2></div>
	<div style="overflow-x:auto">
		<table class="gt-table">
			<thead><tr><th>Field</th><th>What It Does</th><th>Example</th></tr></thead>
			<tbody>
				<?php
				foreach ( array(
					array( 'BOGO Threshold Override', 'The minimum cart value in this currency required to trigger a cart-value BOGO rule. Overrides the base currency threshold.', 'EUR 45 instead of USD 50' ),
					array( 'Min Cart Total', 'An absolute floor — the cart must reach this value in the local currency before any BOGO rule can fire. Set to 0 to disable.', 'GBP 20 minimum for all rules' ),
					array( 'Discount Cap', 'The maximum discount value in this currency. Prevents outsized discounts caused by favourable exchange rates.', 'JPY 2,000 max discount' ),
					array( 'Rate Override', 'Manual exchange rate for threshold conversion. Leave at 0 to use WooCommerce\'s built-in rate. Use this for fixed-rate markets.', '1 USD = 0.92 EUR' ),
					array( 'Note', 'Internal memo visible only in this admin panel. Useful for documenting why a specific override was set.', 'EU compliance — reduced threshold' ),
				) as $row ) :
					?>
				<tr>
					<td style="font-weight:700;color:var(--gt-white);white-space:nowrap"><?php echo esc_html( $row[0] ); ?></td>
					<td style="color:var(--gt-soft);font-size:13px"><?php echo esc_html( $row[1] ); ?></td>
					<td style="font-family:'DM Mono',monospace;font-size:13px;color:var(--gt-subtle)"><?php echo esc_html( $row[2] ); ?></td>
				</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
	</div>
</div>

<!-- GUIDANCE -->
<div class="gt-card gt-animate-in" style="background:linear-gradient(135deg,rgba(59,130,246,0.06),rgba(7,12,28,0));border-color:rgba(59,130,246,0.15)">
	<div class="gt-card-header"><h2 class="gt-card-title">🧠 Multi-Currency Strategy Guide</h2></div>
	<div class="gt-feature-grid gt-feature-grid--2col">
		<div>
			<div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Purchasing Power Parity</div>
			<div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Do not use flat exchange rates for thresholds. A $50 threshold is trivially easy for UK customers paying in GBP. Set GBP thresholds 10–15% below USD equivalent to keep conversion rates consistent across markets.</div>
		</div>
		<div>
			<div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">JPY and KRW — No Decimals</div>
			<div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Japanese Yen and Korean Won have no decimal places. Set Price Rounding to "Floor" for these currencies and use whole-number thresholds (e.g. JPY 6,000 not JPY 6,000.00) to avoid display issues in WooCommerce checkout.</div>
		</div>
		<div>
			<div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Discount Caps for Exchange Rate Protection</div>
			<div style="font-size:13px;color:var(--gt-soft);line-height:1.7">If you sell in currencies that fluctuate significantly against your base currency, set a Discount Cap. A 50% BOGO on a $100 item becomes a much larger effective discount if the exchange rate moves 20% in the customer's favour. Caps protect your margins automatically.</div>
		</div>
		<div>
			<div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Testing Currency Overrides</div>
			<div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Always test threshold rules in your secondary currencies using WooCommerce's currency switcher before going live. Place a test order in each configured currency, verify the BOGO fires at the correct threshold, and check the discount cap is applied correctly. Log the test in the Audit Log for compliance records.</div>
		</div>
	</div>
</div>

<?php endif; ?>
<script>
(function(){
	// Live exchange rate refresh
	var refreshBtn = document.getElementById('gt-mc-refresh-rates');
	if (refreshBtn) {
		refreshBtn.addEventListener('click', function() {
			this.textContent = 'Refreshing...';
			this.disabled = true;
			var fd = new FormData();
			fd.append('action', 'gtbogo_refresh_exchange_rates');
			fd.append('nonce', gtBogoAdmin.nonce);
			fetch(ajaxurl, {method:'POST', body:fd, credentials:'same-origin'})
				.then(r => r.json())
				.then(d => {
					if (d.success) {
						// Update rate displays
						if (d.data && d.data.rates) {
							Object.keys(d.data.rates).forEach(function(cc) {
								var el = document.getElementById('gt-rate-' + cc);
								if (el) el.textContent = d.data.rates[cc];
							});
						}
						refreshBtn.textContent = '✓ Rates Updated';
					} else {
						refreshBtn.textContent = '✕ Refresh Failed';
					}
					refreshBtn.disabled = false;
					setTimeout(() => { refreshBtn.textContent = '↻ Refresh Rates'; }, 3000);
				}).catch(() => {
					refreshBtn.textContent = '✕ Error'; refreshBtn.disabled = false;
				});
		});
	}
})();
</script>

<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>