<?php
/**
 * Language utilities supporting nav menu selection and filtering.
 *
 * @package WPR_Translate
 */

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

if ( ! function_exists( 'wpr_translation_get_nav_menu_language_code' ) ) {
    /**
     * Retrieves the effective language code for a nav menu.
     *
     * @param int $menu_id Menu identifier.
     *
     * @return string
     */
    function wpr_translation_get_nav_menu_language_code( $menu_id ) {
        // Normalize the menu ID.
        $menu_id = absint( $menu_id );

        if ( $menu_id <= 0 ) {
            // No valid menu ID means no language.
            return '';
        }

        // Load the stored menu language.
        $language_code = get_term_meta( $menu_id, wpr_translation_get_nav_menu_language_meta_key(), true );
        $language_code = strtolower( sanitize_key( $language_code ) );

        if ( '' !== $language_code ) {
            // Return stored language when available.
            return $language_code;
        }

        $overview = wpr_translation_get_nav_menu_overview();

        if ( empty( $overview['default'] ) ) {
            // No default language configured.
            return '';
        }

        return $overview['default'];
    }
}

if ( ! function_exists( 'wpr_translation_adjust_selected_nav_menu' ) ) {
    /**
     * Ensures the selected nav menu matches the active language filter.
     *
     * @param int $selected_id Currently selected menu identifier.
     *
     * @return int
     */
    function wpr_translation_adjust_selected_nav_menu( $selected_id ) {
        // Adjust menu selection based on the language filter.
        $language_filter = wpr_translation_get_current_nav_menu_filter();

        if ( '' === $language_filter ) {
            // No filter applied.
            return $selected_id;
        }

        $selected_id = absint( $selected_id );

        if ( $selected_id > 0 ) {
            $current_language = wpr_translation_get_nav_menu_language_code( $selected_id );

            if ( $language_filter === $current_language ) {
                // Keep the selection when language matches.
                return $selected_id;
            }
        }

        $overview      = wpr_translation_get_nav_menu_overview();
        $matching_menu = 0;

        if ( ! empty( $overview['menus'] ) ) {
            // Find the first menu matching the filter.
            foreach ( $overview['menus'] as $entry ) {
                $entry_id   = isset( $entry['id'] ) ? (int) $entry['id'] : 0;
                $entry_lang = isset( $entry['language'] ) ? $entry['language'] : '';

                if ( $entry_id > 0 && $entry_lang === $language_filter ) {
                    $matching_menu = $entry_id;
                    break;
                }
            }
        }

        return $matching_menu;
    }

    add_filter( 'nav_menu_selected_id', 'wpr_translation_adjust_selected_nav_menu' );
}

