<?php
/**
 * Helper functions supporting the nav menu translation UI.
 *
 * @package WPR_Translate
 */

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

if ( ! function_exists( 'wpr_translation_get_nav_menu_language_meta_key' ) ) {
    /**
     * Returns the term meta key storing menu language assignments.
     *
     * @return string
     */
    function wpr_translation_get_nav_menu_language_meta_key() {
        return 'wpr_menu_language';
    }
}

if ( ! function_exists( 'wpr_translation_get_nav_menu_overview' ) ) {
    /**
     * Collects navigation menu counts and language metadata for the toolbar UI.
     *
     * @return array
     */
    function wpr_translation_get_nav_menu_overview() {
        static $cache = null;

        if ( null !== $cache ) {
            // Return cached overview for this request.
            return $cache;
        }

        $languages = array();

        if ( function_exists( 'wpestate_translation_get_active_languages' ) ) {
            $languages = wpestate_translation_get_active_languages();
        } elseif ( function_exists( 'wpr_translation_get_active_languages' ) ) {
            $languages = wpr_translation_get_active_languages();
        }

        if ( empty( $languages ) ) {
            // Provide a default empty structure when no languages exist.
            $cache = array(
                'languages' => array(),
                'counts'    => array(),
                'default'   => '',
                'total'     => 0,
            );

            return $cache;
        }

        $language_map = array();

        foreach ( $languages as $language ) {
            if ( empty( $language['code'] ) ) {
                continue;
            }

            $code = strtolower( sanitize_key( $language['code'] ) );

            if ( '' === $code || isset( $language_map[ $code ] ) ) {
                // Skip invalid or duplicate language codes.
                continue;
            }

            $language_map[ $code ] = $language;
        }

        $default_code = '';

        if ( function_exists( 'wpr_translation_get_default_language_code' ) ) {
            // Resolve the default language code.
            $default_code = strtolower( sanitize_key( wpr_translation_get_default_language_code( $languages ) ) );
        }

        $counts       = array();
        $menu_records = array();

        foreach ( array_keys( $language_map ) as $code ) {
            $counts[ $code ] = 0;
        }

        $menus = get_terms(
            array(
                'taxonomy'   => 'nav_menu',
                'hide_empty' => false,
            )
        );

        $total = 0;

        if ( ! is_wp_error( $menus ) ) {
            // Aggregate menu counts per language.
            foreach ( $menus as $menu ) {
                if ( ! $menu instanceof WP_Term ) {
                    continue;
                }

                $total++;

                $stored_language = get_term_meta( $menu->term_id, wpr_translation_get_nav_menu_language_meta_key(), true );
                $stored_language = strtolower( sanitize_key( $stored_language ) );
                $language_code   = $stored_language;

                if ( '' === $language_code ) {
                    // Fall back to default language when none is stored.
                    $language_code = $default_code;
                }

                if ( '' !== $language_code ) {
                    if ( ! isset( $counts[ $language_code ] ) ) {
                        $counts[ $language_code ] = 0;
                    }

                    $counts[ $language_code ]++;
                }

                $menu_records[] = array(
                    'id'               => (int) $menu->term_id,
                    'name'             => $menu->name,
                    'language'         => $language_code,
                    'stored_language'  => $stored_language,
                );
            }
        }

        $cache = array(
            'languages' => array_values( $language_map ),
            'counts'    => $counts,
            'default'   => $default_code,
            'total'     => $total,
            'menus'     => $menu_records,
        );

        return $cache;
    }
}

