<?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 ): string {
	$lang = get_current_locale();

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

	$file = dirname( __DIR__ ) . '/languages/' . $lang . '.json';

	if ( ! file_exists( $file ) ) {
		return '[]';
	}

	$translations = \file_get_contents( $file ); // phpcs:ignore

	return $translations;
}

/**
 * Load text domain for translations.
 */
function load_textdomain() {
	global $wp_locale;

	if ( \is_user_logged_in() ) {
		load_default_textdomain( \get_user_locale() );

		if ( \get_user_locale() === 'ar' ) {
			$wp_locale->text_direction = 'rtl';
		} else {
			$wp_locale->text_direction = 'ltr';
		}
	}

	\load_theme_textdomain(
		'nisje',
		get_template_directory() . '/languages/'
	);
}
\add_action( 'after_setup_theme', __NAMESPACE__ . '\\load_textdomain' );

/**
 * Always use user locale
 */
\add_filter( 'pre_determine_locale', function() {
	return \is_user_logged_in() ? \get_user_locale() : null;
} );
