<?php
/**
 * Elementor text extraction helpers.
 *
 * Utilities for locating translatable text nodes inside Elementor layouts.
 *
 * @package WPR_Translate
 */

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

/**
 * Extract translatable text from stored Elementor data.
 *
 * @param mixed $raw_elementor_data Stored Elementor payload.
 *
 * @return array
 */
function wpr_translate_extract_elementor_text_fields( $raw_elementor_data ) {
    // Normalize the stored Elementor payload.
    $data = maybe_unserialize( $raw_elementor_data );

    // Elementor stores JSON strings; convert them into arrays for iteration.
    if ( is_string( $data ) ) {
        $decoded = json_decode( $data, true );

        if ( is_array( $decoded ) ) {
            $data = $decoded;
        }
    }

    if ( ! is_array( $data ) ) {
        return array();
    }

    // Track common text fields that should be translated.
    $text_fields   = array();
    $wanted_fields = array( 'title', 'heading', 'text', 'button_text', 'label' );

    foreach ( $data as $element ) {
        if ( isset( $element['settings'] ) && is_array( $element['settings'] ) ) {
            foreach ( $element['settings'] as $setting_key => $setting_value ) {
                // Collect common string fields for translation.
                if ( in_array( $setting_key, $wanted_fields, true ) && is_string( $setting_value ) ) {
                    $text_fields[] = wp_strip_all_tags( $setting_value );
                }
            }
        }

        if ( isset( $element['elements'] ) && is_array( $element['elements'] ) ) {
            // Traverse nested widgets so no text nodes are missed.
            $text_fields = array_merge( $text_fields, wpr_translate_extract_elementor_text_fields( $element['elements'] ) );
        }
    }

    return array_values( array_filter( $text_fields ) );
}

