<?php


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

function reeid_add_settings_page() {

    add_options_page(
        __( 'REEID Translate Settings', 'reeid-translate' ),
        __( 'REEID Translate', 'reeid-translate' ),
        'manage_options',
        'reeid-translate-settings',
        'reeid_render_settings_page'
    );
}

/* =============================================================================
   FAQ TAB — Enterprise Documentation Hub
   ============================================================================= */
function reeid_render_faq_tab() {

    if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
        echo '<div class="notice notice-error"><p>' .
            esc_html__( 'Unauthorized.', 'reeid-translate' ) .
        '</p></div>';
        return;
    }

    $sections = array(

       /* ============================================================= */
'getting_started' => array(
	'title' => '🚀 ' . __( 'Getting Started', 'reeid-translate' ),
	'items' => array(
		array(
			'q' => __( 'How do I translate a post or page?', 'reeid-translate' ),
			'a' => __( 'Open the REEID Translate panel inside the editor, choose your target language, and click Translate. If a translation already exists, REEID updates it safely instead of creating unnecessary duplicates. The plugin supports Gutenberg, Classic Editor, and WooCommerce product translation workflows in the free version, so the workflow stays simple while the underlying translation logic remains focused and safe.', 'reeid-translate' ),
		),
		array(
			'q' => __( 'What gets translated?', 'reeid-translate' ),
			'a' => __( 'REEID can translate titles, slugs, body content, supported editor blocks, SEO fields, menus, and WooCommerce product content. The goal is not only linguistic translation, but also structural preservation, so the translated version remains visually and technically aligned with the original.', 'reeid-translate' ),
		),
		array(
			'q' => __( 'Which editors are supported?', 'reeid-translate' ),
			'a' => __( 'REEID Translate Free supports Gutenberg, Classic Editor, and WooCommerce product translation workflows. Each supported content type uses dedicated extraction and reinjection logic, helping preserve layout, block structure, metadata, and product content more safely than generic copy-and-replace translation tools.', 'reeid-translate' ),
		),
		array(
			'q' => __( 'Does REEID Translate work with my theme?', 'reeid-translate' ),
			'a' => __( 'REEID Translate is built to work with standard WordPress themes and common WordPress layouts. Compatibility has been checked with Astra, Twenty Twenty-Five, GeneratePress, Kadence, and Blocksy. In some themes, especially those using custom header builders, correct menu or switcher behavior may depend on proper theme menu-location assignment or header placement rather than translation logic itself. When theme-specific adjustments are needed, they are kept minimal and isolated to avoid affecting other themes.', 'reeid-translate' ),
		),
		array(
			'q' => __( 'Why is my menu still showing English even though page translation works?', 'reeid-translate' ),
			'a' => __( 'In some themes, especially header-builder themes, this may happen when the active header menu location is not assigned to the intended navigation menu. In that case, the theme may fall back to a default page list, which is separate from REEID menu-label translation. Before assuming translation failed, check your theme menu locations and header builder assignments.', 'reeid-translate' ),
		),
		array(
			'q' => __( 'Where are translations stored?', 'reeid-translate' ),
			'a' => __( 'REEID works with native WordPress structures and metadata relationships instead of depending on large shadow systems or fragile content duplication layers. This keeps the architecture cleaner, easier to maintain, and more compatible with long-term WordPress site growth.', 'reeid-translate' ),
		),
		array(
			'q' => __( 'Can I re-translate safely?', 'reeid-translate' ),
			'a' => __( 'Yes. Re-running translation is designed to update the existing translated version safely while preserving relationships, structure, and continuity. This makes refinement and iteration practical, especially when improving prompts, terminology, or content quality over time.', 'reeid-translate' ),
		),
		array(
			'q' => __( 'Why can the first translation take longer?', 'reeid-translate' ),
			'a' => __( 'The first translation may take longer because REEID analyzes the content structure, prepares translatable text, and generates the translated version while preserving the original layout as much as possible.', 'reeid-translate' ),
		),
		array(
			'q' => __( 'Why does the translated page keep the same layout?', 'reeid-translate' ),
			'a' => __( 'REEID is intentionally built to preserve visual and structural integrity. Rather than rebuilding layouts manually, it translates the text layer while respecting the original editor structure. This helps protect design consistency, reduce breakage risk, and maintain a more reliable editorial workflow across languages.', 'reeid-translate' ),
		),
		array(
			'q' => __( 'How and where should I place the language switcher?', 'reeid-translate' ),
			'a' => __( 'The switcher can be placed wherever your theme or builder allows it, such as header areas, menus, widget zones, shortcode-friendly blocks, or theme text elements. In some builder-based themes, switcher placement depends on the theme header system rather than the translation engine itself, so placement options may differ between themes. To do so, use this shortcode: [reeid_language_switcher] ', 'reeid-translate' ),
		),
        array(
            'q' => __( 'REEID Translate and WordPress Multisite', 'reeid-translate' ),
            'a' => __( 'REEID Translate can be activated across a multisite network, but it operates independently on each subsite. Each subsite has its own settings page, API configuration, languages, and translation data.', 'reeid-translate' ),
        ),
		array(
			'q' => __( 'How does REEID translate WooCommerce products?', 'reeid-translate' ),
			'a' => __( 'REEID uses a more refined WooCommerce strategy than simple duplication. Instead of creating unnecessary product copies, it translates language-specific content in a controlled way that keeps product relationships cleaner and more compatible with the wider WooCommerce ecosystem. Titles, descriptions, attributes, SEO fields, and localized slugs can all be translated while pricing, stock, and product configuration remain untouched.', 'reeid-translate' ),
		),
	),
),
        
        /* ============================================================= */
        'seo' => array(
            'title' => '🌍 ' . __( 'SEO & Indexing', 'reeid-translate' ),
            'items' => array(
                array(
                    'q' => __( 'Will search engines index translated pages correctly?', 'reeid-translate' ),
                    'a' => __( 'Yes. REEID is built with multilingual SEO in mind and can output language-aware URLs, hreflang relationships, and canonical logic that help translated content remain discoverable and properly separated in search engines.', 'reeid-translate' ),
                ),
                array(
                    'q' => __( 'Is REEID compatible with Yoast and Rank Math?', 'reeid-translate' ),
                    'a' => __( 'Yes. REEID is designed to coexist with major SEO plugins while keeping multilingual SEO output disciplined and controlled. The objective is not simply compatibility, but cleaner interoperability with reduced risk of duplicate emitters or conflicting signals.', 'reeid-translate' ),
                ),
                array(
                    'q' => __( 'Are native slugs preserved?', 'reeid-translate' ),
                    'a' => __( 'Yes. REEID is designed to support native-language slugs where appropriate, including languages such as Chinese, Thai, Arabic, and Greek. This helps preserve authenticity, improve usability for local audiences, and support a more natural multilingual SEO structure.', 'reeid-translate' ),
                ),
                array(
                    'q' => __( 'How are duplicate SEO issues avoided?', 'reeid-translate' ),
                    'a' => __( 'REEID treats SEO as a discipline, not an afterthought. Its multilingual logic is structured to keep branches isolated, relationships clear, and canonical behavior more predictable. The result is a more controlled SEO environment with less risk of noisy or contradictory signals.', 'reeid-translate' ),
                ),
            ),
        ),

        /* ============================================================= */
        'errors' => array(
            'title' => '⚠️ ' . __( 'Common Error Messages', 'reeid-translate' ),
            'items' => array(
                array(
                    'q' => __( '“AJAX failed. Try again.”', 'reeid-translate' ),
                    'a' => __( 'This usually indicates a technical interruption in the request path, such as a nonce mismatch, timeout, memory limit issue, or translation engine error. In most cases the best next step is to review the debug log and confirm that the request payload and API credentials are valid.', 'reeid-translate' ),
                ),
                array(
                    'q' => __( '“Translation engine not available.”', 'reeid-translate' ),
                    'a' => __( 'This message typically means the translation engine was not loaded correctly, the request context was incomplete, or the system blocked execution before a valid translation call could be made.', 'reeid-translate' ),
                ),
                array(
                    'q' => __( '“Missing parameters.”', 'reeid-translate' ),
                    'a' => __( 'This means the request did not contain one or more required values, such as target language, post ID, nonce, or another essential field needed by the translation workflow.', 'reeid-translate' ),
                ),
            ),
        ),

        /* ============================================================= */
        'performance' => array(
            'title' => '⚡ ' . __( 'Performance & Memory', 'reeid-translate' ),
            'items' => array(
                array(
                    'q' => __( 'Does REEID slow down the frontend?', 'reeid-translate' ),
                    'a' => __( 'REEID is designed to keep frontend impact low. Heavy translation work happens in controlled admin or AJAX workflows, while the frontend primarily consumes already stored data and multilingual SEO signals. This separation helps maintain a more production-friendly performance profile.', 'reeid-translate' ),
                ),
                array(
                    'q' => __( 'How does REEID manage translation workload?', 'reeid-translate' ),
                    'a' => __( 'REEID performs translation work through controlled admin and AJAX workflows instead of running heavy translation tasks on normal frontend page loads. This helps keep visitor-facing performance more predictable while translation work is handled from the WordPress admin area.', 'reeid-translate' ),
                ),
                array(
                    'q' => __( 'What PHP settings are recommended?', 'reeid-translate' ),
                    'a' => __( 'For more comfortable operation, PHP 8.1 or higher is recommended, along with a memory limit of at least 256M. For heavier translation workloads or larger content-heavy sites, 512M provides a stronger margin of stability.', 'reeid-translate' ),
                ),
            ),
        ),

        /* ============================================================= */
        'security' => array(
            'title' => '🔒 ' . __( 'Security & Data Handling', 'reeid-translate' ),
            'items' => array(
                array(
                    'q' => __( 'Is communication encrypted?', 'reeid-translate' ),
                    'a' => __( 'Yes. External communication is performed over secure HTTPS channels using authenticated request patterns appropriate to the workflow.', 'reeid-translate' ),
                ),
                array(
                    'q' => __( 'Is content stored permanently on external servers?', 'reeid-translate' ),
                    'a' => __( 'REEID is designed around processing content for translation rather than treating external services as long-term content storage. The intention is controlled translation handling, not permanent offsite archiving of your editorial content.', 'reeid-translate' ),
                ),
                array(
                    'q' => __( 'Does REEID modify WordPress core?', 'reeid-translate' ),
                    'a' => __( 'No. REEID works through WordPress hooks, options, metadata, and content relationships without modifying core files. This keeps the plugin aligned with WordPress extension best practices and makes maintenance significantly safer.', 'reeid-translate' ),
                ),
                array(
                    'q' => __( 'Is REEID Translate fully functional?', 'reeid-translate' ),
                    'a' => __( 'Yes. REEID Translate provides the WordPress translation workflows included in this package as fully available functionality.', 'reeid-translate' ),
                ),
            ),
        ),

        /* ============================================================= */
        'developer' => array(
            'title' => '🛠 ' . __( 'Developer Hooks & Extensibility', 'reeid-translate' ),
            'items' => array(
                array(
                    'q' => __( 'Can developers customize behavior?', 'reeid-translate' ),
                    'a' => __( 'Yes. REEID is designed to be extensible. Internal hooks, filters, and integration points can be used to influence prompt behavior, tone selection, SEO handling, slug logic, and other workflow-specific decisions.', 'reeid-translate' ),
                ),
                array(
                    'q' => __( 'Can translation be triggered programmatically?', 'reeid-translate' ),
                    'a' => __( 'Yes. Controlled programmatic workflows are possible through internal functions and AJAX-based entry points, making REEID suitable for more advanced editorial, operational, or custom integration scenarios.', 'reeid-translate' ),
                ),
            ),
        ),

        /* ============================================================= */
        'positioning' => array(
            'title' => '📌 ' . __( 'Why REEID Translate?', 'reeid-translate' ),
            'items' => array(
                array(
                    'q' => __( 'How is REEID different from traditional multilingual plugins?', 'reeid-translate' ),
                    'a' => __( 'REEID is built for a more modern multilingual workflow — one centered on AI automation, structural integrity, and SEO precision. Rather than relying on heavy manual language management, duplicate content trees, or complex synchronization layers, REEID works closer to native WordPress architecture and the realities of today’s editor ecosystems. The result is a cleaner, more scalable translation framework that preserves layout, reduces operational friction, and supports high-quality multilingual growth with significantly less overhead.', 'reeid-translate' ),
                ),
                array(
                    'q' => __( 'Does REEID replace WPML or Polylang?', 'reeid-translate' ),
                    'a' => __( 'REEID is not trying to imitate every traditional multilingual framework. It is purpose-built for a different philosophy: automation first, structural safety by design, and cleaner multilingual SEO control. For teams that want a lighter, more AI-native translation workflow with less manual overhead, REEID offers a distinctly more modern operating model.', 'reeid-translate' ),
                ),
                array(
                    'q' => __( 'Who is REEID best suited for?', 'reeid-translate' ),
                    'a' => __( 'REEID is especially well suited to site owners, agencies, product teams, and businesses that want multilingual scale without inheriting unnecessary complexity. It is ideal for projects where layout preservation, SEO discipline, and efficient AI-assisted production matter more than maintaining a heavy editorial translation bureaucracy.', 'reeid-translate' ),
                ),
            ),
        ),
    );

    ?>

    <div class="reeid-faq-wrapper">

        <div class="reeid-faq-header">
            <h2><?php esc_html_e( 'REEID Translate — Documentation Hub', 'reeid-translate' ); ?></h2>
            <div class="reeid-faq-actions">
                <button id="reeid-open-all" class="button button-secondary"><?php esc_html_e( 'Open All', 'reeid-translate' ); ?></button>
                <button id="reeid-close-all" class="button button-secondary"><?php esc_html_e( 'Close All', 'reeid-translate' ); ?></button>
            </div>
        </div>

        <input
            type="text"
            id="reeid-faq-search"
            placeholder="<?php esc_attr_e( 'Search documentation...', 'reeid-translate' ); ?>"
        />

        <?php foreach ( $sections as $section_key => $section ) : ?>

            <div class="reeid-faq-card">
                <h3><?php echo esc_html( $section['title'] ); ?></h3>

                <?php foreach ( $section['items'] as $i => $item ) : ?>
                    <?php $id = 'faq-' . esc_attr( $section_key ) . '-' . $i; ?>

                    <div class="reeid-faq-item">
                        <div class="reeid-faq-question" data-target="<?php echo esc_attr( $id ); ?>">
                            <span><?php echo esc_html( $item['q'] ); ?></span>
                            <span class="reeid-chevron">›</span>
                        </div>
                        <div id="<?php echo esc_attr( $id ); ?>" class="reeid-faq-answer">
                            <?php echo wp_kses_post( wpautop( $item['a'] ) ); ?>
                        </div>
                    </div>

                <?php endforeach; ?>
            </div>

        <?php endforeach; ?>

    </div>


    
    <?php
}
/* =============================================================================
   INFO TAB RENDERER — Professional Edition
   ============================================================================= */
