<?php
/**
 * File Path: includes/admin/tabs/general/class-mbs-tab-general-currency.php
 *
 * General Tab — Currency & Timezone Field Group
 *
 * Renders the Currency and Timezone fields inside the Regional & Currency
 * Settings card. The parent (MBS_Tab_General) owns the surrounding
 * .mbs-settings-card wrapper; this class outputs a .mbs-settings-field-grid
 * containing two .mbs-settings-field-cell blocks arranged side-by-side on
 * wide screens.
 *
 * Option keys read:
 *   mbs_setting_general_currency        — canonical key (also read by Formatting tab)
 *   mbs_setting_general_timezone
 *   mbs_setting_general_default_language — SET-01: moved here from MBS_Tab_General_Display
 *
 * Form field naming convention for the Currency dropdown + custom-input pair:
 *   Dropdown:     id=mbs_general_currency_select   name=mbs_general_currency
 *   Custom input: id=mbs_general_currency_custom   name=mbs_general_currency_custom
 *
 * The two inputs carry distinct names so PHP's $_POST never has a duplicate
 * key. The save handler coalesces: if the dropdown value is 'other', it
 * reads the custom input; otherwise it reads the dropdown.
 *
 * The dropdown/custom toggle script is in:
 *   assets/js/adminjs/child-admin-general-currency.js
 * Enqueued by MBS_Tab_General::enqueue() on tab === 'general'.
 *
 * Phase 4b (2026-04-19):
 *   · Locale field removed per client CR — the mbs_setting_general_locale
 *     option has no runtime consumers (dead-wire). The saved option value is
 *     preserved in wp_options (non-destructive deprecation) pending a future
 *     cleanup migration (logged as PLG-054 — LOW).
 *   · Method renamed render_rows() → render_fields() to reflect that output
 *     is no longer <tr> rows for an outer <table>, but a self-contained grid.
 *   · Timezone default now reads wp_timezone_string() when no MBS value is
 *     saved, falling back to 'UTC' only as last resort. Aligns with client
 *     directive "never hard-code UTC" (2026-04-19).
 *   · Timezone helper text flagged as "feature in development" — the option
 *     is saved but has no consumer yet. Logged as PLG-052 (LOW) with
 *     F-008 (locale-filtered timezone options) and F-009 (auto-populate from
 *     WordPress) as future enhancements.
 *   · Layout changed from <tr> rows to two .mbs-settings-field-cell blocks in
 *     a 2-column grid (stacks to 1 column below ~900px).
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Admin/Tabs/General
 * @since      1.0.0
 */

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

class MBS_Tab_General_Currency { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	// -------------------------------------------------------------------------
	// Instance helpers — called by render_fields()
	// -------------------------------------------------------------------------

	/**
	 * Get the IANA region prefix matching the current WordPress locale.
	 *
	 * @return string Region prefix (e.g. 'Europe/') or '' when not recognized.
	 */
	private function get_locale_region_prefix(): string {
		$locale = function_exists( 'get_locale' ) ? get_locale() : '';
		return MBS_Timezone_Helper::locale_to_region_prefix( $locale );
	}

