<?php
/**
 * Marketplace IDs Utility
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes/common/utils
 * @author     miniOrange
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Utils;

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

/**
 * Class Marketplace_IDs
 *
 * Utility class for managing marketplace IDs.
 */
class Marketplace_IDs {

	/**
	 * Map of marketplace IDs to seller central URLs.
	 *
	 * @var array
	 */
	private static $seller_central_url_map = array(
		'ATVPDKIKX0DER'  => 'https://sellercentral.amazon.com',
		'A2EUQ1WTGCTBG2' => 'https://sellercentral.amazon.ca',
		'A1AM78C64UM0Y8' => 'https://sellercentral.amazon.com.mx',
		'A2Q3Y263D00KWC' => 'https://sellercentral.amazon.com.br',
		'A28R8C7NBKEWEA' => 'https://sellercentral.amazon.ie',
		'A1RKKUPIHCS9HS' => 'https://sellercentral-europe.amazon.com',
		'A1F83G8C2ARO7P' => 'https://sellercentral-europe.amazon.com',
		'A13V1IB3VIYZZH' => 'https://sellercentral-europe.amazon.com',
		'AMEN7PMS3EDWL'  => 'https://sellercentral.amazon.com.be',
		'A1805IZSGTT6HS' => 'https://sellercentral.amazon.nl',
		'A1PA6795UKMFR9' => 'https://sellercentral-europe.amazon.com',
		'APJ6JRA9NG5V4'  => 'https://sellercentral-europe.amazon.com',
		'A2NODRKZP88ZB9' => 'https://sellercentral.amazon.se',
		'AE08WJ6YKNBMC'  => 'https://sellercentral.amazon.co.za',
		'A1C3SOZRARQ6R3' => 'https://sellercentral.amazon.pl',
		'ARBP9OOSHTCHU'  => 'https://sellercentral.amazon.eg',
		'A33AVAJ2PDY3EV' => 'https://sellercentral.amazon.com.tr',
		'A17E79C6D8DWNP' => 'https://sellercentral.amazon.sa',
		'A2VIGQ35RCS4UG' => 'https://sellercentral.amazon.ae',
		'A21TJRUUN4KGV'  => 'https://sellercentral.amazon.in',
		'A19VAU5U5O7RUS' => 'https://sellercentral.amazon.sg',
		'A39IBJ37TRP1C6' => 'https://sellercentral.amazon.com.au',
		'A1VC38T7YXB528' => 'https://sellercentral.amazon.co.jp',
	);

	/**
	 * Map of country codes to marketplace IDs.
	 *
	 * @var array
	 */
	private static $marketplace_id_map = array(
		'us' => 'ATVPDKIKX0DER',
		'ca' => 'A2EUQ1WTGCTBG2',
		'mx' => 'A1AM78C64UM0Y8',
		'br' => 'A2Q3Y263D00KWC',
		'uk' => 'A1F83G8C2ARO7P',
		'ie' => 'A28R8C7NBKEWEA',
		'de' => 'A1PA6795UKMFR9',
		'fr' => 'A13V1IB3VIYZZH',
		'it' => 'APJ6JRA9NG5V4',
		'es' => 'A1RKKUPIHCS9HS',
		'nl' => 'A1805IZSGTT6HS',
		'se' => 'A2NODRKZP88ZB9',
		'pl' => 'A1C3SOZRARQ6R3',
		'be' => 'AMEN7PMS3EDWL',
		'jp' => 'A1VC38T7YXB528',
		'au' => 'A39IBJ37TRP1C6',
		'in' => 'A21TJRUUN4KGV',
		'sg' => 'A19VAU5U5O7RUS',
		'ae' => 'A2VIGQ35RCS4UG',
		'sa' => 'A17E79C6D8DWNP',
		'tr' => 'A33AVAJ2PDY3EV',
		'eg' => 'ARBP9OOSHTCHU',
		'za' => 'AE08WJ6YKNBMC',
	);