function reeid_render_info_tab() {

    if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
        echo '<div class="notice notice-error"><p>' .
            esc_html__( 'Unauthorized.', 'reeid-translate' ) .
        '</p></div>';
        return;
    }

    $url = 'https://reeid.com/';
    $version = defined( 'REEID_TRANSLATE_VERSION' ) ? REEID_TRANSLATE_VERSION : '—';
    ?>

    <div class="reeid-info-tab" style="max-width:900px;">

        <h2>🌍 <?php esc_html_e( 'About REEID Translate', 'reeid-translate' ); ?></h2>

        <p>
        <?php esc_html_e(
            'REEID Translate is an AI-driven multilingual plugin built for modern WordPress environments. It focuses on automation, structural safety, and SEO integrity while preserving native WordPress architecture.',
            'reeid-translate'
        ); ?>
        </p>

        <hr>

        <h3>🚀 <?php esc_html_e( 'Core Capabilities', 'reeid-translate' ); ?></h3>

        <ul>
            <li><?php esc_html_e( 'AI-powered translation workflows', 'reeid-translate' ); ?></li>
            <li><?php esc_html_e( 'Gutenberg, Classic Editor & WooCommerce support', 'reeid-translate' ); ?></li>
            <li><?php esc_html_e( 'SEO-safe hreflang and canonical isolation', 'reeid-translate' ); ?></li>
            <li><?php esc_html_e( 'Native Unicode slug preservation', 'reeid-translate' ); ?></li>
            <li><?php esc_html_e( 'Controlled admin-side translation workflow', 'reeid-translate' ); ?></li>
            <li><?php esc_html_e( 'Lightweight architecture (no shadow DB tables)', 'reeid-translate' ); ?></li>
        </ul>

        <hr>

        <h3>🧠 <?php esc_html_e( 'Architectural Principles', 'reeid-translate' ); ?></h3>

        <ul>
            <li><?php esc_html_e( 'Uses native WordPress post storage and metadata mapping', 'reeid-translate' ); ?></li>
            <li><?php esc_html_e( 'Strict SEO branch isolation (Pages vs Woo)', 'reeid-translate' ); ?></li>
            <li><?php esc_html_e( 'Editor-aware translation engines', 'reeid-translate' ); ?></li>
            <li><?php esc_html_e( 'WordPress.org compliant sanitization & security practices', 'reeid-translate' ); ?></li>
        </ul>

        <hr>

        <h3>📦 <?php esc_html_e( 'System Information', 'reeid-translate' ); ?></h3>

        <table class="widefat striped" style="max-width:600px;">
            <tbody>
                <tr>
                    <td><strong><?php esc_html_e( 'Plugin Version', 'reeid-translate' ); ?></strong></td>
                    <td><?php echo esc_html( $version ); ?></td>
                </tr>
                <tr>
                    <td><strong><?php esc_html_e( 'WordPress Version', 'reeid-translate' ); ?></strong></td>
                    <td><?php echo esc_html( get_bloginfo( 'version' ) ); ?></td>
                </tr>
                <tr>
                    <td><strong><?php esc_html_e( 'PHP Version', 'reeid-translate' ); ?></strong></td>
                    <td><?php echo esc_html( PHP_VERSION ); ?></td>
                </tr>
                <tr>
                    <td><strong><?php esc_html_e( 'Memory Limit', 'reeid-translate' ); ?></strong></td>
                    <td><?php echo esc_html( ini_get( 'memory_limit' ) ); ?></td>
                </tr>
            </tbody>
        </table>

        <hr>

        <p>
            <?php esc_html_e( 'Documentation and support:', 'reeid-translate' ); ?>
            <a href="<?php echo esc_url( $url ); ?>"
               target="_blank"
               rel="noopener noreferrer">
               <?php echo esc_html( $url ); ?>
            </a>
        </p>

    </div>
    <?php
}

