<?php
/**
 * Internationalization-related functions for the Nisje.
 *
 * @package nisje
 */

declare( strict_types=1 );
namespace NisjeFrontend\I18n;

if ( ! defined( 'ABSPATH' ) ) {
	die( 'Silence is golden.' );
}

/**
 * Returns lang
 *
 * @return string
 */
function get_current_locale(): string {
	return is_user_logged_in() ? get_user_locale() : get_locale();
}

/**
 * Returns Jed-formatted localization data.
 *
 * @param  string $domain Translation domain.
 * @return array
 */
function get_jed_locale_data( string $domain ): array {
	$lang = get_current_locale();

	if ( 'en_US' === $lang ) {
		return [];
	}

	$translations = \get_translations_for_domain( $domain );

	$locale = [
		'' => [
			'domain' => $domain,
			'lang'   => is_user_logged_in() ? get_user_locale() : get_locale(),
		],
	];

	if ( ! empty( $translations->headers['Plural-Forms'] ) ) {
		$locale['']['plural_forms'] = $translations->headers['Plural-Forms'];
	}

	foreach ( $translations->entries as $msgid => $entry ) {
		$locale[ $msgid ] = $entry->translations;
	}

	return $locale;
}

/**
 * Load text domain for translations.
 */
function load_textdomain() {
	\load_theme_textdomain(
		'nisje-theme',
		get_template_directory() . '/languages/'
	);
}
add_action( 'after_setup_theme', __NAMESPACE__ . '\\load_textdomain' );
