<?php
/**
 * Import helper for theme and plugin specific admin strings.
 *
 * @package WPR_Translate
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
require_once WPR_TRANSLATE_PATH . 'includes/admin/string-storage.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/string-query.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/theme-strings-helpers.php';
/**
 * Import admin strings declared by the active theme.
 *
 * @return array|WP_Error
 */
function wpr_translate_admin_import_theme_admin_strings() {
    static $processed = false;
    // Avoid duplicate imports within the same request.
    if ( $processed ) {
        return array(
            'status' => 'skipped',
            'domain' => get_option( 'wpr_translate_theme_admin_strings_domain', '' ),
        );
    }
    $processed   = true;
    $theme_path  = trailingslashit( get_stylesheet_directory() ) . 'wpr/';
    $source_file = $theme_path . 'theme_admin_strings.json';
    // Ensure the JSON definition file exists and is readable.
    if ( ! file_exists( $source_file ) || ! is_readable( $source_file ) ) {
        return new WP_Error(
            'wpr_translate_theme_admin_missing',
            __( 'The theme admin strings file could not be found in the active theme.', 'wpr-translate' )
        );
    }
    // Read and decode the JSON payload.
    $raw = file_get_contents( $source_file );
    if ( false === $raw ) {
        return new WP_Error(
            'wpr_translate_theme_admin_unreadable',
            __( 'Failed to read the theme admin strings file.', 'wpr-translate' )
        );
    }
    $data = json_decode( $raw, true );
    if ( null === $data || ! is_array( $data ) ) {
        return new WP_Error(
            'wpr_translate_theme_admin_invalid',
            __( 'The theme admin strings file is not formatted correctly.', 'wpr-translate' )
        );
    }
    // Extract the first domain block from the file.
    $domain      = '';
    $domain_data = array();
    foreach ( $data as $domain_key => $domain_value ) {
        if ( is_string( $domain_key ) && is_array( $domain_value ) ) {
            $domain      = sanitize_key( $domain_key );
            $domain_data = $domain_value;
            break;
        }
    }
    if ( '' === $domain ) {
        return new WP_Error(
            'wpr_translate_theme_admin_invalid_domain',
            __( 'The theme admin strings file does not declare a valid domain.', 'wpr-translate' )
        );
    }
    // Persist the domain and check if the file has changed.
    update_option( 'wpr_translate_theme_admin_strings_domain', $domain );
    $file_hash      = md5_file( $source_file );
    $stored_hash = get_option( 'wpr_translate_theme_admin_strings_hash', '' );
    // Flatten the nested JSON into string entries.
    $flattened = wpr_translate_admin_flatten_theme_admin_strings( $domain_data );
    // Expand wildcard paths with live option values when available.
    $flattened = wpr_translate_admin_expand_theme_admin_wildcards( $flattened, $domain );
    $expected_count = count( $flattened );
    $existing_count = 0;
    if ( $expected_count > 0 && function_exists( 'wpr_translate_admin_count_strings_for_domain_names' ) ) {
        $existing_count = wpr_translate_admin_count_strings_for_domain_names( $domain, array_keys( $flattened ) );
    }
    // Always continue to persistence so changed option values are synced even
    // when the JSON file hash and string-name count are unchanged.
    if ( empty( $flattened ) ) {
        update_option( 'wpr_translate_theme_admin_strings_hash', $file_hash );
        return array(
            'status' => 'imported',
            'count'  => 0,
            'domain' => $domain,
        );
    }
    // Prepare string payloads for insertion.
    $languages    = get_option( 'wpr_translate_languages', array() );
    $default_code = wpr_translate_admin_get_default_language_code( $languages );
    $strings      = array();
    foreach ( $flattened as $name => $value ) {
        $clean_name  = sanitize_text_field( $name );
        $clean_value = wp_kses_post( $value );
        if ( '' === $clean_name ) {
            continue;
        }
        $hash_key             = md5( $domain . '|' . $clean_name );
        $strings[ $hash_key ] = array(
            'context'      => $domain,
            'name'         => $clean_name,
            'value'        => $clean_value,
            'md5'          => md5( $clean_value ),
            'translations' => array(),
        );
    }
    if ( empty( $strings ) ) {
        return new WP_Error(
            'wpr_translate_theme_admin_empty',
            __( 'No valid admin strings were found in the theme file.', 'wpr-translate' )
        );
    }
    // Insert or update the strings in storage.
    $inserted = wpr_translate_admin_persist_detected_strings( $strings, $languages, $default_code );
    update_option( 'wpr_translate_theme_admin_strings_hash', $file_hash );
    return array(
        'status' => 'imported',
        'count'  => $inserted,
        'domain' => $domain,
    );
}

