<?php
/**
 * Elementor widget compatibility helpers for WPResidence shortcodes.
 *
 * The filters in this file ensure Elementor's shortcode widget benefits from
 * the same ID translation logic that runs on regular content so front-end
 * widgets honour the viewer's language.
 *
 * @package WPR_Translate
 */

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

/**
 * Register Elementor widget filters once.
 *
 * @return void
 */
function wpr_translate_bootstrap_elementor_widget_compat() {
    // Track registration state to avoid attaching duplicate filters.
    static $bootstrapped = false;

    if ( $bootstrapped ) {
        // Filters are already registered.
        return;
    }

    // Execute the filter that replays shortcode content inside Elementor widgets.
    $bootstrapped = true;
    add_filter( 'elementor/widget/render_content', 'wpr_translate_filter_elementor_shortcode_widget_content', 10, 2 );
    add_action( 'elementor/frontend/widget/before_render', 'wpr_translate_prepare_search_form_builder_frontend_ids', 20, 1 );
    add_action( 'elementor/frontend/widget/before_render', 'wpr_translate_log_agent_grids_frontend_ids', 20, 1 );
}
/**
 * Re-render Elementor shortcode widgets so shortcode compatibility applies.
 *
 * @param string $content Rendered widget content.
 * @param mixed  $widget  Widget instance provided by Elementor.
 *
 * @return string Filtered widget content.
 */
function wpr_translate_filter_elementor_shortcode_widget_content( $content, $widget ) {
    // Skip processing altogether when the compatibility toggle is disabled.
    if ( ! wpr_translate_is_elementor_compat_enabled() ) {
        // Keep Elementor output unchanged.
        return $content;
    }

    // Ensure we are dealing with a valid Elementor widget object.
    if ( ! is_object( $widget ) || ! method_exists( $widget, 'get_name' ) ) {
        // Widget does not expose the required API.
        return $content;
    }

    // Only re-render widgets registered as the generic Elementor shortcode widget.
    if ( 'shortcode' !== $widget->get_name() ) {
        // Only handle the shortcode widget type.
        return $content;
    }

    // Confirm the widget exposes settings before attempting to read them.
    if ( ! method_exists( $widget, 'get_settings_for_display' ) ) {
        // Settings are required to access the shortcode string.
        return $content;
    }

    $settings = $widget->get_settings_for_display();

    // The widget must contain a shortcode string so we can inspect it.
    if ( empty( $settings['shortcode'] ) || ! is_string( $settings['shortcode'] ) ) {
        // No shortcode to execute.
        return $content;
    }

    // Store the original shortcode string for comparison purposes.
    $shortcode_string = (string) $settings['shortcode'];

    // If Elementor already executed the shortcode, reuse the generated content.
    if ( trim( $content ) !== trim( $shortcode_string ) ) {
        // Elementor already executed the shortcode.
        return $content;
    }

    // Elementor sometimes bypasses execution (e.g., in previews); in that case rerun it.
    // Execute the shortcode so translation filters can run.
    return do_shortcode( $shortcode_string );
}

/**
 * Prime WPResidence Search Form Builder taxonomy transient on front end.
 *
 * @param mixed $widget Elementor widget instance.
 *
 * @return void
 */
function wpr_translate_prepare_search_form_builder_frontend_ids( $widget ) {
    // Restrict logic to front-end rendering only.
    if ( is_admin() || wp_doing_ajax() || wp_doing_cron() ) {
        return;
    }

    if ( ! is_object( $widget ) || ! method_exists( $widget, 'get_name' ) ) {
        return;
    }

    if ( 'WpResidence_Search_Form_Builder' !== (string) $widget->get_name() ) {
        return;
    }

    if ( ! method_exists( $widget, 'get_settings_for_display' ) ) {
        return;
    }

    $settings = $widget->get_settings_for_display();

    if ( ! is_array( $settings ) ) {
        return;
    }

    $widget_id = method_exists( $widget, 'get_id' ) ? sanitize_key( (string) $widget->get_id() ) : '';
    $page_id   = absint( get_queried_object_id() );
    $cache_key = $page_id . ':' . $widget_id;
    static $prepared_widgets = array();

    if ( isset( $prepared_widgets[ $cache_key ] ) ) {
        return;
    }

    $prepared_widgets[ $cache_key ] = true;

    $tax_field_map = array(
        'property_action_category' => 'action_data',
        'property_category'        => 'category_data',
        'property_city'            => 'city_data',
        'property_area'            => 'area_data',
        'property_county_state'    => 'county_data',
        'property_status'          => 'status_data',
    );

    $tabs_field = isset( $settings['tabs_field'] ) ? sanitize_key( (string) $settings['tabs_field'] ) : '';

    if ( '' === $tabs_field || ! isset( $tax_field_map[ $tabs_field ] ) ) {
        foreach ( $tax_field_map as $taxonomy => $field_name ) {
            if ( empty( $settings[ $field_name ] ) ) {
                continue;
            }

            $tabs_field = $taxonomy;
            break;
        }
    }

    if ( '' === $tabs_field || ! isset( $tax_field_map[ $tabs_field ] ) || ! taxonomy_exists( $tabs_field ) ) {
        return;
    }

    $tab_term_ids = wpr_translate_normalize_agent_grids_ids_for_log( $settings[ $tax_field_map[ $tabs_field ] ] );

    if ( empty( $tab_term_ids ) ) {
        return;
    }

    $primed_terms = array();

    foreach ( $tab_term_ids as $tab_term_id ) {
        $tab_term = get_term( $tab_term_id, $tabs_field );

        if ( ! ( $tab_term instanceof WP_Term ) || is_wp_error( $tab_term ) ) {
            continue;
        }

        $primed_terms[ (int) $tab_term->term_id ] = sanitize_text_field( (string) $tab_term->name );
    }

    if ( empty( $primed_terms ) ) {
        return;
    }

    $primed_transient_key = 'wpestate_elementor_tax_';

    if ( function_exists( 'wpestate_set_transient_name_multilang' ) ) {
        $primed_transient_key = (string) wpestate_set_transient_name_multilang( $primed_transient_key );
    }

    set_transient( $primed_transient_key, $primed_terms, 60 * 60 * 6 );
}

