<?php
/**
 * Helper functions bridging the legacy WP Estate translation helpers with the
 * modern language manager utilities introduced by this plugin.
 *
 * @package WPR_Translate
 */

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

if ( ! class_exists( 'WP_Estate_Translation' ) ) {
    /**
     * Minimal compatibility layer exposing the current language slug expected
     * by legacy helper functions inside the WP Estate theme.
     */
    class WP_Estate_Translation {
        /**
         * Cached current language slug (e.g. `en`, `fr`).
         *
         * @var string|null
         */
        public static $current_language = null;
    }
}

if ( ! function_exists( 'wpr_translation_get_default_language_code' ) ) {
    /**
     * Retrieves the default language code from the language list.
     *
     * @param array $languages Languages list.
     *
     * @return string
     */
    function wpr_translation_get_default_language_code( $languages ) {
        // Look for the explicit default language first.
        foreach ( $languages as $language ) {
            if ( ! empty( $language['is_default'] ) && ! empty( $language['code'] ) ) {
                return $language['code'];
            }
        }

        // Fall back to the first language entry when available.
        if ( ! empty( $languages[0]['code'] ) ) {
            return $languages[0]['code'];
        }

        // Return an empty string when no valid language is found.
        return '';
    }
}

if ( ! function_exists( 'wpestate_translation_get_active_languages' ) ) {
    /**
     * Retrieve the active languages indexed by their public slug and code.
     *
     * @return array<string, array> Associative list of active languages keyed
     *                               by slug and code.
     */
    function wpestate_translation_get_active_languages() {
        // Build an index of active languages by slug and code.
        $languages = array();
        $active    = wpr_translate_get_active_languages();

        foreach ( $active as $language ) {
            // Resolve the public-facing slug for each language.
            $slug = wpr_translate_get_language_slug( $language );

            if ( '' === $slug && ! empty( $language['code'] ) ) {
                $slug = sanitize_title( $language['code'] );
            }

            if ( '' !== $slug ) {
                // Store the language keyed by its slug.
                $languages[ strtolower( $slug ) ] = $language;
            }

            if ( ! empty( $language['code'] ) ) {
                $code = sanitize_title( $language['code'] );

                if ( '' !== $code ) {
                    // Also store the language keyed by its code.
                    $languages[ strtolower( $code ) ] = $language;
                }
            }
        }

        // Return the indexed list used by legacy theme helpers.
        return $languages;
    }
}

if ( ! function_exists( 'wpestate_get_current_language' ) ) {
    /**
     * Determine the visitor's current language slug following the legacy
     * WP Estate logic.
     *
     * @return string Sanitised language slug that represents the visitor
     *                selection.
     */
    function wpestate_get_current_language() {
        // Prefer the plugin language context when available.
        $resolved_slug = '';

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

            if ( is_array( $language ) ) {
                $slug = wpr_translate_get_language_slug( $language );

                if ( '' === $slug && ! empty( $language['code'] ) ) {
                    $slug = sanitize_title( $language['code'] );
                }

                if ( '' !== $slug ) {
                    $resolved_slug = $slug;
                }
            }
        }

        if ( function_exists( 'wpr_translate_get_context_language' ) ) {
            $language = wpr_translate_get_context_language();

            if ( is_array( $language ) ) {
                $slug = wpr_translate_get_language_slug( $language );

                if ( '' === $slug && ! empty( $language['code'] ) ) {
                    $slug = sanitize_title( $language['code'] );
                }

                if ( '' !== $slug ) {
                    $resolved_slug = $slug;
                }
            }
        }

        if ( '' !== $resolved_slug ) {
            // Override cached values when the plugin resolves a language.
            WP_Estate_Translation::$current_language = $resolved_slug;
            return $resolved_slug;
        }

        // Use the cached language when available.
        if ( isset( WP_Estate_Translation::$current_language ) && '' !== WP_Estate_Translation::$current_language ) {
            return WP_Estate_Translation::$current_language;
        }

        // Parse the first request URI segment for a language slug.
        $uri     = isset( $_SERVER['REQUEST_URI'] ) ? trim( wp_unslash( $_SERVER['REQUEST_URI'] ), '/' ) : '';
        $segment = strtolower( (string) strtok( $uri, '/' ) );

        // Check against the active language list.
        $languages = wpestate_translation_get_active_languages();

        if ( '' !== $segment && isset( $languages[ $segment ] ) ) {
            // Cache the detected language slug for future calls.
            WP_Estate_Translation::$current_language = $segment;

            return $segment;
        }

        // Fall back to the stored default language option.
        $default = sanitize_title( get_option( 'wpestate_default_language', 'en' ) );

        if ( '' === $default ) {
            $default = 'en';
        }

        // Cache the default language for future calls.
        WP_Estate_Translation::$current_language = $default;

        return $default;
    }
}

