<?php
/**
 * Navigation menu language controls inside the WordPress admin.
 *
 * @package WPR_Translate
 */

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

if ( ! function_exists( 'wpr_translation_setup_nav_menu_integration' ) ) {
    /**
     * Hooks nav menu integrations on the nav menu management screen.
     */
    function wpr_translation_setup_nav_menu_integration() {
        if ( ! current_user_can( 'edit_theme_options' ) ) {
            // Only allow menu integrations for authorized users.
            return;
        }

        // Register toolbar hooks and menu filtering.
        add_action( 'admin_notices', 'wpr_translation_render_nav_menu_toolbar' );
        add_action( 'admin_enqueue_scripts', 'wpr_translation_enqueue_nav_menu_toolbar_assets' );
        add_filter( 'wp_get_nav_menus', 'wpr_translation_filter_nav_menus_by_language', 10, 2 );
    }

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

if ( ! function_exists( 'wpr_translation_render_nav_menu_toolbar' ) ) {
    /**
     * Renders the language toolbar above the nav menu editor.
     */
    function wpr_translation_render_nav_menu_toolbar() {
        $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;

        if ( ! $screen || 'nav-menus' !== $screen->base ) {
            // Only render on the nav menus screen.
            return;
        }

        $overview = wpr_translation_get_nav_menu_overview();

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

        $current_filter    = wpr_translation_get_current_nav_menu_filter();
        $default_code      = isset( $overview['default'] ) ? $overview['default'] : '';
        $links             = array();
        $all_link_classes  = array( 'wpr-nav-menu-link' );
        $current_action    = isset( $_GET['action'] ) ? sanitize_key( wp_unslash( $_GET['action'] ) ) : '';// phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $base_url          = remove_query_arg(
            array( 'action', 'menu', 'wpr_language' ),
            admin_url( 'nav-menus.php' )
        );
        $base_url          = admin_url( 'nav-menus.php' );


        if ( 'locations' === $current_action ) {
            // Preserve the locations action when present.
            $base_url = add_query_arg( 'action', 'locations', $base_url );
        }

        $all_url = remove_query_arg( 'wpr_language', $base_url );

        if ( '' === $current_filter ) {
            // Highlight the "All languages" link when no filter is active.
            $all_link_classes[] = 'is-active';
        }

        $links[] = sprintf(
            '<div class="%1$s" role="link" tabindex="0" data-wpr-target="%2$s"><span class="wpr-nav-menu-link__label">%3$s</span></div>',
            esc_attr( implode( ' ', $all_link_classes ) ),
            esc_url( $all_url ),
            esc_html( sprintf( __( 'All languages (%d)', 'wpr-translate' ), (int) $overview['total'] ) )
        );

        foreach ( $overview['languages'] as $language ) {
            $code         = strtolower( sanitize_key( $language['code'] ) );
            $name         = ! empty( $language['name'] ) ? sanitize_text_field( $language['name'] ) : $language['code'];
            $count        = isset( $overview['counts'][ $code ] ) ? (int) $overview['counts'][ $code ] : 0;
            $link_classes = array( 'wpr-nav-menu-link' );
            $flag_markup  = '';
            $flag_code    = '';

            if ( $code === $current_filter ) {
                // Mark the active filter.
                $link_classes[] = 'is-active';
            }

            if ( '' === $current_filter && $code === $default_code ) {
                // Mark the default language when no filter is set.
                $link_classes[] = 'is-default';
            }

            if ( ! empty( $language['flag'] ) ) {
                $flag_code = sanitize_key( $language['flag'] );
            } elseif ( ! empty( $language['code'] ) ) {
                $flag_code = sanitize_key( $language['code'] );
            }

            if ( '' !== $flag_code && defined( 'WPR_TRANSLATE_URL' ) ) {
                // Build the flag image markup for the toolbar.
                $flag_url = WPR_TRANSLATE_URL . 'assets/img/flags/4x3/' . $flag_code . '.svg';
                /* translators: %s: Language name. */
                $flag_alt = sprintf( __( '%s flag', 'wpr-translate' ), $name );
                $flag_markup = sprintf(
                    '<span class="wpr-nav-menu-link__flag"><img src="%1$s" alt="%2$s" loading="lazy" decoding="async" width="18" height="14" /></span>',
                    esc_url( $flag_url ),
                    esc_attr( $flag_alt )
                );
            }

            $label_markup = sprintf(
                '<span class="wpr-nav-menu-link__label">%s</span>',
                esc_html( sprintf( '%1$s (%2$d)', $name, $count ) )
            );

            $links[] = sprintf(
                '<div class="%1$s" role="link" tabindex="0" data-wpr-target="%2$s">%3$s%4$s</div>',
                esc_attr( implode( ' ', $link_classes ) ),
                esc_url( add_query_arg( 'wpr_language', $code, $base_url ) ),
                $flag_markup,
                $label_markup
            );
        }

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

        if ( $requested_menu_id > 0 ) {
            // Resolve the stored language for the selected menu.
            $stored_language = get_term_meta( $requested_menu_id, wpr_translation_get_nav_menu_language_meta_key(), true );
            $stored_language = strtolower( sanitize_key( $stored_language ) );

            if ( '' === $stored_language ) {
                // Fall back to the default language when no meta is set.
                $stored_language = $default_code;
            }

            if ( '' !== $stored_language ) {
                $current_menu_language = $stored_language;
            }
        }

        $selected_language = $current_filter;
        $fallback_language = $default_code;

        if ( '' === $selected_language && '' !== $fallback_language ) {
            // Use the default language when no filter is selected.
            $selected_language = $fallback_language;
        }

        $placeholder_label = __( 'Select language', 'wpr-translate' );
        $selected_label    = $placeholder_label;
        $dropdown_options  = array();

        foreach ( $overview['languages'] as $language ) {
            $code        = strtolower( sanitize_key( $language['code'] ) );
            $name        = ! empty( $language['name'] ) ? $language['name'] : $language['code'];
            $is_selected = '' !== $selected_language && $code === $selected_language;

            if ( $is_selected ) {
                // Track the current selection label.
                $selected_label = $name;
            }

            $dropdown_options[] = sprintf(
                '<div class="wpr-nav-menu-dropdown__option%3$s" role="option" tabindex="0" data-value="%1$s">%2$s</div>',
                esc_attr( $code ),
                esc_html( $name ),
                $is_selected ? ' is-selected' : ''
            );
        }

        $is_creating_menu = function_exists( 'wpr_translation_is_creating_nav_menu' ) ? wpr_translation_is_creating_nav_menu() : false;
        $toolbar_attrs    = array(
            'class="notice notice-info wpr-nav-menu-toolbar"',
            'role="region"',
            'data-fallback-language="' . esc_attr( $fallback_language ) . '"',
            'data-is-creating-menu="' . ( $is_creating_menu ? '1' : '0' ) . '"',
        );

        if ( '' !== $selected_language ) {
            $toolbar_attrs[] = 'data-selected-language="' . esc_attr( $selected_language ) . '"';
        }

        if ( '' !== $current_menu_language ) {
            $toolbar_attrs[] = 'data-current-menu-language="' . esc_attr( $current_menu_language ) . '"';
        }

        $debug_entries = isset( $overview['menus'] ) ? $overview['menus'] : array();

        if ( ! empty( $debug_entries ) ) {
            // Render debug information for menu language mappings.
            echo '<div class="notice notice-info wpr-nav-menu-debug">';
            echo '<div class="wpr-nav-menu-debug__title">' . esc_html__( 'Menu language debug', 'wpr-translate' ) . '</div>';

            foreach ( $debug_entries as $entry ) {
                $menu_id          = isset( $entry['id'] ) ? (int) $entry['id'] : 0;
                $menu_name        = isset( $entry['name'] ) ? $entry['name'] : '';
                $effective_code   = isset( $entry['language'] ) ? $entry['language'] : '';
                $stored_code      = isset( $entry['stored_language'] ) ? $entry['stored_language'] : '';
                $effective_output = '' !== $effective_code ? $effective_code : __( 'none', 'wpr-translate' );
                $stored_output    = '' !== $stored_code ? $stored_code : __( 'default', 'wpr-translate' );

                echo '<div class="wpr-nav-menu-debug__row">';
                echo '<div class="wpr-nav-menu-debug__item">' . esc_html( sprintf( __( 'ID: %d', 'wpr-translate' ), $menu_id ) ) . '</div>';
                echo '<div class="wpr-nav-menu-debug__item">' . esc_html( sprintf( __( 'Name: %s', 'wpr-translate' ), $menu_name ) ) . '</div>';
                echo '<div class="wpr-nav-menu-debug__item">' . esc_html( sprintf( __( 'Language: %s (meta: %s)', 'wpr-translate' ), $effective_output, $stored_output ) ) . '</div>';
                echo '</div>';
            }

            echo '</div>';
        }

        echo '<div ' . implode( ' ', $toolbar_attrs ) . '>';
        echo '<div class="wpr-nav-menu-toolbar__links">' . implode( '', $links ) . '</div>';

        if ( $is_creating_menu && ! empty( $dropdown_options ) ) {
            // Show the language selector when creating a new menu.
            echo '<div class="wpr-nav-menu-toolbar__actions">';
            echo '<div class="wpr-nav-menu-toolbar__select">';
            echo '<div class="screen-reader-text">' . esc_html__( 'Menu language', 'wpr-translate' ) . '</div>';
            echo '<div class="wpr-nav-menu-dropdown" data-selected="' . esc_attr( $selected_language ) . '" data-placeholder="' . esc_attr( $placeholder_label ) . '" data-fallback="' . esc_attr( $fallback_language ) . '">';
            echo '<div class="wpr-nav-menu-dropdown__label" role="button" tabindex="0">' . esc_html( $selected_label ) . '</div>';
            echo '<div class="wpr-nav-menu-dropdown__list" hidden>' . implode( '', $dropdown_options ) . '</div>';
            echo '</div>';
            echo '</div>';
            echo '</div>';
        }

        echo '</div>';
    }
}

