<?php
/**
 * Filters WPResidence advanced search tab term IDs by the active language.
 *
 * @package WPR_Translate
 */

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

/**
 * Map WPResidence advanced search tab terms to the current language.
 *
 * @param mixed $options Theme options array from `wpresidence_admin`.
 *
 * @return mixed
 */
function wpr_translate_filter_adv6_terms_in_theme_options( $options ) {
    // Only adjust on the front end.
    if ( is_admin() ) {
        return $options;
    }

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

    if ( empty( $options['wp_estate_adv6_taxonomy_terms'] ) || ! is_array( $options['wp_estate_adv6_taxonomy_terms'] ) ) {
        return $options;
    }

    $taxonomy = '';

    if ( ! empty( $options['wp_estate_adv6_taxonomy'] ) ) {
        $taxonomy = sanitize_key( $options['wp_estate_adv6_taxonomy'] );
    }

    if ( '' === $taxonomy || ! function_exists( 'wpr_translation_is_taxonomy_translatable' ) ) {
        return $options;
    }

    if ( ! wpr_translation_is_taxonomy_translatable( $taxonomy ) ) {
        return $options;
    }

    if ( ! function_exists( 'wpr_translate_resolve_original_term_id' ) || ! function_exists( 'wpr_translate_lookup_translated_term_id_strict' ) ) {
        return $options;
    }

    $languages = function_exists( 'wpr_translate_get_active_languages' ) ? wpr_translate_get_active_languages() : array();

    if ( empty( $languages ) ) {
        return $options;
    }

    $default_language = wpr_translation_get_default_language_code( $languages );

    if ( '' === $default_language ) {
        return $options;
    }

    $current_language = '';

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

    $request_language = '';

    if ( isset( $GLOBALS['wpr_translate_language_router']['matched_language']['code'] ) ) {
        // Router may strip language prefix from REQUEST_URI; use matched language when available.
        $request_language = sanitize_key( (string) $GLOBALS['wpr_translate_language_router']['matched_language']['code'] );
    }

    if ( '' === $request_language && ! empty( $languages ) ) {
        // Resolve language from the first URL segment so early option reads map terms correctly.
        $request_uri  = isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_unslash( $_SERVER['REQUEST_URI'] ) : '';
        $request_path = (string) wp_parse_url( $request_uri, PHP_URL_PATH );
        $segments     = array_values( array_filter( explode( '/', trim( $request_path, '/' ) ) ) );
        $home_path    = (string) wp_parse_url( home_url( '/' ), PHP_URL_PATH );
        $base_segments = array_values( array_filter( explode( '/', trim( $home_path, '/' ) ) ) );

        if ( ! empty( $base_segments ) && ! empty( $segments ) ) {
            foreach ( $base_segments as $index => $base_segment ) {
                if ( isset( $segments[ $index ] ) && $segments[ $index ] === $base_segment ) {
                    unset( $segments[ $index ] );
                }
            }
            $segments = array_values( $segments );
        }

        if ( ! empty( $segments ) ) {
            $first_segment = strtolower( sanitize_key( (string) $segments[0] ) );

            foreach ( $languages as $language_data ) {
                if ( ! is_array( $language_data ) ) {
                    continue;
                }

                $language_code = ! empty( $language_data['code'] ) ? strtolower( sanitize_key( (string) $language_data['code'] ) ) : '';
                $language_slug = '';

                if ( function_exists( 'wpr_translate_get_language_slug' ) ) {
                    $language_slug = strtolower( sanitize_key( (string) wpr_translate_get_language_slug( $language_data ) ) );
                } elseif ( ! empty( $language_data['slug'] ) ) {
                    $language_slug = strtolower( sanitize_key( (string) $language_data['slug'] ) );
                }

                if ( '' !== $language_slug && $first_segment === $language_slug ) {
                    $request_language = '' !== $language_code ? $language_code : $language_slug;
                    break;
                }

                if ( '' !== $language_code && $first_segment === $language_code ) {
                    $request_language = $language_code;
                    break;
                }
            }
        }
    }

    if ( '' !== $request_language ) {
        // URL/router language must win over early default fallbacks.
        $current_language = $request_language;
    }

    if ( '' === $current_language && function_exists( 'wpestate_get_current_language' ) ) {
        $current_language = sanitize_key( wpestate_get_current_language() );
        if ( '' !== $current_language && function_exists( 'wpr_translate_get_language' ) ) {
            $resolved = wpr_translate_get_language( $current_language );
            if ( is_array( $resolved ) && ! empty( $resolved['code'] ) ) {
                $current_language = sanitize_key( $resolved['code'] );
            }
        }
    }

    if ( '' === $current_language ) {
        $current_language = $default_language;
    }

    $mapped_terms = array();
    $seen_terms   = array();
    $taxonomy_registered = taxonomy_exists( $taxonomy );

    foreach ( $options['wp_estate_adv6_taxonomy_terms'] as $term_id ) {
        $term_id = absint( $term_id );

        if ( $term_id <= 0 ) {
            continue;
        }

        if ( $taxonomy_registered ) {
            $canonical_term_id = absint( wpr_translate_resolve_original_term_id( $term_id, $taxonomy ) );
        } else {
            // Early option reads may happen before taxonomy registration.
            $canonical_term_id = absint( get_term_meta( $term_id, 'wpr_original_term_id', true ) );
        }

        if ( $canonical_term_id <= 0 ) {
            $canonical_term_id = $term_id;
        }

        $target_id         = 0;

        if ( $current_language === $default_language ) {
            // Keep canonical source terms in the default language.
            $target_id = $canonical_term_id > 0 ? $canonical_term_id : $term_id;
        } else {
            if ( $taxonomy_registered ) {
                // Try strict translation mapping first.
                $resolved_target = wpr_translate_lookup_translated_term_id_strict( $canonical_term_id, $taxonomy, $current_language );

                if ( is_numeric( $resolved_target ) ) {
                    $target_id = absint( $resolved_target );
                }

                // Fallback to non-strict lookup when strict mapping is missing.
                if ( $target_id <= 0 && function_exists( 'wpr_translate_lookup_translated_term_id' ) ) {
                    $resolved_target = wpr_translate_lookup_translated_term_id( $canonical_term_id, $taxonomy, $current_language );

                    if ( is_numeric( $resolved_target ) ) {
                        $target_id = absint( $resolved_target );
                    }
                }
            } else {
                // Use direct term-meta map until taxonomy APIs are available.
                $meta_key = function_exists( 'wpr_translate_get_translated_term_meta_key' )
                    ? wpr_translate_get_translated_term_meta_key( $current_language )
                    : 'wpr_translated_term_' . sanitize_key( $current_language );

                $meta_target = absint( get_term_meta( $canonical_term_id, $meta_key, true ) );

                if ( $meta_target > 0 && $meta_target !== $canonical_term_id ) {
                    $target_id = $meta_target;
                }
            }

            // Keep the canonical term when no translated mapping exists.
            if ( $target_id <= 0 ) {
                $target_id = $canonical_term_id > 0 ? $canonical_term_id : $term_id;
            }
        }

        if ( $target_id <= 0 || isset( $seen_terms[ $target_id ] ) ) {
            continue;
        }

        $mapped_terms[]           = $target_id;
        $seen_terms[ $target_id ] = true;
    }

    $options['wp_estate_adv6_taxonomy_terms'] = $mapped_terms;

    return $options;
}
// Support both WPResidence and WPRentals option stores without changing term mapping logic.
add_filter( 'option_wpresidence_admin', 'wpr_translate_filter_adv6_terms_in_theme_options', 20 );
add_filter( 'option_wprentals_admin', 'wpr_translate_filter_adv6_terms_in_theme_options', 20 );