	/**
	 * Map of marketplace IDs to country codes.
	 *
	 * @var array
	 */
	private static $country_code_map = array(
		'ATVPDKIKX0DER'  => 'us',
		'A2EUQ1WTGCTBG2' => 'ca',
		'A1AM78C64UM0Y8' => 'mx',
		'A2Q3Y263D00KWC' => 'br',
		'A1F83G8C2ARO7P' => 'uk',
		'A28R8C7NBKEWEA' => 'ie',
		'A1PA6795UKMFR9' => 'de',
		'A13V1IB3VIYZZH' => 'fr',
		'APJ6JRA9NG5V4'  => 'it',
		'A1RKKUPIHCS9HS' => 'es',
		'A1805IZSGTT6HS' => 'nl',
		'A2NODRKZP88ZB9' => 'se',
		'A1C3SOZRARQ6R3' => 'pl',
		'AMEN7PMS3EDWL'  => 'be',
		'A1VC38T7YXB528' => 'jp',
		'A39IBJ37TRP1C6' => 'au',
		'A21TJRUUN4KGV'  => 'in',
		'A19VAU5U5O7RUS' => 'sg',
		'A2VIGQ35RCS4UG' => 'ae',
		'A17E79C6D8DWNP' => 'sa',
		'A33AVAJ2PDY3EV' => 'tr',
		'ARBP9OOSHTCHU'  => 'eg',
		'AE08WJ6YKNBMC'  => 'za',
	);


	/**
	 * Get marketplace ID from country code.
	 *
	 * @param string $country_code Two-letter country code (e.g., 'us', 'ca').
	 * @return string|null Marketplace ID or null if not found.
	 */
	public static function get_marketplace_id( string $country_code ): ?string {
		$country_code = strtolower( $country_code );
		return isset( self::$marketplace_id_map[ $country_code ] ) ? self::$marketplace_id_map[ $country_code ] : null;
	}

	/**
	 * Get country code from marketplace ID.
	 *
	 * @param string $marketplace_id Amazon marketplace ID.
	 * @return string|null Country code or null if not found.
	 */
	public static function get_country_code( string $marketplace_id ): ?string {
		return isset( self::$country_code_map[ $marketplace_id ] ) ? self::$country_code_map[ $marketplace_id ] : null;
	}

	/**
	 * Check if a string is a marketplace ID.
	 *
	 * @param string $value The string to check.
	 * @return bool True if the string is a marketplace ID, false otherwise.
	 */
	public static function is_marketplace_id( string $value ): bool {
		return isset( self::$country_code_map[ $value ] );
	}

	/**
	 * Map of marketplace IDs to their respective Amazon Selling Partner API base URLs.
	 * Based on official Amazon Selling Partner API documentation.
	 *
	 * @var array
	 */
	private static $api_base_url_map = array(
		// North America region (Canada, US, Mexico, and Brazil marketplaces).
		'A2EUQ1WTGCTBG2' => 'https://sellingpartnerapi-na.amazon.com', // CA.
		'ATVPDKIKX0DER'  => 'https://sellingpartnerapi-na.amazon.com', // US.
		'A1AM78C64UM0Y8' => 'https://sellingpartnerapi-na.amazon.com', // MX.
		'A2Q3Y263D00KWC' => 'https://sellingpartnerapi-na.amazon.com', // BR.

		// Europe region (Spain, UK, France, Belgium, Netherlands, Germany, Italy, Sweden, South Africa, Poland, Saudi Arabia, Egypt, Turkey, United Arab Emirates, and India marketplaces).
		'A1F83G8C2ARO7P' => 'https://sellingpartnerapi-eu.amazon.com', // UK.
		'A1PA6795UKMFR9' => 'https://sellingpartnerapi-eu.amazon.com', // DE.
		'A13V1IB3VIYZZH' => 'https://sellingpartnerapi-eu.amazon.com', // FR.
		'APJ6JRA9NG5V4'  => 'https://sellingpartnerapi-eu.amazon.com', // IT.
		'A1RKKUPIHCS9HS' => 'https://sellingpartnerapi-eu.amazon.com', // ES.
		'A1805IZSGTT6HS' => 'https://sellingpartnerapi-eu.amazon.com', // NL.
		'A2NODRKZP88ZB9' => 'https://sellingpartnerapi-eu.amazon.com', // SE.
		'A1C3SOZRARQ6R3' => 'https://sellingpartnerapi-eu.amazon.com', // PL.
		'AMEN7PMS3EDWL'  => 'https://sellingpartnerapi-eu.amazon.com', // BE.
		'A33AVAJ2PDY3EV' => 'https://sellingpartnerapi-eu.amazon.com', // TR.
		'ARBP9OOSHTCHU'  => 'https://sellingpartnerapi-eu.amazon.com', // EG.
		'A2VIGQ35RCS4UG' => 'https://sellingpartnerapi-eu.amazon.com', // AE.
		'AE08WJ6YKNBMC'  => 'https://sellingpartnerapi-eu.amazon.com', // ZA.
		'A21TJRUUN4KGV'  => 'https://sellingpartnerapi-eu.amazon.com', // IN.
		'A28R8C7NBKEWEA' => 'https://sellingpartnerapi-eu.amazon.com', // IE.

		// Far East region (Singapore, Australia, and Japan marketplaces).
		'A19VAU5U5O7RUS' => 'https://sellingpartnerapi-fe.amazon.com', // SG.
		'A39IBJ37TRP1C6' => 'https://sellingpartnerapi-fe.amazon.com', // AU.
		'A1VC38T7YXB528' => 'https://sellingpartnerapi-fe.amazon.com', // JP.
	);

