<?php
/**
 * Settings language helpers.
 *
 * @package BatoCookieConsent
 */

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

final class Bato_Cookie_Consent_Settings_Languages
{
    private const SUPPORTED = array(
        'en',
        'en-gb',
        'uk',
        'fr',
        'de',
        'es',
        'it',
        'pt',
        'he',
        'ca-es',
        'sv',
        'no',
        'nl',
        'fi',
        'hu',
        'cs',
        'hr',
        'da',
        'sk',
        'sl',
        'pl',
        'el',
        'mk',
        'ro',
        'sr',
        'et',
        'lt',
        'lv',
        'ru',
        'bg',
        'cy',
        'ja',
        'ar',
        'tr',
    );

    public static function supported(): array
    {
        return self::SUPPORTED;
    }

    public static function normalize_locale(string $locale): string
    {
        $language = strtolower(str_replace('_', '-', $locale));

        $aliases = array(
            'en-uk' => 'en-gb',
            'en-us' => 'en',
            'uk-ua' => 'uk',
            'ca-es-valencia' => 'ca-es',
        );

        if (isset($aliases[$language])) {
            return $aliases[$language];
        }

        if (in_array($language, self::SUPPORTED, true)) {
            return $language;
        }

        $base = strtok($language, '-');

        return in_array($base, self::SUPPORTED, true) ? $base : '';
    }

    public static function default_language(): string
    {
        $site_language = self::normalize_locale(get_locale());

        return $site_language ? $site_language : 'auto';
    }
}