/* =============================================================================
   Render translation map as HTML
   ============================================================================= */
function reeid_render_translation_map_html( $map ) {

    if ( ! is_array( $map ) || ! count( $map ) ) {
        return '';
    }

    $out  = '<h4 style="margin-top:20px;">' .
            esc_html__( 'Current Map:', 'reeid-translate' ) .
            '</h4><ul>';

    foreach ( $map as $lang => $post_id ) {

        $post_id   = absint( $post_id );
        $title     = get_the_title( $post_id );
        $status    = get_post_status( $post_id );
        $edit_link = get_edit_post_link( $post_id );

        $out .= sprintf(
            '<li><b>%s</b> &#8594; <a href="%s" target="_blank" rel="noopener noreferrer">%s</a> <span style="color:#888;">(%s, %s)</span></li>',
            esc_html( strtoupper( (string) $lang ) ),
            esc_url( (string) $edit_link ),
            esc_html( (string) $title ),
            esc_html( (string) $post_id ),
            esc_html( (string) $status )
        );
    }

    $out .= '</ul>';
    return $out;
}


/* =============================================================================
   Force repair translation map for a given post ID
   ============================================================================= */
function reeid_force_repair_translation_map( $post_id ) {

    $post_id = absint( $post_id );
    if ( ! $post_id ) {
        return false;
    }

    $source_id    = $post_id;
    $default_lang = sanitize_text_field( (string) get_option( 'reeid_translation_source_lang', 'en' ) );
    $map          = array();

    $cache_key = 'reeid_children_' . $source_id;
    $children  = get_transient( $cache_key );

    if ( false === $children ) {

        // Query only IDs; avoid heavy caches.
       $q = new WP_Query(
    array(
        'post_type'              => array( 'post', 'page', 'product' ),
        'post_status'            => array( 'publish', 'draft', 'pending' ),
        'posts_per_page'         => -1,
        'fields'                 => 'ids',
        'no_found_rows'          => true,
        'ignore_sticky_posts'    => true,
        'orderby'                => 'none',
        'update_post_meta_cache' => false,
        'update_post_term_cache' => false,
        'cache_results'          => false,
    )
);

$matched_ids = array();

if ( $q->posts ) {
    foreach ( $q->posts as $pid ) {
        $src = get_post_meta( $pid, '_reeid_translation_source', true );
        if ( (int) $src === (int) $source_id ) {
            $matched_ids[] = $pid;
        }
    }
}
        $children = $q->posts;
        set_transient( $cache_key, $children, 300 );
    }

    foreach ( (array) $children as $child_id ) {

        $child_id  = absint( $child_id );
        $lang      = get_post_meta( $child_id, '_reeid_translation_lang', true );
        $lang      = sanitize_text_field( (string) $lang );

        if ( $lang && 'publish' === get_post_status( $child_id ) ) {
            $map[ $lang ] = $child_id;
        }
    }

    // include source
    if ( 'publish' === get_post_status( $source_id ) ) {
        $map[ $default_lang ] = $source_id;
    }

    update_post_meta( $source_id, '_reeid_translation_map', $map );

    return $map;
}



