<?php
defined('ABSPATH') || exit;
/**
 * Mirror *mixed* taxonomies (attached to multiple object types) under all relevant parents,
 * so each post type shows the taxonomy entry in its native menu.
 * We keep the original taxonomy registration intact (one show_in_menu),
 * and add additional submenu entries for the other parents.
 */
add_action('admin_menu', function(){
    if ( ! function_exists('add_submenu_page') ) return;

    $tax_objects = get_taxonomies( array( 'show_ui' => true ), 'objects' );
    foreach ( $tax_objects as $tax ) {
        $types = isset($tax->object_type) ? (array) $tax->object_type : array();
        $types = array_unique(array_filter(array_map('strval', $types)));
        if ( count($types) < 2 ) {
            continue; // only mixed taxonomies
        }

        // Build target parents per object type
        $parents = array();
        foreach ( $types as $t ) {
            if ( $t === 'post' ) {
                $parents[$t] = array( 'parent' => 'edit.php', 'post_type' => 'post' );
            } elseif ( $t === 'page' ) {
                $parents[$t] = array( 'parent' => 'edit.php?post_type=page', 'post_type' => 'page' );
            } elseif ( $t === 'attachment' ) {
                $parents[$t] = array( 'parent' => 'upload.php', 'post_type' => 'attachment' );
            } else {
                // Custom post types (includes 'product')
                $parents[$t] = array( 'parent' => 'edit.php?post_type=' . $t, 'post_type' => $t );
            }
        }

        // Add submenu item under each parent, pointing to taxonomy screen with proper post_type
        foreach ( $parents as $t => $info ) {
            $slug = 'edit-tags.php?taxonomy=' . $tax->name . '&post_type=' . $info['post_type'];
            // Title: use plural label, fall back to taxonomy name
            $menu_title = ! empty( $tax->labels->name ) ? $tax->labels->name : $tax->name;

            add_submenu_page(
                $info['parent'],
                $menu_title,
                $menu_title,
                $tax->cap->manage_terms ?? 'manage_categories',
                $slug
            );
        }
    }
}, 999);