	/**
	 * Get Amazon Selling Partner API base URL for a marketplace.
	 *
	 * @param string $marketplace_id_or_country Amazon marketplace ID (e.g., 'ATVPDKIKX0DER') or country code (e.g., 'us').
	 * @return string|null Base URL or null if marketplace not found.
	 */
	public static function get_api_base_url( string $marketplace_id_or_country ): ?string {
		// Check if it's a country code first.
		if ( strlen( $marketplace_id_or_country ) === 2 ) {
			$marketplace_id = self::get_marketplace_id( $marketplace_id_or_country );
			if ( null === $marketplace_id ) {
				return null;
			}
		} else {
			$marketplace_id = $marketplace_id_or_country;
		}

		return isset( self::$api_base_url_map[ $marketplace_id ] ) ? self::$api_base_url_map[ $marketplace_id ] : null;
	}

	/**
	 * Get region identifier from marketplace ID.
	 *
	 * @param string $marketplace_id Amazon marketplace ID.
	 * @return string|null 'north-america', 'europe', 'far-east', or null.
	 */
	public static function get_region_by_marketplace_id( string $marketplace_id ): ?string {
		$base_url = self::get_api_base_url( $marketplace_id );

		if ( null === $base_url ) {
			return null;
		}

		if ( strpos( $base_url, 'sellingpartnerapi-na.amazon.com' ) !== false ) {
			return 'north-america';
		} elseif ( strpos( $base_url, 'sellingpartnerapi-eu.amazon.com' ) !== false ) {
			return 'europe';
		} elseif ( strpos( $base_url, 'sellingpartnerapi-fe.amazon.com' ) !== false ) {
			return 'far-east';
		}

		return null;
	}

	/**
	 * Group channels by AWS API region for optimized API calls.
	 *
	 * @deprecated 1.3.0 No longer used since switching to individual marketplace sync.
	 *             Each marketplace now gets its own Action Scheduler job for better
	 *             error isolation and concurrency handling. Amazon's Feeds API doesn't
	 *             properly support multiple marketplace IDs in a single feed request.
	 *
	 * @param array $channels Array of channel data (must include 'region' key).
	 * @return array Grouped: ['north-america' => [channels], 'europe' => [channels], ...].
	 */
	public static function group_channels_by_region( array $channels ): array {
		_deprecated_function( __METHOD__, '1.3.0', 'Individual marketplace sync via Multi_Channel_Sync_Handler' );

		$grouped = array();

		foreach ( $channels as $channel ) {
			$marketplace_id = $channel['region'] ?? '';
			if ( empty( $marketplace_id ) ) {
				continue;
			}

			$region = self::get_region_by_marketplace_id( $marketplace_id );
			if ( null === $region ) {
				continue;
			}

			if ( ! isset( $grouped[ $region ] ) ) {
				$grouped[ $region ] = array();
			}

			$grouped[ $region ][] = $channel;
		}

		return $grouped;
	}