/**
 * Ensures every translation in a group shares the same map.
 *
 * Note: This uses a meta_key/meta_value query to find all children. This can be slow when many translation records exist,
 * so we cache the result for 5 minutes. This function is intended for admin/tools use only, not for every page load.
 */
function reeid_repair_translation_group($group_source_id)
{
    $group_source_id = absint($group_source_id);

    // Use transient cache to avoid repeated slow queries.
    $cache_key = 'reeid_group_children_' . $group_source_id;
    $children  = get_transient($cache_key);
if ( false === $children ) {

    // 1) Gather all published posts/pages/products.
    $all_ids = get_posts( array(
        'post_type'              => array( 'post', 'page', 'product' ),
        'posts_per_page'         => -1,
        'post_status'            => array( 'publish' ),
        'fields'                 => 'ids',
        'no_found_rows'          => true,
        'update_post_meta_cache' => false,
        'update_post_term_cache' => false,
    ) );

    $children = array();

    if ( $all_ids ) {
        foreach ( $all_ids as $pid ) {
            $src = get_post_meta( $pid, '_reeid_translation_source', true );
            if ( (int) $src === (int) $group_source_id ) {
                $children[] = $pid;
            }
        }
    }

    set_transient( $cache_key, $children, 300 ); // 5 min cache.
}

    // 2) Build a clean map: lang => post_id.
    $translations = array();
    foreach ((array) $children as $child_id) {
        $lang = get_post_meta($child_id, '_reeid_translation_lang', true);
        if ($lang) {
            $translations[$lang] = (int) $child_id;
        }
    }

    // 3) Add the original source (if published).
    if (get_post_status($group_source_id) === 'publish') {
        $default_lang                 = get_option('reeid_translation_source_lang', 'en');
        $translations[$default_lang] = (int) $group_source_id;
    }

    // 4) Write the same map into every post in this group.
    foreach ($translations as $lang => $post_id) {
        update_post_meta($post_id, '_reeid_translation_map', $translations);
    }

    return $translations;
}

/**
 * Render the main settings page with tabs.
 */
function reeid_render_settings_page()
{
    $logo_id        = absint(apply_filters('reeid_logo_attachment_id', 123));

    $active_tab_raw = filter_input(INPUT_GET, 'tab', FILTER_UNSAFE_RAW);
    $active_tab     = $active_tab_raw ? sanitize_text_field(wp_unslash($active_tab_raw)) : 'settings';

    $base = admin_url('options-general.php');
?>
    <div class="wrap">
        <h1>
            <?php
            if ($logo_id && get_post($logo_id)) {
                echo wp_get_attachment_image(
                    $logo_id,
                    'medium',
                    false,
                    array(
                        'alt' => esc_attr__('REEID Translate Settings', 'reeid-translate'),
                        'style' => 'max-height:50px; margin-bottom:10px;'
                    )
                );
            }
            ?>
        </h1>

        <h2 class="nav-tab-wrapper" style="margin-bottom:18px;">
            <?php
            $tabs = array(
                'settings' => __('SETTINGS', 'reeid-translate'),
                'tools'    => __('TOOLS', 'reeid-translate'),
                'menu-labels' => __('MENU LABELS', 'reeid-translate'),
                'seo'      => __('SEO', 'reeid-translate'),
                'faq'      => __('FAQ', 'reeid-translate'),
                'info'     => __('INFO', 'reeid-translate'),
                
                

            );

            


foreach ( $tabs as $slug => $label ) {
	$url = add_query_arg(
		array(
			'page' => 'reeid-translate-settings',
			'tab'  => $slug,
		),
		$base
	);
	$cls = 'nav-tab' . ( $active_tab === $slug ? ' nav-tab-active' : '' );
	echo '<a href="' . esc_url( $url ) . '" class="' . esc_attr( $cls ) . '">' . esc_html( $label ) . '</a>';
}
?>
</h2>

<div class="reeid-tab-content">
	<?php
	switch ( $active_tab ) {
		case 'tools':
			reeid_render_tools_tab();
			break;
        
            case 'menu-labels':
            reeid_render_menu_labels_tab();
            break;

            case 'seo':
            reeid_render_seo_tab();
            break;
		
		case 'faq':
			reeid_render_faq_tab();
			break;
		case 'info':
			reeid_render_info_tab();
			break;
		case 'stat':
			if ( function_exists( 'reeid_render_stat_tab' ) ) {
				reeid_render_stat_tab();
			} else {
				echo '<p>' . esc_html__( 'Stat tab not available.', 'reeid-translate' ) . '</p>';
			}
			break;
		case 'settings':
		default:
			reeid_render_settings_tab();
			break;
	}
	?>
</div>
</div>
<?php
}

/**
 * Render the “Settings” tab contents.
 */
function reeid_render_settings_tab() {
    if ( ! is_admin() || ! current_user_can( 'manage_options' ) || ! function_exists( 'settings_fields' ) ) {
        echo '<div class="notice notice-error"><p>' . esc_html__( 'Unauthorized.', 'reeid-translate' ) . '</p></div>';
        return;
    }

    $compare_url = 'https://reeid.com/ai-wordpress-translation-plugin/';
    ?>
    
    

    <div class="reeid-settings-grid">
       <div class="reeid-settings-main">
    <form method="post" action="options.php">
        <?php
        settings_fields( 'reeid_translate_settings' );
        do_settings_sections( 'reeid-translate-settings' );
        submit_button();
        ?>
    </form>

    <div class="reeid-free-summary">
        <strong><?php esc_html_e( 'Included in Free', 'reeid-translate' ); ?></strong>
        <span>
            <?php esc_html_e( 'Manual AI translation, OpenAI API key support, Gutenberg support, WooCommerce product translation, language switcher, hreflang tags, and translation map repair.', 'reeid-translate' ); ?>
        </span>
    </div>

    
</div>

               <aside class="reeid-settings-pro-card" aria-label="<?php echo esc_attr__( 'REEID Translate Pro information', 'reeid-translate' ); ?>">
            <div class="reeid-settings-pro-head">
                <h3><?php esc_html_e( 'REEID Translate Pro', 'reeid-translate' ); ?></h3>
                <p><?php esc_html_e( 'Optional Pro edition.', 'reeid-translate' ); ?></p>
            </div>

            <div class="reeid-settings-pro-body">
                <div class="reeid-settings-pro-highlights">

                    <div class="reeid-settings-pro-highlight">
                        <span class="reeid-settings-pro-icon">📘</span>
                        <strong><?php esc_html_e( 'Terminology Consistency', 'reeid-translate' ); ?></strong>
                        <small><?php esc_html_e( 'Keep preferred terminology consistent across translations.', 'reeid-translate' ); ?></small>
                    </div>

                    <div class="reeid-settings-pro-highlight">
                        <span class="reeid-settings-pro-icon">☁️</span>
                        <strong><?php esc_html_e( 'Assisted Translation Workflows', 'reeid-translate' ); ?></strong>
                        <small><?php esc_html_e( 'Optional assisted workflows for supported translation tasks.', 'reeid-translate' ); ?></small>
                    </div>

                    <div class="reeid-settings-pro-highlight">
                        <span class="reeid-settings-pro-icon">🧩</span>
                        <strong><?php esc_html_e( 'Builder-Aware Workflows', 'reeid-translate' ); ?></strong>
                        <small><?php esc_html_e( 'Separate Pro workflows for supported visual builders.', 'reeid-translate' ); ?></small>
                    </div>

                    <div class="reeid-settings-pro-highlight">
                        <span class="reeid-settings-pro-icon">🛡️</span>
                        <strong><?php esc_html_e( 'Layout Protection', 'reeid-translate' ); ?></strong>
                        <small><?php esc_html_e( 'Extra safeguards for complex editor layouts.', 'reeid-translate' ); ?></small>
                    </div>

                </div>

                <a class="reeid-settings-pro-button"
                   href="<?php echo esc_url( $compare_url ); ?>"
                   target="_blank"
                   rel="noopener noreferrer">
                    <?php esc_html_e( 'Compare Free and Pro', 'reeid-translate' ); ?>
                </a>

                <p class="reeid-settings-pro-note">
                    <?php esc_html_e( 'Useful for larger websites, teams, agencies, WooCommerce stores, and advanced multilingual SEO workflows.', 'reeid-translate' ); ?>
                </p>
            </div>
        </aside>
    <?php
}

