<?php

namespace RRZE\Locale;

defined('ABSPATH') || exit;

class Locale
{
    /**
     * Dropdown for available languages
     *
     * @return void
     */
    public function langDropdown()
    {
        $currentLocale = $this->getLocale();
        $availableLanguages = $this->getAvailableLanguages();

        echo '<label class="screen-reader-text" for="language">' . __('Select a language') . '</label>', PHP_EOL;
        echo '<select name="language" id="language">', PHP_EOL;

        foreach ($availableLanguages as $locale) {
            $translation = $this->getTranslation($locale);
            printf('<option value="%1$s"' . selected($currentLocale, $locale, false) . '>%2$s</option>%3$s', $locale, esc_attr($translation['native_name']), PHP_EOL);
        }
        echo '</select>', PHP_EOL;
    }

    /**
     * Retrieves the current base locale. (i.e. de_DE_formal => de_DE)
     *
     * @return string
     */
    protected function getLocale(): string
    {
        $locale = get_locale();
        return substr($locale, 0, 5);
    }

    /**
     * Get all available base languages (i.e. de_DE_formal => de_DE)
     *
     * @return array
     */
    protected function getAvailableLanguages(): array
    {
        // Get all available languages based on the presence of *.mo files in WP_LANG_DIR.
        $languages = get_available_languages();
        foreach ($languages as $k => $lang) {
            if (strlen($lang) > 5) {
                unset($languages[$k]);
            }
        }

        return array_merge($languages, ['en_US']);
    }

    /**
     * Get available translations from the WordPress.org API
     * and add en_US (default) to the available translations.
     *
     * @return array
     */
    protected function getAvailableTranslations(): array
    {
        require_once(ABSPATH . 'wp-admin/includes/translation-install.php');
        // Get available translations from the WordPress.org API.
        $translations = wp_get_available_translations();
        $english = [
            'en_US' => [
                'language' => 'en_US',
                'english_name' => 'English',
                'native_name' => 'English',
                'iso' => [
                    1 => 'en'
                ]
            ]
        ];

        return array_merge($translations, $english);
    }

    /**
     * Get a translation from the available translations.
     *
     * @param string $locale
     * @return string
     */
    protected function getTranslation(string $locale = 'en_US'): string
    {
        $translations = $this->getAvailableTranslations();
        if ($locale == 'en_EN') {
            $locale = 'en_US';
        }
        return $translations[$locale];
    }
}