<?php
/**
 * Helper utilities for the languages admin view.
 *
 * @package WPR_Translate
 */

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

/**
 * Prepare payload for the languages admin view.
 *
 * @param array $languages Saved languages option.
 * @param array $catalog   Available catalog languages.
 *
 * @return array
 */
function wpr_translate_admin_prepare_languages_view_data( $languages, $catalog ) {
    // Normalize inputs to arrays.
    if ( ! is_array( $languages ) ) {
        $languages = array();
    }

    if ( ! is_array( $catalog ) ) {
        $catalog = array();
    }

    // Sort configured languages by display order.
    usort(
        $languages,
        static function ( $a, $b ) {
            $order_a = isset( $a['display_order'] ) ? (int) $a['display_order'] : 0;
            $order_b = isset( $b['display_order'] ) ? (int) $b['display_order'] : 0;

            if ( $order_a === $order_b ) {
                return 0;
            }

            return ( $order_a < $order_b ) ? -1 : 1;
        }
    );

    // Build a lookup table for catalog languages.
    $catalog_lookup = array();

    foreach ( $catalog as $entry ) {
        if ( ! is_array( $entry ) || empty( $entry['code'] ) ) {
            continue;
        }

        $code = sanitize_text_field( $entry['code'] );

        $catalog_lookup[ $code ] = array(
            'code'   => $code,
            'name'   => isset( $entry['name'] ) ? sanitize_text_field( $entry['name'] ) : '',
            'locale' => isset( $entry['locale'] ) ? sanitize_text_field( $entry['locale'] ) : '',
            'slug'   => isset( $entry['slug'] ) ? sanitize_title( $entry['slug'] ) : $code,
            'flag'   => isset( $entry['flag'] ) ? sanitize_text_field( $entry['flag'] ) : '',
        );
    }

    // Build the prepared list for the view.
    $prepared_languages = array();
    $default_code       = '';
    $next_index         = 0;

    foreach ( $languages as $language ) {
        if ( ! is_array( $language ) ) {
            continue;
        }

        // Normalize missing keys with defaults.
        $language = wp_parse_args(
            $language,
            array(
                'code'          => '',
                'locale'        => '',
                'name'          => '',
                'slug'          => '',
            'flag'          => '',
            'is_default'    => false,
            'is_active'     => true,
            'is_public'     => true,
            'date_format'   => '',
            'time_format'   => '',
            'display_order' => $next_index,
            )
        );

        $code = sanitize_text_field( $language['code'] );

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

        $is_default = ! empty( $language['is_default'] );

        if ( $is_default && '' === $default_code ) {
            $default_code = $code;
        }

        $catalog_entry = isset( $catalog_lookup[ $code ] ) ? $catalog_lookup[ $code ] : array();

        $prepared_languages[] = array(
            'index'         => $next_index,
            'code'          => $code,
            'name'          => sanitize_text_field( $language['name'] ),
            'locale'        => sanitize_text_field( $language['locale'] ),
            'slug'          => sanitize_title( $language['slug'] ),
            'flag'          => isset( $language['flag'] ) ? sanitize_text_field( $language['flag'] ) : '',
            'display_order' => isset( $language['display_order'] ) ? (int) $language['display_order'] : $next_index,
            'is_default'    => $is_default ? '1' : '0',
            'is_active'     => isset( $language['is_active'] ) ? (bool) $language['is_active'] : true,
            'is_public'     => isset( $language['is_public'] ) ? (bool) $language['is_public'] : true,
            'date_format'   => isset( $language['date_format'] ) ? sanitize_text_field( $language['date_format'] ) : '',
            'time_format'   => isset( $language['time_format'] ) ? sanitize_text_field( $language['time_format'] ) : '',
            'lock_code'     => ! empty( $catalog_entry ),
        );

        $next_index++;
    }

    // Ensure a default language is set.
    if ( '' === $default_code && ! empty( $prepared_languages ) ) {
        $default_code = $prepared_languages[0]['code'];
        $prepared_languages[0]['is_default'] = '1';
    }

    $active_codes = wp_list_pluck( $prepared_languages, 'code' );

    // Build catalog options with active flags.
    $available_catalog = array();

    foreach ( $catalog_lookup as $code => $entry ) {
        $entry['is_active'] = in_array( $code, $active_codes, true );
        $available_catalog[] = $entry;
    }

    // Sort catalog entries alphabetically for predictable picker ordering.
    usort(
        $available_catalog,
        static function ( $a, $b ) {
            $name_a = isset( $a['name'] ) ? strtolower( $a['name'] ) : '';
            $name_b = isset( $b['name'] ) ? strtolower( $b['name'] ) : '';

            if ( $name_a === $name_b ) {
                $code_a = isset( $a['code'] ) ? strtolower( $a['code'] ) : '';
                $code_b = isset( $b['code'] ) ? strtolower( $b['code'] ) : '';

                return strcmp( $code_a, $code_b );
            }

            return strcmp( $name_a, $name_b );
        }
    );

    // Prepare flag label options for the selector.
    $flag_labels = array(
        '' => __( 'No flag', 'wpr-translate' ),
    );

    foreach ( $available_catalog as $entry ) {
        if ( empty( $entry['flag'] ) ) {
            continue;
        }

        if ( ! isset( $flag_labels[ $entry['flag'] ] ) ) {
            $flag_labels[ $entry['flag'] ] = sprintf(
                /* translators: %1$s is the language name, %2$s is the flag code. */
                __( '%1$s (%2$s)', 'wpr-translate' ),
                $entry['name'],
                strtoupper( $entry['flag'] )
            );
        }
    }

    foreach ( $prepared_languages as $language ) {
        if ( '' === $language['flag'] ) {
            continue;
        }

        if ( ! isset( $flag_labels[ $language['flag'] ] ) ) {
            $flag_labels[ $language['flag'] ] = strtoupper( $language['flag'] );
        }
    }

    // Use WordPress defaults for date/time formatting.
    $default_date_format = get_option( 'date_format' );
    $default_time_format = get_option( 'time_format' );

    // Check if there are any inactive catalog entries to add.
    $has_available_catalog = false;
    foreach ( $available_catalog as $entry ) {
        if ( empty( $entry['is_active'] ) ) {
            $has_available_catalog = true;
            break;
        }
    }

    return array(
        'languages'             => $prepared_languages,
        'catalog_options'       => $available_catalog,
        'flag_labels'           => $flag_labels,
        'default_language_code' => $default_code,
        'next_index'            => $next_index,
        'default_date_format'   => $default_date_format,
        'default_time_format'   => $default_time_format,
        'has_available_catalog' => $has_available_catalog,
    );
}
