<?php
/**
 * Helper utilities shared by the language manager functions.
 *
 * @package WPR_Translate
 */

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

/**
 * Cached current language payload.
 *
 * @var array|null
 */
$GLOBALS['wpr_translate_current_language'] = $GLOBALS['wpr_translate_current_language'] ?? null;

/**
 * Normalize the language payload ensuring expected keys exist.
 *
 * @param array $language Language payload.
 *
 * @return array
 */
function wpr_translate_normalize_language( $language ) {
    // Merge defaults so every key exists.
    $language = wp_parse_args(
        $language,
        array(
            'code'        => '',
            'locale'      => '',
            'name'        => '',
            'slug'        => '',
            'flag'        => '',
            'is_default'  => false,
            'is_active'   => false,
            'is_public'   => false,
            'date_format' => '',
            'time_format' => '',
        )
    );

    // Sanitize user-facing values for safe usage.
    $language['code']   = sanitize_text_field( $language['code'] );
    $language['locale'] = sanitize_text_field( $language['locale'] );
    $language['name']   = sanitize_text_field( $language['name'] );
    $language['slug']   = sanitize_title( $language['slug'] );

    // Return the normalized language payload.
    return $language;
}

/**
 * Attempt to match the browser accept language header.
 *
 * @param array $languages Active languages.
 *
 * @return array|null
 */
function wpr_translate_match_browser_language( $languages ) {
    if ( empty( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) {
        // No header means we cannot infer a preference.
        return null;
    }

    // Parse the header into language candidates and quality scores.
    $header     = strtolower( wp_unslash( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) );
    $candidates = array();

    foreach ( explode( ',', $header ) as $entry ) {
        $entry = trim( $entry );

        if ( '' === $entry ) {
            // Skip empty segments from the header.
            continue;
        }

        $quality = 1.0;
        $code    = $entry;

        if ( false !== strpos( $entry, ';q=' ) ) {
            list( $code, $priority ) = array_map( 'trim', explode( ';q=', $entry ) );
            $quality                 = (float) $priority;
        }

        // Normalize locale separators to a single style.
        $code = str_replace( '_', '-', $code );

        $candidates[ $code ] = $quality;
    }

    if ( empty( $candidates ) ) {
        // No valid candidates were found.
        return null;
    }

    // Sort by descending quality to prioritize the strongest match.
    arsort( $candidates, SORT_NUMERIC );

    foreach ( $candidates as $candidate => $quality ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
        // Compare the full candidate and its root language.
        $candidate_root = substr( $candidate, 0, 2 );

        foreach ( $languages as $language ) {
            $locale_match = strtolower( str_replace( '_', '-', $language['locale'] ) );
            $code_match   = strtolower( $language['code'] );
            $slug_match   = strtolower( $language['slug'] );

            // First attempt an exact match.
            if ( $candidate === $locale_match || $candidate === $code_match || $candidate === $slug_match ) {
                return $language;
            }

            // Fall back to root-language matching.
            if ( $candidate_root === substr( $code_match, 0, 2 ) ) {
                return $language;
            }

            // Try locale root matching as a final fallback.
            if ( $candidate_root === substr( $locale_match, 0, 2 ) ) {
                return $language;
            }
        }
    }

    return null;
}

/**
 * Write a structured debug entry to the WordPress debug log.
 *
 * @param string $message Log message.
 * @param array  $context Optional context data.
 *
 * @return void
 */
function wpr_translate_debug_log( $message, $context = array() ) {
    if ( ! defined( 'WP_DEBUG_LOG' ) || ! WP_DEBUG_LOG || ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) {
        return;
    }

    if ( ! defined( 'WPR_TRANSLATE_DEBUG_LOG' ) || ! WPR_TRANSLATE_DEBUG_LOG ) {
        // Keep plugin debug output disabled unless explicitly enabled.
        return;
    }

    $entry = '[WPR Translate] ' . (string) $message;

    if ( ! empty( $context ) ) {
        $entry .= ' ' . wp_json_encode( $context );
    }

    // Emit a user notice so WordPress writes the entry into debug.log.
    trigger_error( $entry, E_USER_NOTICE ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
}