if ( ! function_exists( 'wpr_object_id' ) ) {
    /**
     * Resolve the translated object ID for the current language context.
     *
     * This helper mirrors the expected API from third-party code that calls
     * `apply_filters( 'wpr_object_id', $post_id, $post_type )` to fetch the
     * translated post for the active language. It looks up the desired
     * language based on the current request (front-end or admin) and returns
     * the matching translation when available.
     *
     * @param int    $object_id Original object/post ID.
     * @param string $post_type Post type slug for the object.
     *
     * @return int Translated object ID or the original ID when no translation is found.
     */
    function wpr_object_id( $object_id, $post_type = '' ) {
        // Normalise incoming values to avoid unexpected types.
        $object_id = absint( $object_id );
        $post_type = sanitize_key( $post_type );

        // Bail out early if the input is incomplete.
        if ( ! $object_id || '' === $post_type ) {
            return $object_id;
        }

        // Track the language code to resolve the translation.
        $language_code = '';

        // Prefer the admin-specific language selector when editing content.
        if ( is_admin() && function_exists( 'wpr_translate_return_current_language_admin' ) ) {
            $language_code = sanitize_key( wpr_translate_return_current_language_admin() );
        }

        // Fall back to the resolved front-end language payload when available.
        if ( '' === $language_code && function_exists( 'wpr_translate_get_current_language' ) ) {
            $language = wpr_translate_get_current_language();

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

        // Legacy fallback using the slug helper from the WP Estate theme.
        if ( '' === $language_code && function_exists( 'wpestate_get_current_language' ) ) {
            $language_code = sanitize_key( wpestate_get_current_language() );

            if ( '' !== $language_code && function_exists( 'wpr_translate_get_language' ) ) {
                $resolved = wpr_translate_get_language( $language_code );

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

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

        // Use the post-type aware resolver when available for accurate lookups.
        if ( function_exists( 'wpr_translate_resolve_post_for_language' ) ) {
            return wpr_translate_resolve_post_for_language( $object_id, $post_type, $language_code );
        }

        // Fallback to the generic resolver which relies on the translation group data.
        if ( function_exists( 'wpr_translate_resolve_translated_post_id' ) ) {
            return wpr_translate_resolve_translated_post_id( $object_id, $language_code );
        }

        return $object_id;
    }

    // Expose the helper through a filter for third-party compatibility.
    add_filter( 'wpr_object_id', 'wpr_object_id', 10, 2 );
}

if ( ! function_exists( 'wpr_current_language' ) ) {
    /**
     * Determine the current language slug with a sensible fallback.
     *
     * This helper mirrors the expected API from third-party code that calls
     * `apply_filters( 'wpr_current_language', 'en' )` to fetch the active
     * language. It inspects the admin selection, front-end context, and legacy
     * WP Estate helper before defaulting to the provided fallback.
     *
     * @param string $default Default language code to return when no language
     *                        is detected. Defaults to `en`.
     *
     * @return string Resolved language code.
     */
    function wpr_current_language( $default = 'en' ) {
        // Attempt to read the language chosen in the admin area first.
        $language_code = '';

        if ( is_admin() && function_exists( 'wpr_translate_return_current_language_admin' ) ) {
            $language_code = sanitize_key( wpr_translate_return_current_language_admin() );
        }

        // Use the front-end language payload when available.
        if ( '' === $language_code && function_exists( 'wpr_translate_get_current_language' ) ) {
            $language = wpr_translate_get_current_language();

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

        // Fall back to the legacy helper from the WP Estate theme.
        if ( '' === $language_code && function_exists( 'wpestate_get_current_language' ) ) {
            $language_code = sanitize_key( wpestate_get_current_language() );

            if ( '' !== $language_code && function_exists( 'wpr_translate_get_language' ) ) {
                $resolved = wpr_translate_get_language( $language_code );

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

        // Final fallback to the provided default value.
        if ( '' === $language_code ) {
            $language_code = sanitize_key( $default );
        }

        // Guarantee a non-empty fallback.
        if ( '' === $language_code ) {
            $language_code = 'en';
        }

        return $language_code;
    }

    // Expose the current language helper through a filter for compatibility.
    add_filter( 'wpr_current_language', 'wpr_current_language', 10, 1 );
}