function reeid_render_tools_tab() {
    $tools_action_url = admin_url( 'admin-post.php' );


  if ( isset( $_GET['fixed'] ) ) {

    $fixed = filter_input( INPUT_GET, 'fixed', FILTER_SANITIZE_NUMBER_INT );
    $fixed = absint( $fixed );

    echo '<div class="notice notice-success"><p>'
        . sprintf(
            /* translators: %1$d is the number of repaired translation maps. */
            esc_html__( 'Translation maps repaired: %1$d', 'reeid-translate' ),
            esc_html( $fixed )
        )
        . '</p></div>';
}

$purged_raw = filter_input( INPUT_GET, 'purged', FILTER_UNSAFE_RAW );

if ( null !== $purged_raw ) {
    echo '<div class="notice notice-success"><p>'
        . esc_html__( 'All REEID translation caches have been purged.', 'reeid-translate' )
        . '</p></div>';
}

$tools_result_raw = filter_input( INPUT_GET, 'reeid_tools_result', FILTER_UNSAFE_RAW );
$tools_result     = is_string( $tools_result_raw ) ? sanitize_key( wp_unslash( $tools_result_raw ) ) : '';

if ( 'ok' === $tools_result ) {
    echo '<div class="notice notice-success"><p>'
        . esc_html__( 'Translation maps repaired successfully.', 'reeid-translate' )
        . '</p></div>';
}

    

	if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
		echo '<div class="notice notice-error"><p>' . esc_html__( 'Unauthorized.', 'reeid-translate' ) . '</p></div>';
		return;
	}

	$msg        = '';
	$map_output = '';



    $method_raw = filter_input( INPUT_SERVER, 'REQUEST_METHOD', FILTER_UNSAFE_RAW );
    $method     = is_string( $method_raw ) ? sanitize_text_field( wp_unslash( $method_raw ) ) : '';
$tools_post = ( 'POST' === strtoupper($method) && isset($_POST['reeid_tools_tab_nonce']) );

    $nonce_post        = filter_input( INPUT_POST, 'reeid_tools_tab_nonce', FILTER_UNSAFE_RAW );
    $nonce_unslashed   = is_string( $nonce_post ) ? wp_unslash( $nonce_post ) : '';
    $nonce             = sanitize_text_field( $nonce_unslashed );
    $valid_tools_nonce = $nonce && wp_verify_nonce($nonce, 'reeid_tools_tab_action') && current_user_can('manage_options');

    if ($tools_post && $valid_tools_nonce) {

        
        // Save uninstall behavior (checkbox).
        $delete_data = ! empty( $_POST['reeid_delete_data_on_uninstall'] ) ? '1' : '0';
        update_option( 'reeid_delete_data_on_uninstall', $delete_data );

        // Save switcher appearance.
        if ( isset( $_POST['reeid_switcher_style'] ) ) {
                update_option(
                        'reeid_switcher_style',
                        sanitize_text_field( wp_unslash( $_POST['reeid_switcher_style'] ) )
                );
        }

        if ( isset( $_POST['reeid_switcher_theme'] ) ) {
                update_option(
                        'reeid_switcher_theme',
                        sanitize_text_field( wp_unslash( $_POST['reeid_switcher_theme'] ) )
                );
        }




       
       /* Global Purge Cache */
    if ( ! empty( $_POST['reeid_purge_all_cache'] ) ) {

    global $wpdb;

// 1. Delete all REEID transients.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->query(
    $wpdb->prepare(
        "DELETE FROM {$wpdb->options}
         WHERE option_name LIKE %s",
        $wpdb->esc_like( '_transient_reeid_ht_' ) . '%'
    )
);

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->query(
    $wpdb->prepare(
        "DELETE FROM {$wpdb->options}
         WHERE option_name LIKE %s",
        $wpdb->esc_like( '_transient_timeout_reeid_ht_' ) . '%'
    )
);

// 2. Delete WooCommerce caches.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->query(
    $wpdb->prepare(
        "DELETE FROM {$wpdb->options}
         WHERE option_name LIKE %s",
        $wpdb->esc_like( 'reeid_woo_strings_' ) . '%'
    )
);

    // Clear object cache safely
    if ( function_exists( 'wp_cache_flush' ) ) {
        wp_cache_flush();
    }
    do_action( 'reeid_purge_translation_cache' );
}
        /* Repair ALL maps */
        if (! empty($_POST['reeid_maprepair_all'])) {

            $all_ids = get_posts(array(
                'post_type'        => array('post', 'page'),
                'post_status'      => array('publish'),
                'numberposts'      => -1,
                'fields'           => 'ids',
                'no_found_rows'    => true,
                'suppress_filters' => false,
            ));

            $updated_groups = 0;
            $summary        = array();

            foreach ((array) $all_ids as $source_id) {
                $meta_val        = (int) get_post_meta($source_id, '_reeid_translation_source', true);
                $is_group_source = ($meta_val === 0 || $meta_val === (int) $source_id);
                if (! $is_group_source) {
                    continue;
                }
                $map = reeid_repair_translation_group((int) $source_id);
                if (is_array($map) && ! empty($map)) {
                    $updated_groups++;
                    $langs      = implode(', ', array_keys($map));
                    $summary[]  = 'Group Source ID ' . (int) $source_id . ': ' . $langs;
                }
            }

            if ($updated_groups > 0) {
                $msg        = '<div style="color:green;font-weight:bold;">&#10004; '
                    . esc_html__('All groups repaired. Total groups updated:', 'reeid-translate')
                    . ' ' . esc_html((string) $updated_groups) . '.</div>';
                $map_output = '<details style="margin:10px 0;"><summary style="cursor:pointer;">'
                    . esc_html__('Show details', 'reeid-translate')
                    . '</summary><pre style="background:#fafaff;border:1px solid #ddd;padding:8px;">'
                    . esc_html(implode("\n", $summary))
                    . '</pre></details>';
            } else {
                $msg = '<div style="color:orange;font-weight:bold;">'
                    . esc_html__('No groups required repair.', 'reeid-translate')
                    . '</div>';
            }
        }

        /* Repair SINGLE map */
        elseif (isset($_POST['reeid_maprepair_post_id'])) {

            $pid = absint(wp_unslash($_POST['reeid_maprepair_post_id']));
            $post = $pid ? get_post($pid) : false;

            if ($pid && $post && in_array($post->post_type, array('post', 'page'), true)) {

                $meta_val        = (int) get_post_meta($pid, '_reeid_translation_source', true);
                $group_source_id = ($meta_val === 0 || $meta_val === $pid) ? $pid : $meta_val;

                $map = reeid_repair_translation_group((int) $group_source_id);

                if (is_array($map) && ! empty($map)) {
                    $langs = implode(', ', array_keys($map));
                    $msg   = '<div style="color:green;font-weight:bold;">&#10004; '
                        . sprintf(
                            /* translators: %1$d = post ID, %2$s = comma-separated langs */
                            esc_html__('Group map repaired for Post ID %1$d. Languages: %2$s.', 'reeid-translate'),
                            $pid,
                            esc_html($langs)
                        )
                        . '</div>';
                    $map_output = reeid_render_translation_map_html($map);

                } elseif (is_array($map) && empty($map)) {
                    $msg = '<div style="color:orange;font-weight:bold;margin-top:10px;">'
                        . esc_html__('No translations found for Post ID', 'reeid-translate')
                        . ' ' . esc_html((string)$pid) . '.</div>';

                } else {
                    $msg = '<div style="color:red;font-weight:bold;">'
                        . esc_html__('Failed to repair map for Post ID', 'reeid-translate')
                        . ' ' . esc_html((string)$pid) . '.</div>';
                }

            } else {
                $msg = '<div style="color:red;font-weight:bold;">'
                    . esc_html__('Please enter a valid Post/Page ID.', 'reeid-translate')
                    . '</div>';
            }
        }

    } elseif ($tools_post) {
        $msg = '<div style="color:red;font-weight:bold;">'
            . esc_html__('Security check failed. Please try again.', 'reeid-translate')
            . '</div>';
    }

   // Current switcher settings.