if ( ! function_exists( 'wpr_translation_get_current_nav_menu_filter' ) ) {
    /**
     * Retrieves the currently requested language filter for the menu screen.
     *
     * @return string
     */
    function wpr_translation_get_current_nav_menu_filter() {
        // Read the language filter from the request.
        $requested = isset( $_GET['wpr_language'] ) ? sanitize_key( wp_unslash( $_GET['wpr_language'] ) ) : '';// phpcs:ignore WordPress.Security.NonceVerification.Recommended

        if ( '' === $requested && is_admin() ) {
            global $pagenow;

            if ( isset( $pagenow ) && 'nav-menus.php' === $pagenow && isset( $_GET['menu'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                $menu_id = absint( $_GET['menu'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended

                if ( $menu_id > 0 ) {
                    // Respect the menu's stored language when no filter is provided.
                    $menu_language = get_term_meta( $menu_id, wpr_translation_get_nav_menu_language_meta_key(), true );
                    $menu_language = strtolower( sanitize_key( $menu_language ) );

                    if ( '' === $menu_language && function_exists( 'wpr_translation_get_nav_menu_language_code' ) ) {
                        $menu_language = wpr_translation_get_nav_menu_language_code( $menu_id );
                    }

                    if ( '' !== $menu_language ) {
                        $requested = $menu_language;
                    }
                }
            }
        }

        if ( '' === $requested && function_exists( 'wpr_translate_get_admin_selected_language_code' ) ) {
            // Fall back to the user's admin language preference.
            $requested = wpr_translate_get_admin_selected_language_code();
        }

        if ( '' === $requested ) {
            // No filter requested.
            return '';
        }

        $overview = wpr_translation_get_nav_menu_overview();

        if ( empty( $overview['languages'] ) ) {
            // No languages available for filtering.
            return '';
        }

        $requested = strtolower( $requested );

        foreach ( $overview['languages'] as $language ) {
            if ( strtolower( sanitize_key( $language['code'] ) ) === $requested ) {
                return $requested;
            }
        }

        return '';
    }
}

if ( ! function_exists( 'wpr_translation_is_creating_nav_menu' ) ) {
    /**
     * Determines whether the current screen is creating a new nav menu.
     *
     * @return bool
     */
    function wpr_translation_is_creating_nav_menu() {
        // Determine whether the current request is creating a new menu.
        $action = isset( $_GET['action'] ) ? sanitize_key( wp_unslash( $_GET['action'] ) ) : '';// phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $menu   = isset( $_GET['menu'] ) ? absint( $_GET['menu'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

        return ( 'edit' === $action && 0 === $menu );
    }
}

if ( ! function_exists( 'wpr_translation_filter_nav_menus_by_language' ) ) {
    /**
     * Filters `wp_get_nav_menus()` results based on the requested language filter.
     *
     * @param array $menus Nav menu list.
     * @param array $args  Query arguments.
     *
     * @return array
     */
    function wpr_translation_filter_nav_menus_by_language( $menus, $args ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedParameter
        // Apply language filtering when requested.
        $language_filter = wpr_translation_get_current_nav_menu_filter();

        if ( '' === $language_filter ) {
            // No filter means return all menus.
            return $menus;
        }

        $filtered = array();
        $overview = wpr_translation_get_nav_menu_overview();
        $default  = $overview['default'];

        foreach ( $menus as $menu ) {
            if ( ! $menu instanceof WP_Term ) {
                $filtered[] = $menu;
                continue;
            }

            $language_code = get_term_meta( $menu->term_id, wpr_translation_get_nav_menu_language_meta_key(), true );
            $language_code = strtolower( sanitize_key( $language_code ) );

            if ( '' === $language_code ) {
                // Default to the overview default language.
                $language_code = $default;
            }

            if ( $language_filter === $language_code ) {
                $filtered[] = $menu;
            }
        }

        return $filtered;
    }
}

if ( ! function_exists( 'wpr_translation_store_nav_menu_language' ) ) {
    /**
     * Persists the selected menu language when a nav menu is created or saved.
     *
     * @param int   $menu_id   Menu identifier.
     * @param array $menu_data Menu data payload.
     */
    function wpr_translation_store_nav_menu_language( $menu_id, $menu_data = array() ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedParameter
        if ( ! $menu_id || ! current_user_can( 'edit_theme_options' ) ) {
            // Require a valid menu ID and capability.
            return;
        }

        $language_code = '';

        if ( isset( $_POST['wpr_menu_language'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
            // Prefer the language posted from the menu form.
            $language_code = sanitize_key( wp_unslash( $_POST['wpr_menu_language'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
        } elseif ( isset( $_GET['wpr_language'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            // Fall back to the query string.
            $language_code = sanitize_key( wp_unslash( $_GET['wpr_language'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        }
        $overview      = wpr_translation_get_nav_menu_overview();
        $valid_codes   = array();

        foreach ( $overview['languages'] as $language ) {
            // Build a list of valid codes for validation.
            $valid_codes[] = strtolower( sanitize_key( $language['code'] ) );
        }

        if ( '' !== $language_code && ! in_array( $language_code, $valid_codes, true ) ) {
            // Reset invalid codes.
            $language_code = '';
        }

        if ( '' === $language_code && ! empty( $overview['default'] ) ) {
            // Fall back to the default language.
            $language_code = $overview['default'];
        }

        if ( '' !== $language_code ) {
            // Store the language selection on the menu term.
            update_term_meta( $menu_id, wpr_translation_get_nav_menu_language_meta_key(), $language_code );
            if ( function_exists( 'wpr_translation_ensure_nav_menu_translation_record' ) ) {
                // Ensure a translation record is created when needed.
                wpr_translation_ensure_nav_menu_translation_record( $menu_id, $language_code );
            }
        } else {
            // Clear the menu language assignment.
            delete_term_meta( $menu_id, wpr_translation_get_nav_menu_language_meta_key() );
        }
    }

    add_action( 'wp_create_nav_menu', 'wpr_translation_store_nav_menu_language', 10, 2 );
    add_action( 'wp_update_nav_menu', 'wpr_translation_store_nav_menu_language', 10, 2 );
}