	/**
	 * Render the Currency + Timezone fields.
	 *
	 * Outputs a .mbs-settings-field-grid wrapper with two cells. No outer
	 * table tags.
	 *
	 * F-009: Timezone cell includes a "Use WP Timezone" button that JS uses
	 * to one-click-populate the dropdown from the WordPress timezone setting.
	 *
	 * F-008: Timezone <select> renders locale-matched zones first in a named
	 * <optgroup>, followed by remaining zones in "All Other Timezones". Falls
	 * back to a flat list when no region prefix is detected.
	 *
	 * @return void
	 */
	public function render_fields(): void {
		$current_currency = get_option( 'mbs_setting_general_currency', 'USD' );
		$current_timezone = MBS_Timezone_Helper::resolve_current_timezone();
		$region_prefix    = $this->get_locale_region_prefix();

		// Format: 'symbol (CODE) Name' — keeps symbol, code, and name scannable in the dropdown.
		// Must stay in sync with the $currency_symbols table in MBS_Tab_Formatting::get_currency_symbol().
		$common_currencies = array(

			// ── Dollar-sign currencies ────────────────────────────────────────
			'USD' => '$ (USD) US Dollar',
			'CAD' => '$ (CAD) Canadian Dollar',
			'AUD' => '$ (AUD) Australian Dollar',
			'HKD' => '$ (HKD) Hong Kong Dollar',
			'MXN' => '$ (MXN) Mexican Peso',

			// ── Euro & Sterling ───────────────────────────────────────────────
			'EUR' => '€ (EUR) Euro',
			'GBP' => '£ (GBP) British Pound',

			// ── Asian major currencies ────────────────────────────────────────
			'JPY' => '¥ (JPY) Japanese Yen',
			'CNY' => '¥ (CNY) Chinese Yuan',
			'KRW' => '₩ (KRW) South Korean Won',
			'INR' => '₹ (INR) Indian Rupee',
			'HUF' => 'Ft (HUF) Hungarian Forint',

			// ── European regional currencies ──────────────────────────────────
			'CHF' => 'CHF (CHF) Swiss Franc',
			'SEK' => 'kr (SEK) Swedish Krona',
			'NOK' => 'kr (NOK) Norwegian Krone',
			'DKK' => 'kr (DKK) Danish Krone',
			'PLN' => 'zł (PLN) Polish Zloty',
			'CZK' => 'Kč (CZK) Czech Koruna',
			'UAH' => '₴ (UAH) Ukrainian Hryvnia',
			'TRY' => '₺ (TRY) Turkish Lira',
			'RUB' => '₽ (RUB) Russian Ruble',

			// ── Americas ──────────────────────────────────────────────────────
			'BRL' => 'R$ (BRL) Brazilian Real',
			'CRC' => '₡ (CRC) Costa Rican Colon',
			'PYG' => '₲ (PYG) Paraguayan Guarani',

			// ── Africa & Middle East ──────────────────────────────────────────
			'ZAR' => 'R (ZAR) South African Rand',
			'NGN' => '₦ (NGN) Nigerian Naira',
			'ILS' => '₪ (ILS) Israeli Shekel',
			'SAR' => '﷼ (SAR) Saudi Riyal',
			'IRR' => '﷼ (IRR) Iranian Rial',

			// ── South & Southeast Asia ────────────────────────────────────────
			'IDR' => 'Rp (IDR) Indonesian Rupiah',
			'MYR' => 'RM (MYR) Malaysian Ringgit',
			'THB' => '฿ (THB) Thai Baht',
			'VND' => '₫ (VND) Vietnamese Dong',
			'PHP' => '₱ (PHP) Philippine Peso',
			'KZT' => '₸ (KZT) Kazakhstani Tenge',
			'LAK' => '₭ (LAK) Lao Kip',

			// ── Cryptocurrencies ──────────────────────────────────────────────
			// SALES DIFFERENTIATOR: Native cryptocurrency support is a competitive
			// advantage over most book-catalog plugins (e.g. MyBookTable, WP Books
			// Gallery) which support fiat only. Crypto-native author communities
			// (Web3, NFT-linked books, direct reader-pay models) are an underserved
			// segment. Flag for competitive analysis: include in feature comparison
			// matrix and marketing copy. — Note to competitive analysis consultant:
			// verify whether any direct competitors have added crypto support since
			// this note was written and update the analysis accordingly.
			'BTC'  => '₿ (BTC) Bitcoin',
			'ETH'  => 'Ξ (ETH) Ethereum',
			'LTC'  => 'Ł (LTC) Litecoin',
			'DOGE' => 'Ð (DOGE) Dogecoin',
		);

		$is_custom = ! array_key_exists( $current_currency, $common_currencies );
		?>
		<div class="mbs-settings-field-grid">

			<?php /* ── Currency ──────────────────────────────────────────── */ ?>
			<div class="mbs-settings-field-cell">
				<label for="mbs_general_currency_select"><?php esc_html_e( 'Default Currency', 'my-book-showroom' ); ?></label>
				<select id="mbs_general_currency_select" name="mbs_general_currency" class="regular-text">
					<?php foreach ( $common_currencies as $code => $label ) : ?>
						<option value="<?php echo esc_attr( $code ); ?>" <?php selected( $current_currency, $code ); ?>>
							<?php echo esc_html( $label ); ?>
						</option>
					<?php endforeach; ?>
					<option value="other" <?php selected( $is_custom, true ); ?>><?php esc_html_e( 'Other / Custom', 'my-book-showroom' ); ?></option>
				</select>
				<input type="text"
				       id="mbs_general_currency_custom"
				       name="mbs_general_currency_custom"
				       value="<?php echo esc_attr( $is_custom ? $current_currency : '' ); ?>"
				       class="regular-text"
				       placeholder="<?php esc_attr_e( 'ISO currency code', 'my-book-showroom' ); ?>"
				       style="margin-top: 8px; display: <?php echo esc_attr( $is_custom ? 'block' : 'none' ); ?>;">
				<p class="description">
					<?php esc_html_e( 'Select from the list, or choose Other to enter a custom ISO currency code.', 'my-book-showroom' ); ?>
				</p>

				<?php /* SET-01: Default Book Language — same column as Default Currency, matching UX pattern. */ ?>
				<label for="mbs_general_default_language" style="margin-top: 16px; display: block;"><?php esc_html_e( 'Default Book Language', 'my-book-showroom' ); ?></label>
				<select id="mbs_general_default_language" name="mbs_general_default_language" class="regular-text">
					<?php
					$saved_lang = get_option( 'mbs_setting_general_default_language', 'en' );
					$languages  = array(
						'af'   => __( 'Afrikaans', 'my-book-showroom' ),
						'ar'   => __( 'Arabic', 'my-book-showroom' ),
						'zh'   => __( 'Chinese (Simplified)', 'my-book-showroom' ),
						'zh-tw'=> __( 'Chinese (Traditional)', 'my-book-showroom' ),
						'cs'   => __( 'Czech', 'my-book-showroom' ),
						'da'   => __( 'Danish', 'my-book-showroom' ),
						'nl'   => __( 'Dutch', 'my-book-showroom' ),
						'en'   => __( 'English', 'my-book-showroom' ),
						'fi'   => __( 'Finnish', 'my-book-showroom' ),
						'fr'   => __( 'French', 'my-book-showroom' ),
						'de'   => __( 'German', 'my-book-showroom' ),
						'el'   => __( 'Greek', 'my-book-showroom' ),
						'he'   => __( 'Hebrew', 'my-book-showroom' ),
						'hi'   => __( 'Hindi', 'my-book-showroom' ),
						'hu'   => __( 'Hungarian', 'my-book-showroom' ),
						'id'   => __( 'Indonesian', 'my-book-showroom' ),
						'it'   => __( 'Italian', 'my-book-showroom' ),
						'ja'   => __( 'Japanese', 'my-book-showroom' ),
						'ko'   => __( 'Korean', 'my-book-showroom' ),
						'ms'   => __( 'Malay', 'my-book-showroom' ),
						'no'   => __( 'Norwegian', 'my-book-showroom' ),
						'fa'   => __( 'Persian (Farsi)', 'my-book-showroom' ),
						'pl'   => __( 'Polish', 'my-book-showroom' ),
						'pt'   => __( 'Portuguese', 'my-book-showroom' ),
						'pt-br'=> __( 'Portuguese (Brazil)', 'my-book-showroom' ),
						'ro'   => __( 'Romanian', 'my-book-showroom' ),
						'ru'   => __( 'Russian', 'my-book-showroom' ),
						'sk'   => __( 'Slovak', 'my-book-showroom' ),
						'es'   => __( 'Spanish', 'my-book-showroom' ),
						'sv'   => __( 'Swedish', 'my-book-showroom' ),
						'th'   => __( 'Thai', 'my-book-showroom' ),
						'tr'   => __( 'Turkish', 'my-book-showroom' ),
						'uk'   => __( 'Ukrainian', 'my-book-showroom' ),
						'ur'   => __( 'Urdu', 'my-book-showroom' ),
						'vi'   => __( 'Vietnamese', 'my-book-showroom' ),
					);
					foreach ( $languages as $code => $lang_label ) :
						?>
						<option value="<?php echo esc_attr( $code ); ?>" <?php selected( $saved_lang, $code ); ?>>
							<?php echo esc_html( $lang_label ); ?>
						</option>
					<?php endforeach; ?>
				</select>
				<p class="description"><?php esc_html_e( 'Applied to new books when no language is explicitly selected in the book editor.', 'my-book-showroom' ); ?></p>
			</div>

			<?php /* ── Timezone ──────────────────────────────────────────── */ ?>
			<div class="mbs-settings-field-cell">
				<label for="mbs_general_timezone"><?php esc_html_e( 'Timezone', 'my-book-showroom' ); ?></label>
				<select id="mbs_general_timezone" name="mbs_general_timezone" class="regular-text">
					<?php
					$all_zones = timezone_identifiers_list();
					if ( '' !== $region_prefix ) :
						$locale_zones = array_values( array_filter( $all_zones, fn( $tz ) => str_starts_with( $tz, $region_prefix ) ) );
						$other_zones  = array_values( array_filter( $all_zones, fn( $tz ) => ! str_starts_with( $tz, $region_prefix ) ) );
						$region_label = MBS_Timezone_Helper::region_prefix_to_label( $region_prefix );
					?>
						<optgroup label="<?php echo esc_attr( $region_label ); ?>">
							<?php foreach ( $locale_zones as $tz ) : ?>
								<option value="<?php echo esc_attr( $tz ); ?>" <?php selected( $current_timezone, $tz ); ?>>
									<?php echo esc_html( $tz ); ?>
								</option>
							<?php endforeach; ?>
						</optgroup>
						<optgroup label="<?php esc_attr_e( 'All Other Timezones', 'my-book-showroom' ); ?>">
							<?php foreach ( $other_zones as $tz ) : ?>
								<option value="<?php echo esc_attr( $tz ); ?>" <?php selected( $current_timezone, $tz ); ?>>
									<?php echo esc_html( $tz ); ?>
								</option>
							<?php endforeach; ?>
						</optgroup>
					<?php else : ?>
						<?php foreach ( $all_zones as $tz ) : ?>
							<option value="<?php echo esc_attr( $tz ); ?>" <?php selected( $current_timezone, $tz ); ?>>
								<?php echo esc_html( $tz ); ?>
							</option>
						<?php endforeach; ?>
					<?php endif; ?>
				</select>
				<p class="description">
					<?php esc_html_e( 'Used to display publication dates and scheduled release dates in your local time zone.', 'my-book-showroom' ); ?>
				</p>
				<button type="button"
				        class="button button-secondary mbs-use-wp-timezone"
				        style="margin-top: 6px;"
				        data-done-label="<?php echo esc_attr( __( 'Applied', 'my-book-showroom' ) ); ?>"
				        data-tz="<?php echo esc_attr( MBS_Timezone_Helper::get_wp_iana_timezone() ); ?>">
					<?php esc_html_e( 'Use WP Timezone', 'my-book-showroom' ); ?>
				</button>
			</div>

		</div>
		<?php
	}
}