if ( ! function_exists( 'wpr_translation_enqueue_nav_menu_toolbar_assets' ) ) {
    /**
     * Enqueues toolbar scripts and styles on the nav menu screen.
     *
     * @param string $hook Current admin hook name.
     */
    function wpr_translation_enqueue_nav_menu_toolbar_assets( $hook ) {
        if ( 'nav-menus.php' !== $hook ) {
            // Only load assets on the nav menus screen.
            return;
        }

        if ( ! current_user_can( 'edit_theme_options' ) ) {
            // Require edit permissions.
            return;
        }

        $overview = wpr_translation_get_nav_menu_overview();

        if ( empty( $overview['languages'] ) ) {
            // No languages means no toolbar assets needed.
            return;
        }

        // Enqueue toolbar styles and scripts.
        wp_enqueue_style(
            'wpr-translate-nav-menus-toolbar',
            WPR_TRANSLATE_PLUGIN_URL . 'assets/css/nav-menus-toolbar.css',
            array(),
            WPR_TRANSLATE_VERSION
        );

        wp_enqueue_script(
            'wpr-translate-nav-menus-toolbar',
            WPR_TRANSLATE_PLUGIN_URL . 'assets/js/nav-menus-toolbar.js',
            array(),
            WPR_TRANSLATE_VERSION,
            true
        );
    }
}

