<?php
/**
 * Language pack helpers for admin language management.
 *
 * @package WPR_Translate
 */

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

/**
 * Download WordPress core language packs for newly added locales.
 *
 * @param array $previous_languages Previously saved languages.
 * @param array $current_languages  Newly sanitized languages.
 *
 * @return void
 */
function wpr_translate_admin_maybe_install_language_packs( $previous_languages, $current_languages ) {
    // Only attempt installs in the admin for users with permissions.
    if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
        return;
    }

    if ( ! is_array( $previous_languages ) || ! is_array( $current_languages ) ) {
        return;
    }

    // Load WordPress translation install helpers when needed.
    if ( ! function_exists( 'wp_download_language_pack' ) || ! function_exists( 'wp_can_install_language_pack' ) ) {
        require_once ABSPATH . 'wp-admin/includes/translation-install.php';
    }

    if ( ! function_exists( 'wp_can_install_language_pack' ) || ! wp_can_install_language_pack() ) {
        return;
    }

    $installed_locales = get_available_languages();
    $installed_lookup  = array();

    if ( is_array( $installed_locales ) ) {
        foreach ( $installed_locales as $installed_locale ) {
            $installed_lookup[ strtolower( (string) $installed_locale ) ] = true;
        }
    }

    // WordPress does not list the default locale in available languages.
    $installed_lookup['en_us'] = true;

    foreach ( $current_languages as $language ) {
        if ( ! is_array( $language ) || empty( $language['locale'] ) ) {
            continue;
        }

        $locale = sanitize_text_field( $language['locale'] );
        $key    = strtolower( $locale );

        if ( '' === $locale ) {
            continue;
        }

        if ( isset( $installed_lookup[ $key ] ) ) {
            continue;
        }

        // Download the core language pack so date and time localization works.
        $downloaded = wp_download_language_pack( $locale );

        if ( false === $downloaded ) {
            continue;
        }

        // Track successful installs to avoid duplicate downloads during the same save.
        $installed_lookup[ $key ] = true;
    }
}
