<?php
/**
 * Primary language retrieval helpers.
 *
 * @package WPR_Translate
 */

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

if ( ! function_exists( 'wpr_translate_get_active_languages' ) ) {
    /**
     * Retrieve the configured languages that are active.
     *
     * @param bool $public_only Optional. Whether to restrict results to public languages. Default true.
     *
     * @return array<int, array<string, mixed>>
     */
    function wpr_translate_get_active_languages( $public_only = true ) {
        // Filter stored languages based on active/public flags.
        $languages = array_filter(
            wpr_translate_get_languages(),
            static function ( $language ) use ( $public_only ) {
                if ( empty( $language['is_active'] ) ) {
                    return false;
                }
                if ( $public_only && empty( $language['is_public'] ) ) {
                    return false;
                }
                return true;
            }
        );

        // Return a re-indexed list for predictable ordering.
        return array_values( $languages );
    }
}

if ( ! function_exists( 'wpr_translate_get_current_language' ) ) {
    /**
     * Retrieve the language resolved for the current visitor.
     *
     * @return array<string, mixed>|null
     */
    function wpr_translate_get_current_language() {
        global $wpr_translate_current_language;

        // Return cached language when already resolved.
        if ( null !== $wpr_translate_current_language ) {
            return $wpr_translate_current_language;
        }

        // Resolve the preferred language based on current context.
        $preferred = wpr_translate_resolve_preferred_language();

        if ( null !== $preferred ) {
            // Persist the selected language and refresh theme translations.
            wpr_translate_set_current_language(
                $preferred,
                array( 'reload_theme_translations' => true )
            );
        }

        // Return the cached language payload (or null when unresolved).
        return $wpr_translate_current_language;
    }
}