if ( ! function_exists( 'wpr_translation_enforce_nav_menu_language_context' ) ) {
    /**
     * Prevents editing nav menus that do not match the active language filter.
     */
    function wpr_translation_enforce_nav_menu_language_context() {
        if ( ! current_user_can( 'edit_theme_options' ) ) {
            // Only admins can edit menus.
            return;
        }

        $language_filter = wpr_translation_get_current_nav_menu_filter();

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

        $has_menu_param = isset( $_GET['menu'] );
        $requested_menu = $has_menu_param ? absint( $_GET['menu'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

        if ( $requested_menu <= 0 && ! $has_menu_param ) {
            // Use the most recently edited menu when none is specified.
            $recent_menu = get_user_option( 'nav_menu_recently_edited' );

            if ( $recent_menu ) {
                $requested_menu = (int) $recent_menu;
            }
        }

        $current_action = isset( $_GET['action'] ) ? sanitize_key( wp_unslash( $_GET['action'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

        if ( $has_menu_param && 0 === $requested_menu && 'edit' === $current_action ) {
            // Allow the create-new menu state.
            return;
        }

        $current_language = wpr_translation_get_nav_menu_language_code( $requested_menu );
        $stored_language  = get_term_meta( $requested_menu, wpr_translation_get_nav_menu_language_meta_key(), true );
        $stored_language  = strtolower( sanitize_key( $stored_language ) );

        if ( $language_filter === $current_language ) {
            // Requested menu already matches the filter.
            return;
        }

        if ( '' === $stored_language && '' !== $language_filter ) {
            // Do not redirect when the menu lacks a language assignment yet.
            return;
        }

        $overview      = wpr_translation_get_nav_menu_overview();
        $matching_menu = 0;

        if ( ! empty( $overview['menus'] ) ) {
            // Search for a menu that matches the requested language.
            foreach ( $overview['menus'] as $entry ) {
                $entry_id   = isset( $entry['id'] ) ? (int) $entry['id'] : 0;
                $entry_lang = isset( $entry['language'] ) ? $entry['language'] : '';

                if ( $entry_id > 0 && $entry_lang === $language_filter ) {
                    $matching_menu = $entry_id;
                    break;
                }
            }
        }

        $current_menu_param = $has_menu_param ? absint( $_GET['menu'] ) : null; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $query_args         = array(
            'wpr_language' => $language_filter,
        );
        $needs_redirect     = false;

        if ( $matching_menu > 0 ) {
            // Redirect to the matching menu if available.
            $query_args['menu'] = $matching_menu;

            if ( null === $current_menu_param || $current_menu_param !== $matching_menu ) {
                $needs_redirect = true;
            }

            if ( 'edit' === $current_action ) {
                $query_args['action'] = 'edit';
            } elseif ( '' !== $current_action ) {
                $query_args['action'] = $current_action;
            }
        } else {
            // Force the empty editor state when no matching menu exists.
            $query_args['menu']   = 0;
            $query_args['action'] = 'edit';

            if ( null === $current_menu_param || 0 !== $current_menu_param ) {
                $needs_redirect = true;
            }

            if ( 'edit' !== $current_action ) {
                $needs_redirect = true;
            }
        }

        if ( ! $needs_redirect ) {
            // Current URL already matches the intended state.
            return;
        }

        $redirect_url = add_query_arg( $query_args, admin_url( 'nav-menus.php' ) );

        wp_safe_redirect( $redirect_url );
        exit;
    }

    add_action( 'load-nav-menus.php', 'wpr_translation_enforce_nav_menu_language_context', 5 );
}

if ( ! function_exists( 'wpr_translation_filter_recently_edited_nav_menu_option' ) ) {
    /**
     * Adjusts the cached "recently edited" nav menu to respect the active language filter.
     *
     * @param mixed $value   Short-circuit value for the user option.
     * @param int   $user_id User identifier.
     * @param string $option Option name.
     *
     * @return mixed
     */
    function wpr_translation_filter_recently_edited_nav_menu_option( $value, $user_id, $option ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedParameter
        if ( ! current_user_can( 'edit_theme_options' ) ) {
            // Respect permissions for menu editing.
            return $value;
        }

        $language_filter = wpr_translation_get_current_nav_menu_filter();

        if ( '' === $language_filter ) {
            // No language filter applied.
            return $value;
        }

        $has_menu_param = isset( $_GET['menu'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended

        if ( $has_menu_param ) {
            $menu_param = absint( $_GET['menu'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended

            if ( $menu_param > 0 ) {
                // Keep current menu when it matches the filter.
                $menu_language = wpr_translation_get_nav_menu_language_code( $menu_param );

                if ( $language_filter === $menu_language ) {
                    return $value;
                }
            } else {
                $action = isset( $_GET['action'] ) ? sanitize_key( wp_unslash( $_GET['action'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

                if ( 'edit' === $action ) {
                    // Allow the "new menu" state.
                    return 0;
                }
            }
        }

        $overview = wpr_translation_get_nav_menu_overview();

        if ( empty( $overview['menus'] ) ) {
            // No menus available for the requested language.
            return 0;
        }

        foreach ( $overview['menus'] as $entry ) {
            $entry_id   = isset( $entry['id'] ) ? (int) $entry['id'] : 0;
            $entry_lang = isset( $entry['language'] ) ? $entry['language'] : '';

            if ( $entry_id > 0 && $entry_lang === $language_filter ) {
                // Return the matching menu ID.
                return $entry_id;
            }
        }

        return 0;
    }

    add_filter( 'pre_user_option_nav_menu_recently_edited', 'wpr_translation_filter_recently_edited_nav_menu_option', 10, 3 );
}