$style = get_option('reeid_switcher_style', 'default');
$theme = get_option('reeid_switcher_theme', 'auto');

$tools_action_url = add_query_arg(
    array(
        'page' => 'reeid-translate',
        'tab'  => 'tools',
    ),
    admin_url( 'admin.php' )
);



    
?>





    <div class="reeid-tools-row">

       <!-- Left Column: Map Repair -->
<div class="reeid-tools-col">
    <h2><?php esc_html_e('Translation Map Repair', 'reeid-translate'); ?></h2>

    <?php
    // REQUIRED: admin-safe POST target (prevents 403 / "not allowed")
    $tools_action_url = admin_url( 'admin-post.php' );
    ?>

<form method="post" action="<?php echo esc_url(
    admin_url( 'admin.php?page=reeid-translate-settings&tab=tools' )
); ?>">
    <input type="hidden" name="action" value="reeid_tools_map_repair">
        <?php wp_nonce_field( 'reeid_tools_tab_action', 'reeid_tools_tab_nonce' ); ?>


        <label for="reeid_maprepair_post_id">
            <strong><?php esc_html_e( 'Repair a Map:', 'reeid-translate' ); ?></strong>
        </label>

        <input
            type="number"
            name="reeid_maprepair_post_id"
            id="reeid_maprepair_post_id"
            min="1"
            placeholder="<?php esc_attr_e( 'Enter ID', 'reeid-translate' ); ?>"
            style="width:150px; margin:0 12px 0 8px;" />

        <button type="submit" class="button">
            <?php esc_html_e( 'Repair Map', 'reeid-translate' ); ?>
        </button>

        <button
            type="submit"
            name="reeid_maprepair_all"
            value="1"
            class="button"
            style="margin-left:10px;"
            onclick="return confirm('<?php echo esc_js( __( 'Are you sure? This will scan and repair all translation groups site-wide.', 'reeid-translate' ) ); ?>')">
            <?php esc_html_e( 'Repair All Maps', 'reeid-translate' ); ?>
        </button>
    </form>

    <?php if ( ! empty( $msg ) ) : ?>
        <div class="notice notice-info">
            <?php echo wp_kses_post( $msg ); ?>
        </div>
    <?php endif; ?>

    <?php if ( ! empty( $map_output ) ) : ?>
        <div class="reeid-map-output">
            <?php echo wp_kses_post( $map_output ); ?>
        </div>
    <?php endif; ?>

    <hr>

    <p>
        <?php
        esc_html_e(
            'This tool rebuilds the translation map (_reeid_translation_map) for a specific post/page or all translation groups. This ensures proper linking of translations for the switcher and admin tools.',
            'reeid-translate'
        );
        ?>
    </p>
</div>

        <!-- Right Column: Switcher Appearance -->
        <div class="reeid-tools-col">
            <h2><?php esc_html_e('Switcher Appearance', 'reeid-translate'); ?></h2>

            <form method="post" action="<?php echo esc_url( admin_url( 'admin.php?page=reeid-translate-settings&tab=tools' ) ); ?>">
    <?php wp_nonce_field('reeid_tools_tab_action', 'reeid_tools_tab_nonce'); ?>

                <table class="form-table">
                    <tr>
                        <th scope="row"><?php esc_html_e('Style', 'reeid-translate'); ?></th>
                        <td>
                            <select name="reeid_switcher_style">
                                <option value="default" <?php selected($style, 'default'); ?>>Default</option>
                                <option value="compact" <?php selected($style, 'compact'); ?>>Compact</option>
                                <option value="minimal" <?php selected($style, 'minimal'); ?>>Minimal</option>
                                <option value="outline" <?php selected($style, 'outline'); ?>>Outline</option>
                                <option value="pill" <?php selected($style, 'pill'); ?>>Pill</option>
                                <option value="flat" <?php selected($style, 'flat'); ?>>Flat</option>
                                <option value="glass" <?php selected($style, 'glass'); ?>>Glass / Blur</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Theme', 'reeid-translate'); ?></th>
                        <td>
                            <select name="reeid_switcher_theme">
                                <option value="light" <?php selected($theme, 'light'); ?>>Light</option>
                                <option value="dark" <?php selected($theme, 'dark');  ?>>Dark</option>
                                <option value="auto" <?php selected($theme, 'auto');  ?>>Auto (Match Device)</option>
                            </select>
                        </td>
                    </tr>
                                         
    


                </table>

                <p>
                    <button type="submit" class="button button-primary">
                        <?php esc_html_e('Save Appearance Settings', 'reeid-translate'); ?>
                    </button>
                </p>
            </form>
        </div>

       <!-- Global Purge Cache -->
