<?php

declare(strict_types=1);

namespace Signocore\Multilanguage\Support;

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

final class LocaleHelper
{
	/**
	 * Get the WordPress locale for a language code.
	 */
	public static function getLocaleForCode(string $langCode): string
	{
		$lang = LanguageHelper::getByCode($langCode);
		return $lang !== null ? $lang['locale'] : $langCode;
	}

	/**
	 * Get the language code from a WordPress locale.
	 */
	public static function getCodeFromLocale(string $locale): string
	{
		$languages = LanguageHelper::getAllLanguages();

		foreach ($languages as $lang) {
			if ($lang['locale'] === $locale) {
				return $lang['code'];
			}
		}

		// Try matching just the language part
		$parts = explode('_', $locale);
		$langPart = strtolower($parts[0]);

		if (isset($languages[$langPart])) {
			return $langPart;
		}

		return $locale;
	}

	/**
	 * Remove country code from a locale (e.g., 'da_DK' → 'da').
	 */
	public static function removeCountryCode(string $locale): string
	{
		$parts = explode('_', $locale);
		return strtolower($parts[0]);
	}

	/**
	 * Get the hreflang value for a language code.
	 * Returns format like 'da', 'en', 'pt-br'.
	 */
	public static function getHreflangCode(string $langCode): string
	{
		return strtolower(str_replace('_', '-', $langCode));
	}
}