	/**
	 * Get marketplace dropdown options with IDs.
	 *
	 * @return array Array of marketplace options with marketplace IDs as values.
	 */
	public static function get_marketplace_options(): array {
		$options = array(
			'A2EUQ1WTGCTBG2' => esc_html__( 'Canada (CA)', 'multi-channel-for-woocommerce' ),
			'ATVPDKIKX0DER'  => esc_html__( 'United States (US)', 'multi-channel-for-woocommerce' ),
			'A1AM78C64UM0Y8' => esc_html__( 'Mexico (MX)', 'multi-channel-for-woocommerce' ),
			'A2Q3Y263D00KWC' => esc_html__( 'Brazil (BR)', 'multi-channel-for-woocommerce' ),
			'A28R8C7NBKEWEA' => esc_html__( 'Ireland (IE)', 'multi-channel-for-woocommerce' ),
			'A1RKKUPIHCS9HS' => esc_html__( 'Spain (ES)', 'multi-channel-for-woocommerce' ),
			'A1F83G8C2ARO7P' => esc_html__( 'United Kingdom (UK)', 'multi-channel-for-woocommerce' ),
			'A13V1IB3VIYZZH' => esc_html__( 'France (FR)', 'multi-channel-for-woocommerce' ),
			'AMEN7PMS3EDWL'  => esc_html__( 'Belgium (BE)', 'multi-channel-for-woocommerce' ),
			'A1805IZSGTT6HS' => esc_html__( 'Netherlands (NL)', 'multi-channel-for-woocommerce' ),
			'A1PA6795UKMFR9' => esc_html__( 'Germany (DE)', 'multi-channel-for-woocommerce' ),
			'APJ6JRA9NG5V4'  => esc_html__( 'Italy (IT)', 'multi-channel-for-woocommerce' ),
			'A2NODRKZP88ZB9' => esc_html__( 'Sweden (SE)', 'multi-channel-for-woocommerce' ),
			'AE08WJ6YKNBMC'  => esc_html__( 'South Africa (ZA)', 'multi-channel-for-woocommerce' ),
			'A1C3SOZRARQ6R3' => esc_html__( 'Poland (PL)', 'multi-channel-for-woocommerce' ),
			'ARBP9OOSHTCHU'  => esc_html__( 'Egypt (EG)', 'multi-channel-for-woocommerce' ),
			'A33AVAJ2PDY3EV' => esc_html__( 'Turkey (TR)', 'multi-channel-for-woocommerce' ),
			'A17E79C6D8DWNP' => esc_html__( 'Saudi Arabia (SA)', 'multi-channel-for-woocommerce' ),
			'A2VIGQ35RCS4UG' => esc_html__( 'United Arab Emirates (AE)', 'multi-channel-for-woocommerce' ),
			'A21TJRUUN4KGV'  => esc_html__( 'India (IN)', 'multi-channel-for-woocommerce' ),
			'A19VAU5U5O7RUS' => esc_html__( 'Singapore (SG)', 'multi-channel-for-woocommerce' ),
			'A39IBJ37TRP1C6' => esc_html__( 'Australia (AU)', 'multi-channel-for-woocommerce' ),
			'A1VC38T7YXB528' => esc_html__( 'Japan (JP)', 'multi-channel-for-woocommerce' ),
		);

		asort( $options );

		return $options;
	}

	/**
	 * Get seller central URL for a marketplace.
	 *
	 * @param string $marketplace_id Amazon marketplace ID.
	 * @return string|null Seller central URL or null if not found.
	 */
	public static function get_seller_central_url( string $marketplace_id ): ?string {
		return isset( self::$seller_central_url_map[ $marketplace_id ] ) ? self::$seller_central_url_map[ $marketplace_id ] : null;
	}

	/**
	 * Get human-readable country name from an Amazon marketplace ID.
	 *
	 * Uses WooCommerce countries list when available for proper i18n.
	 * Falls back to an internal map, then to the ISO code if unknown.
	 *
	 * @param string $marketplace_id Amazon marketplace ID, e.g. 'A21TJRUUN4KGV'.
	 * @return string|null Country name (e.g. 'India') or null if mapping not possible.
	 */
	public static function get_country_name_by_marketplace_id( string $marketplace_id ): ?string {
		$country_code = self::get_country_code( $marketplace_id );
		if ( null === $country_code ) {
			return null;
		}

		$iso2   = strtoupper( $country_code );
		$wc_iso = ( 'UK' === $iso2 ) ? 'GB' : $iso2; // WooCommerce uses GB instead of UK.

		// Prefer WooCommerce list for i18n-ready country names.
		if ( function_exists( 'WC' ) ) {
			$wc = \WC();
			if ( $wc && isset( $wc->countries ) && method_exists( $wc->countries, 'get_countries' ) ) {
				$countries = $wc->countries->get_countries();
				if ( isset( $countries[ $wc_iso ] ) ) {
					return $countries[ $wc_iso ];
				}
			}
		}

		// Fallback names if WooCommerce list is not available.
		$fallback_names = array(
			'US' => 'United States',
			'CA' => 'Canada',
			'BR' => 'Brazil',
			'MX' => 'Mexico',
			'UK' => 'United Kingdom',
			'GB' => 'United Kingdom',
			'DE' => 'Germany',
			'FR' => 'France',
			'IT' => 'Italy',
			'ES' => 'Spain',
			'NL' => 'Netherlands',
			'SE' => 'Sweden',
			'PL' => 'Poland',
			'BE' => 'Belgium',
			'JP' => 'Japan',
			'AU' => 'Australia',
			'IN' => 'India',
			'SG' => 'Singapore',
			'AE' => 'United Arab Emirates',
			'SA' => 'Saudi Arabia',
			'EG' => 'Egypt',
			'TR' => 'Turkey',
			'ZA' => 'South Africa',
			'IE' => 'Ireland',
		);

		return $fallback_names[ $iso2 ] ?? $iso2;
	}
}