<div class="reeid-tools-col">
    <h2><?php esc_html_e( 'Global Purge Cache', 'reeid-translate' ); ?></h2>

<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
            <input type="hidden" name="action" value="reeid_tools">
        <?php wp_nonce_field( 'reeid_tools_tab_action', 'reeid_tools_tab_nonce' ); ?>

        <p>
            <button
                type="submit"
                name="reeid_purge_all_cache"
                value="1"
                class="button button-secondary"
                style="background:#b32d2e;color:#fff;"
                onclick="return confirm('<?php echo esc_js(
                    __( '⚠️ WARNING: This will delete ALL REEID translation caches. Continue?', 'reeid-translate' )
                ); ?>')">
                <?php esc_html_e( 'Purge All Translation Cache', 'reeid-translate' ); ?>
            </button>
        </p>

        <p style="max-width:400px;color:#666;">
            <?php esc_html_e(
                'This clears all cached translations (transients only). The next requests may re-trigger API calls.',
                'reeid-translate'
            ); ?>
        </p>
    </form>

    
</div>



        


<?php
}

function reeid_render_menu_labels_tab() {
    $menus = wp_get_nav_menus();

    $method = filter_input( INPUT_SERVER, 'REQUEST_METHOD', FILTER_UNSAFE_RAW );
    $method = is_string( $method ) ? strtoupper( sanitize_text_field( wp_unslash( $method ) ) ) : 'GET';

    $subtab = filter_input( INPUT_GET, 'strings_subtab', FILTER_UNSAFE_RAW );
    if ( 'POST' === $method ) {
        $posted_subtab = filter_input( INPUT_POST, 'strings_subtab', FILTER_UNSAFE_RAW );
        if ( is_string( $posted_subtab ) && $posted_subtab !== '' ) {
            $subtab = $posted_subtab;
        }
    }
    $subtab = is_string( $subtab ) ? sanitize_key( wp_unslash( $subtab ) ) : 'menu-labels';

   $allowed_subtabs = array(
    'menu-labels' => __( 'Menu Labels', 'reeid-translate' ),
);
if ( ! isset( $allowed_subtabs[ $subtab ] ) ) {
    $subtab = 'menu-labels';
}

    $selected_menu = 0;
    $menu_id_post  = filter_input( INPUT_POST, 'reeid_menu_id', FILTER_UNSAFE_RAW );
    $menu_id_get   = filter_input( INPUT_GET, 'reeid_menu_id', FILTER_UNSAFE_RAW );

    if ( is_string( $menu_id_post ) && $menu_id_post !== '' ) {
        $selected_menu = absint( wp_unslash( $menu_id_post ) );
    } elseif ( is_string( $menu_id_get ) && $menu_id_get !== '' ) {
        $selected_menu = absint( wp_unslash( $menu_id_get ) );
    }

    if ( ! $selected_menu && ! empty( $menus[0]->term_id ) ) {
        $selected_menu = (int) $menus[0]->term_id;
    }

   $enabled_langs = function_exists( 'reeid_get_allowed_languages' )
        ? (array) reeid_get_allowed_languages()
        : array();

    $selected_lang = '';
    $lang_post     = filter_input( INPUT_POST, 'reeid_lang', FILTER_UNSAFE_RAW );
    $lang_get      = filter_input( INPUT_GET, 'reeid_lang', FILTER_UNSAFE_RAW );

    if ( is_string( $lang_post ) && $lang_post !== '' ) {
        $selected_lang = sanitize_key( wp_unslash( $lang_post ) );
    } elseif ( is_string( $lang_get ) && $lang_get !== '' ) {
        $selected_lang = sanitize_key( wp_unslash( $lang_get ) );
    }

    if ( ! $selected_lang && ! empty( $enabled_langs ) ) {
        $keys          = array_keys( $enabled_langs );
        $selected_lang = (string) reset( $keys );
    }

        if ( 'POST' === $method && current_user_can( 'manage_options' ) ) {
        $nonce = filter_input( INPUT_POST, 'reeid_menu_labels_nonce', FILTER_UNSAFE_RAW );
        $nonce = is_string( $nonce ) ? sanitize_text_field( wp_unslash( $nonce ) ) : '';

        if ( $nonce && wp_verify_nonce( $nonce, 'reeid_menu_labels_save' ) ) {
    if ( 'menu-labels' === $subtab ) {
        $menu_id = isset( $_POST['reeid_menu_id'] ) ? absint( $_POST['reeid_menu_id'] ) : 0;
        $lang    = isset( $_POST['reeid_lang'] ) ? sanitize_key( wp_unslash( $_POST['reeid_lang'] ) ) : '';

        $posted_overrides = isset( $_POST['reeid_menu_overrides'] ) && is_array( $_POST['reeid_menu_overrides'] )
            ? map_deep( wp_unslash( $_POST['reeid_menu_overrides'] ), 'sanitize_text_field' )
            : array();

        if ( $menu_id && $lang ) {
            $items = wp_get_nav_menu_items( $menu_id );

            if ( $items ) {
                foreach ( $items as $item ) {
                    $item_id  = (int) $item->ID;
                    $existing = get_post_meta( $item_id, '_reeid_menu_label_overrides', true );

                    if ( ! is_array( $existing ) ) {
                        $existing = array();
                    }

                    $value = '';

                    if ( isset( $posted_overrides[ $item_id ] ) ) {
                        if ( is_array( $posted_overrides[ $item_id ] ) ) {
                            $value = isset( $posted_overrides[ $item_id ][ $lang ] )
                                ? trim( (string) $posted_overrides[ $item_id ][ $lang ] )
                                : '';
                        } else {
                            $value = trim( (string) $posted_overrides[ $item_id ] );
                        }
                    }

                    if ( '' === $value ) {
                        unset( $existing[ $lang ] );
                    } else {
                        $existing[ $lang ] = $value;
                    }

                    if ( empty( $existing ) ) {
                        delete_post_meta( $item_id, '_reeid_menu_label_overrides' );
                    } else {
                        update_post_meta( $item_id, '_reeid_menu_label_overrides', $existing );
                    }
                }
            }
        }

        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Menu label overrides saved.', 'reeid-translate' ) . '</p></div>';
    }
}
    }
    ?>
    <div class="wrap">
        <h2><?php esc_html_e( 'Menu Labels', 'reeid-translate' ); ?></h2>

        <h2 class="nav-tab-wrapper" style="margin-bottom:16px;">
            <?php foreach ( $allowed_subtabs as $tab_key => $tab_label ) : ?>
                <?php
                $tab_url = add_query_arg(
                    array(
                        'page'           => 'reeid-translate-settings',
                        'tab'            => 'menu-labels',
                        'strings_subtab' => $tab_key,
                        'reeid_menu_id'  => $selected_menu,
                        'reeid_lang'     => $selected_lang,
                    ),
                    admin_url( 'admin.php' )
                );
                ?>
               <?php
$tab_classes = 'nav-tab ' . ( $subtab === $tab_key ? 'nav-tab-active' : '' );
?>
<a
    href="<?php echo esc_url( $tab_url ); ?>"
    class="<?php echo esc_attr( $tab_classes ); ?>"
>
    <?php echo esc_html( $tab_label ); ?>
</a>
            <?php endforeach; ?>
        </h2>

        <?php if ( 'menu-labels' === $subtab ) : ?>

            <?php if ( empty( $menus ) ) : ?>
                <p><?php esc_html_e( 'No menus found.', 'reeid-translate' ); ?></p>
            <?php else : ?>

                <form method="get" action="">
                    <input type="hidden" name="page" value="reeid-translate-settings">
                    <input type="hidden" name="tab" value="menu-labels">
                    <input type="hidden" name="strings_subtab" value="menu-labels">

                    <p style="display:flex; gap:16px; align-items:flex-end; flex-wrap:wrap;">
                        <span>
                            <label for="reeid_menu_id">
                                <strong><?php esc_html_e( 'Menu', 'reeid-translate' ); ?></strong>
                            </label><br>
                            <select name="reeid_menu_id" id="reeid_menu_id">
                                <?php foreach ( $menus as $menu ) : ?>
                                    <option value="<?php echo esc_attr( (string) $menu->term_id ); ?>" <?php selected( $selected_menu, (int) $menu->term_id ); ?>>
                                        <?php echo esc_html( (string) $menu->name ); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </span>

                        <span>
                            <label for="reeid_lang">
                                <strong><?php esc_html_e( 'Language', 'reeid-translate' ); ?></strong>
                            </label><br>
                            <select name="reeid_lang" id="reeid_lang">
                                <?php foreach ( $enabled_langs as $code => $label ) : ?>
                                    <option value="<?php echo esc_attr( (string) $code ); ?>" <?php selected( $selected_lang, (string) $code ); ?>>
                                        <?php echo esc_html( (string) $label . ' (' . (string) $code . ')' ); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </span>

                        <span>
                            <?php submit_button( __( 'Load', 'reeid-translate' ), 'secondary', '', false ); ?>
                        </span>
                    </p>
                </form>

                <?php
                $items = $selected_menu ? wp_get_nav_menu_items( $selected_menu ) : array();

                if ( empty( $items ) ) :
    ?>
    <p><?php esc_html_e( 'No menu items found for this menu.', 'reeid-translate' ); ?></p>
    <?php
else :
    ?>
                    <form method="post" action="">
    <?php wp_nonce_field( 'reeid_menu_labels_save', 'reeid_menu_labels_nonce' ); ?>
    <input type="hidden" name="strings_subtab" value="menu-labels">
    <input type="hidden" name="reeid_menu_id" value="<?php echo esc_attr( (string) $selected_menu ); ?>">
    <input type="hidden" name="reeid_lang" value="<?php echo esc_attr( (string) $selected_lang ); ?>">

    <table class="widefat striped" style="width:100%;">
        <thead>
            <tr>
                <th style="width:90px;"><?php esc_html_e( 'Item ID', 'reeid-translate' ); ?></th>
                <th style="width:35%;"><?php esc_html_e( 'Source Label', 'reeid-translate' ); ?></th>
                <th style="width:45%;"><?php esc_html_e( 'Translated Label / Override', 'reeid-translate' ); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ( $items as $item ) : ?>
                <?php
               $source_label = isset( $item->title ) ? (string) $item->title : '';

$overrides = get_post_meta( (int) $item->ID, '_reeid_menu_label_overrides', true );
$overrides = is_array( $overrides ) ? $overrides : array();

$custom_label = isset( $overrides[ $selected_lang ] ) ? (string) $overrides[ $selected_lang ] : '';

if (
    '' === trim( $custom_label ) &&
    function_exists( 'reeid_menu_label_saved_translation' )
) {
    $custom_label = reeid_menu_label_saved_translation( $source_label, $selected_lang );
}
                ?>
                <tr>
                    <td><?php echo esc_html( (string) $item->ID ); ?></td>
                    <td><?php echo esc_html( $source_label ); ?></td>
                    
                    <td>
                        <input
                            type="text"
                            class="regular-text"
                            style="width:100%;"
                            name="reeid_menu_overrides[<?php echo esc_attr( (string) $item->ID ); ?>][<?php echo esc_attr( (string) $selected_lang ); ?>]"
                            value="<?php echo esc_attr( $custom_label ); ?>"
                        />
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <p style="margin-top:12px;">
        <?php submit_button( __( 'Save Overrides', 'reeid-translate' ), 'primary', '', false ); ?>
</form>
                <?php endif; ?>

            <?php endif; ?>

            

<?php endif; ?>

    </div>
    <?php
}