/**
 * Recursively flatten the domain structure into string entries.
 *
 * @param array  $data   Nested string data.
 * @param string $prefix Current key prefix.
 *
 * @return array
 */
function wpr_translate_admin_flatten_theme_admin_strings( $data, $prefix = '' ) {
    $results = array();
    foreach ( $data as $key => $value ) {
        // Normalize the current key into a path segment.
        $normalized_key = is_string( $key ) ? $key : '';
        if ( '' === $normalized_key ) {
            continue;
        }
        $path = '' === $prefix ? $normalized_key : $prefix . '.' . $normalized_key;
        if ( is_array( $value ) ) {
            // Recurse into nested arrays.
            $results = array_merge(
                $results,
                wpr_translate_admin_flatten_theme_admin_strings( $value, $path )
            );
            continue;
        }
        if ( is_string( $value ) ) {
            // Store leaf string values.
            $results[ $path ] = $value;
        }
    }
    return $results;
}
/**
 * Replace admin option values with translations from stored string entries.
 *
 * @param mixed  $value  Option value.
 * @param string $option Option name.
 *
 * @return mixed
 */
function wpr_translate_admin_filter_theme_option_translations( $value, $option ) {
    global $wpdb;
    // Only process array options and when a language helper exists.
    if ( ! is_array( $value ) || ! function_exists( 'wpr_translate_get_active_language_code' ) ) {
        return $value;
    }

    // Never alter theme option payloads in wp-admin to avoid saving translated
    // strings back into the source option values.
    if ( is_admin() ) {
        return $value;
    }

    // Resolve the active language code, falling back to the admin helper when needed.
    $language_code = wpr_translate_get_active_language_code();
    if ( '' === $language_code && function_exists( 'wpr_translate_return_current_language_admin' ) ) {
        $language_code = wpr_translate_return_current_language_admin();
    }
    $language_code = strtolower( sanitize_key( $language_code ) );

    if ( '' === $language_code && function_exists( 'wpestate_get_current_language' ) && function_exists( 'wpr_translate_get_language' ) ) {
        // Fall back to the URL-aware theme helper when the language was not resolved yet.
        $language_slug = sanitize_key( wpestate_get_current_language() );
        $resolved      = wpr_translate_get_language( $language_slug );
        if ( is_array( $resolved ) && ! empty( $resolved['code'] ) ) {
            $language_code = strtolower( sanitize_key( $resolved['code'] ) );
        }
    }

    if ( '' === $language_code ) {
        return $value;
    }

    if ( ! wpr_translate_admin_strings_table_exists() ) {
        return $value;
    }
    // Resolve the domain used for theme admin strings.
    $context_domain = get_option( 'wpr_translate_theme_admin_strings_domain', '' );
    $context_domain = '' === $context_domain ? $option : $context_domain;
    $context_domain = sanitize_key( $context_domain );
    if ( '' === $context_domain ) {
        return $value;
    }

    // Cache translations for this domain and language to avoid repeated queries in the same request.
    static $translation_cache = array();
    $cache_key                = $context_domain . '|' . $language_code;
    if ( isset( $translation_cache[ $cache_key ] ) ) {
        $translations = $translation_cache[ $cache_key ];
    } else {
        // Query translations for this domain and language.
        $table = $wpdb->prefix . 'wpestate_translation_strings';
        $rows  = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT name, translation FROM {$table} WHERE context = %s AND language_code = %s",
                $context_domain,
                $language_code
            ),
            ARRAY_A
        );

        // Build a lookup map of translated option paths.
        $translations = array();

        foreach ( $rows as $row ) {
            $name        = isset( $row['name'] ) ? (string) $row['name'] : '';
            $translation = isset( $row['translation'] ) ? (string) $row['translation'] : '';
            $clean_value = trim( wp_strip_all_tags( $translation ) );
            if ( '' === $name || '' === $clean_value ) {
                continue;
            }
            $translations[ $name ] = $translation;
        }

        $translation_cache[ $cache_key ] = $translations;
    }
    if ( empty( $translations ) ) {
        return $value;
    }
    foreach ( $translations as $path => $translated_value ) {
        // Replace values when a path exists in the option array.
        $existing_value = wpr_translate_admin_get_option_value_by_path( $value, $path );

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

        wpr_translate_admin_set_option_value_by_path( $value, $path, $translated_value );
    }

    // Mirror translated advanced search labels into the legacy root key.
    if ( isset( $value['wpestate_set_search']['adv_search_label'] ) && is_array( $value['wpestate_set_search']['adv_search_label'] )
        && isset( $value['wp_estate_adv_search_label'] ) && is_array( $value['wp_estate_adv_search_label'] ) ) {
        foreach ( $value['wpestate_set_search']['adv_search_label'] as $index => $label ) {
            $clean_label = trim( wp_strip_all_tags( (string) $label ) );
            if ( '' === $clean_label ) {
                continue;
            }
            $value['wp_estate_adv_search_label'][ $index ] = $label;
        }
    }

    return $value;
}