/**
 * Normalize Agent Grids post IDs from widget settings.
 *
 * @param mixed $value Raw setting value.
 *
 * @return array<int, int>
 */
function wpr_translate_normalize_agent_grids_ids_for_log( $value ) {
    // Reuse Elementor ID normalization when available.
    if ( function_exists( 'wpr_translate_normalize_elementor_ids' ) ) {
        return array_values( array_filter( array_map( 'absint', (array) wpr_translate_normalize_elementor_ids( $value ) ) ) );
    }

    if ( is_string( $value ) ) {
        $decoded = json_decode( $value, true );

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

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

    return array_values( array_filter( array_map( 'absint', (array) $value ) ) );
}

/**
 * Log front-end IDs used by the WPResidence Agent Grids Elementor widget.
 *
 * @param mixed $widget Elementor widget instance.
 *
 * @return void
 */
function wpr_translate_log_agent_grids_frontend_ids( $widget ) {
    // Restrict logging to front-end rendering only.
    if ( is_admin() || wp_doing_ajax() || wp_doing_cron() ) {
        return;
    }

    if ( ! defined( 'WP_DEBUG_LOG' ) || ! WP_DEBUG_LOG ) {
        return;
    }

    if ( ! is_object( $widget ) || ! method_exists( $widget, 'get_name' ) ) {
        return;
    }

    if ( 'Wpresidence_Agent_Grids' !== (string) $widget->get_name() ) {
        return;
    }

    if ( ! method_exists( $widget, 'get_settings_for_display' ) ) {
        return;
    }

    $settings = $widget->get_settings_for_display();

    if ( ! is_array( $settings ) ) {
        return;
    }

    $widget_id = method_exists( $widget, 'get_id' ) ? sanitize_key( (string) $widget->get_id() ) : '';
    $page_id   = absint( get_queried_object_id() );
    $cache_key = $page_id . ':' . $widget_id;
    static $logged_widgets = array();

    if ( isset( $logged_widgets[ $cache_key ] ) ) {
        return;
    }

    $logged_widgets[ $cache_key ] = true;

    $grid_taxonomy_ids = array();
    $live_agent_ids    = array();
    $live_agents       = array();

    if ( isset( $settings['grid_taxonomy'] ) ) {
        $grid_taxonomy_ids = wpr_translate_normalize_agent_grids_ids_for_log( $settings['grid_taxonomy'] );
    }

    foreach ( $grid_taxonomy_ids as $agent_id ) {
        $agent_post = get_post( $agent_id );

        if ( ! ( $agent_post instanceof WP_Post ) ) {
            continue;
        }

        $live_agent_ids[] = (int) $agent_post->ID;
        $live_agents[]    = array(
            'post_id'   => (int) $agent_post->ID,
            'post_type' => sanitize_key( (string) $agent_post->post_type ),
            'title'     => sanitize_text_field( get_the_title( $agent_post ) ),
        );
    }

    $language_code = '';

    if ( function_exists( 'wpr_translate_get_current_language' ) ) {
        $current_language = wpr_translate_get_current_language();

        if ( is_array( $current_language ) && ! empty( $current_language['code'] ) ) {
            $language_code = sanitize_key( $current_language['code'] );
        }
    }

    $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';

}