function reeid_render_seo_tab() {

    if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
        echo '<div class="notice notice-error"><p>' . esc_html__( 'Unauthorized.', 'reeid-translate' ) . '</p></div>';
        return;
    }

    $method_raw = filter_input( INPUT_SERVER, 'REQUEST_METHOD', FILTER_UNSAFE_RAW );
    $method     = is_string( $method_raw ) ? sanitize_text_field( wp_unslash( $method_raw ) ) : '';
    $seo_post   = ( 'POST' === strtoupper($method) && isset($_POST['reeid_tools_tab_nonce']) );

    $nonce_post        = filter_input( INPUT_POST, 'reeid_tools_tab_nonce', FILTER_UNSAFE_RAW );
    $nonce_unslashed   = is_string( $nonce_post ) ? wp_unslash( $nonce_post ) : '';
    $nonce             = sanitize_text_field( $nonce_unslashed );
    $valid_nonce       = $nonce && wp_verify_nonce($nonce, 'reeid_tools_tab_action') && current_user_can('manage_options');

    if ( $seo_post && $valid_nonce ) {
        $seo_override = ! empty( $_POST['reeid_seo_override_hreflang'] ) ? '1' : '0';

update_option( 'reeid_seo_override_hreflang', $seo_override );

        echo '<div class="notice notice-success"><p>'
            . esc_html__( 'SEO settings saved.', 'reeid-translate' )
            . '</p></div>';
    }

    $pages_enabled  = false;
    $seo_override   = (bool) get_option( 'reeid_seo_override_hreflang', false );
    $robots_enabled = false;
    $action_url = add_query_arg(
        array(
            'page' => 'reeid-translate',
            'tab'  => 'seo',
        ),
        admin_url( 'admin.php' )
    );
    ?>

<form method="post" action="<?php echo esc_url( admin_url( 'admin.php?page=reeid-translate-settings&tab=seo' ) ); ?>">
        <?php wp_nonce_field( 'reeid_tools_tab_action', 'reeid_tools_tab_nonce' ); ?>
        

        <table class="form-table">
           
            <tr>
    <th scope="row"><?php esc_html_e( 'REEID controls hreflang', 'reeid-translate' ); ?></th>
    <td>
        <label>
            <input type="checkbox"
                   name="reeid_seo_override_hreflang"
                   value="1"
                   <?php checked( $seo_override ); ?> />
<?php esc_html_e( 'Disable SEO plugin hreflang/canonical globally and use REEID SEO output (Pages + Woo)', 'reeid-translate' ); ?>
        </label>
    </td>
</tr>

        </table>

        <p>
            <button type="submit" class="button button-primary">
                <?php esc_html_e( 'Save SEO Settings', 'reeid-translate' ); ?>
            </button>
        </p>
    </form>
<?php
}