if ( ! function_exists( 'wpr_translate_admin_apply_declared_theme_option_translations' ) ) {
    /**
     * Apply theme option translations using only keys declared in theme_admin_strings.json.
     *
     * @param array  $value         Option value to translate.
     * @param string $option        Option name/domain.
     * @param string $language_code Target language code.
     *
     * @return array
     */
    function wpr_translate_admin_apply_declared_theme_option_translations( $value, $option, $language_code ) {
        global $wpdb;

        if ( ! is_array( $value ) || '' === $option || '' === $language_code ) {
            return $value;
        }

        if ( is_admin() ) {
            // Never mutate admin payloads while saving options.
            return $value;
        }

        if ( ! function_exists( 'wpr_translate_admin_strings_table_exists' ) || ! wpr_translate_admin_strings_table_exists() ) {
            return $value;
        }

        $source_file = trailingslashit( get_stylesheet_directory() ) . 'wpr/theme_admin_strings.json';
        if ( ! file_exists( $source_file ) || ! is_readable( $source_file ) ) {
            return $value;
        }

        $raw = file_get_contents( $source_file );
        if ( false === $raw ) {
            return $value;
        }

        $data = json_decode( $raw, true );
        if ( ! is_array( $data ) || ! isset( $data[ $option ] ) || ! is_array( $data[ $option ] ) ) {
            return $value;
        }

        $declared_paths = wpr_translate_admin_flatten_theme_admin_strings( $data[ $option ] );
        $declared_paths = wpr_translate_admin_expand_theme_admin_wildcards( $declared_paths, $option );
        $declared_names = array_keys( $declared_paths );

        if ( empty( $declared_names ) ) {
            return $value;
        }

        $table = $wpdb->prefix . 'wpestate_translation_strings';
        $rows  = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT name, translation FROM {$table} WHERE context = %s AND language_code = %s",
                sanitize_key( $option ),
                strtolower( sanitize_key( $language_code ) )
            ),
            ARRAY_A
        );

        if ( empty( $rows ) ) {
            return $value;
        }

        $allowed = array_fill_keys( $declared_names, true );

        foreach ( $rows as $row ) {
            $name        = isset( $row['name'] ) ? (string) $row['name'] : '';
            $translation = isset( $row['translation'] ) ? (string) $row['translation'] : '';

            if ( '' === $name || '' === $translation || ! isset( $allowed[ $name ] ) ) {
                continue;
            }

            if ( '' === wpr_translate_admin_get_option_value_by_path( $value, $name ) ) {
                continue;
            }

            wpr_translate_admin_set_option_value_by_path( $value, $name, $translation );
        }

        return $value;
    }
}
/**
 * Register the option filter for the theme admin strings domain.
 */
function wpr_translate_admin_register_theme_option_translations() {
    static $registered = false;
    // Avoid duplicate registration.
    if ( $registered ) {
        return;
    }
    $registered = true;
    $domain     = get_option( 'wpr_translate_theme_admin_strings_domain', '' );
    if ( '' === $domain ) {
        // Attempt to import domain data if missing.
        $import = wpr_translate_admin_import_theme_admin_strings();
        if ( is_array( $import ) && ! empty( $import['domain'] ) ) {
            $domain = sanitize_key( $import['domain'] );
        }
    }
    if ( '' === $domain ) {
        return;
    }
    // Attach the option filter to translate theme admin strings.
    add_filter( 'option_' . $domain, 'wpr_translate_admin_filter_theme_option_translations', 10, 2 );
}
add_action( 'init', 'wpr_translate_admin_register_theme_option_translations', 1 );
