<?php
/**
 * Import helper for theme classic widget strings.
 *
 * @package WPR_Translate
 */

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

require_once WPR_TRANSLATE_PATH . 'includes/theme-widget-strings.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/string-storage.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/string-query.php';

/**
 * Import classic widget strings declared by the active theme.
 *
 * @return array|WP_Error
 */
function wpr_translate_admin_import_theme_widget_strings() {
    global $wpdb;

    static $processed = false;

    // Avoid duplicate imports within the same request.
    if ( $processed ) {
        return array(
            'status' => 'skipped',
            'domain' => get_option( 'wpr_translate_theme_widget_strings_domain', '' ),
        );
    }

    // Ensure the translation strings table is available.
    $table        = $wpdb->prefix . 'wpestate_translation_strings';
    $table_exists = ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) === $table );

    if ( ! $table_exists ) {
        return new WP_Error(
            'wpr_translate_theme_widget_no_table',
            __( 'The translation strings table is missing, so widget strings cannot be imported yet.', 'wpr-translate' )
        );
    }

    // Resolve widget strings file locations in child/parent themes.
    $theme_path   = trailingslashit( get_stylesheet_directory() ) . 'wpr/';
    $source_file  = $theme_path . 'theme_widgets_strings.json';
    $fallback_dir = trailingslashit( get_template_directory() ) . 'wpr/';

    if ( ! file_exists( $source_file ) || ! is_readable( $source_file ) ) {
        $source_file = $fallback_dir . 'theme_widgets_strings.json';
    }

    if ( ! file_exists( $source_file ) || ! is_readable( $source_file ) ) {
        return new WP_Error(
            'wpr_translate_theme_widget_missing',
            __( 'The theme widget strings file could not be found in the active theme.', 'wpr-translate' )
        );
    }

    $processed = true;

    // Read and parse the widget strings file.
    $raw = file_get_contents( $source_file );

    if ( false === $raw ) {
        return new WP_Error(
            'wpr_translate_theme_widget_unreadable',
            __( 'Failed to read the theme widget strings file.', 'wpr-translate' )
        );
    }

    $data = json_decode( $raw, true );

    if ( null === $data || ! is_array( $data ) ) {
        return new WP_Error(
            'wpr_translate_theme_widget_invalid',
            __( 'The theme widget 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_widget_invalid_domain',
            __( 'The theme widget 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_widget_strings_domain', $domain );

    $file_hash   = md5_file( $source_file );
    $stored_hash = get_option( 'wpr_translate_theme_widget_strings_hash', '' );

    if ( $file_hash === $stored_hash ) {
        $existing = (int) $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(1) FROM {$table} WHERE context = %s",
                $domain
            )
        );

        if ( $existing > 0 ) {
            return array(
                'status' => 'up_to_date',
                'domain' => $domain,
            );
        }
    }

    // Flatten nested widget string definitions.
    $flattened = wpr_translate_admin_flatten_theme_widget_strings( $domain_data );

    if ( empty( $flattened ) ) {
        update_option( 'wpr_translate_theme_widget_strings_hash', $file_hash );

        return array(
            'status' => 'imported',
            'count'  => 0,
            'domain' => $domain,
        );
    }

    // Prepare string rows for persistence.
    $languages    = get_option( 'wpr_translate_languages', array() );
    $default_code = wpr_translate_admin_get_default_language_code( $languages );
    $strings      = array();

    foreach ( $flattened as $name => $value ) {
        $normalized_name = wpr_translate_admin_normalize_widget_string_path( $name );
        $clean_value     = wp_kses_post( $value );

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

        $hash_key             = md5( $domain . '|' . $normalized_name );
        $strings[ $hash_key ] = array(
            'context'      => $domain,
            'name'         => $normalized_name,
            'value'        => $clean_value,
            'md5'          => md5( $clean_value ),
            'translations' => array(),
        );
    }

    if ( empty( $strings ) ) {
        return new WP_Error(
            'wpr_translate_theme_widget_empty',
            __( 'No valid widget 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_widget_strings_hash', $file_hash );

    return array(
        'status' => 'imported',
        'count'  => $inserted,
        'domain' => $domain,
    );
}

/**
 * Recursively flatten widget entries into dot-delimited paths.
 *
 * @param array  $data   Widget strings.
 * @param string $prefix Current traversal prefix.
 *
 * @return array
 */
function wpr_translate_admin_flatten_theme_widget_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_widget_strings( $value, $path )
            );
            continue;
        }

        if ( is_string( $value ) ) {
            // Store leaf string values.
            $results[ $path ] = $value;
        }
    }

    return $results;
}
