<?php

namespace Easymailing\App\Core\Provider\Woocommerce\Service;

class PhoneCountryResolver
{
	public static function fromOrder(\WC_Order $order): ?string
	{
		return self::normalizeCountry($order->get_billing_country()) ?: self::singleSellingCountry();
	}

	public static function fromUser(int $userId): ?string
	{
		$country = get_user_meta($userId, 'billing_country', true);
		return self::normalizeCountry($country) ?: self::singleSellingCountry();
	}

	public static function fromCustomerData(array $customerData): ?string
	{
		foreach (['country', 'billing_country'] as $key) {
			if (!empty($customerData[$key])) {
				return self::normalizeCountry($customerData[$key]);
			}
		}

		return self::singleSellingCountry();
	}

	private static function normalizeCountry($country): ?string
	{
		if (!is_string($country) || trim($country) === '') {
			return null;
		}

		return strtoupper(substr(trim($country), 0, 2));
	}

	private static function singleSellingCountry(): ?string
	{
		if (!function_exists('WC') || !WC() || !WC()->countries) {
			return null;
		}

		$countries = array_keys(WC()->countries->get_allowed_countries());
		if (count($countries) !== 1) {
			return null;
		}

		return self::normalizeCountry($countries[0]);
	}
}
