<?php
defined('ABSPATH') || exit;

add_action('restrict_manage_posts', function() {
    global $typenow;
    if ( $typenow !== 'attachment' ) return;

    $taxonomies = [
        'media_product',
        'product_cat',
        'product_tag',
        ( defined('MEDIA_WC_BRAND_TAXONOMY') ? MEDIA_WC_BRAND_TAXONOMY : 'product_brand' ),
        'brand_category',
        'brand_tag',
        'brand_pattern',
        'media_review',
        'media_review_cat',
        'media_review_tag',
        'attribute_category',
        'attribute_tag',
    ];

    foreach ($taxonomies as $tax) {
        if ( empty($tax) || ! taxonomy_exists($tax) ) continue;
        $tax_obj = get_taxonomy($tax);
        wp_dropdown_categories([
            'show_option_all' => $tax_obj->labels->all_items ?? $tax_obj->labels->name,
            'taxonomy'        => $tax,
            'name'            => $tax,
            'orderby'         => 'name',
            'selected'        => isset($_GET[$tax]) ? (int) $_GET[$tax] : 0,
            'hierarchical'    => $tax_obj->hierarchical,
            'depth'           => 3,
            'show_count'      => false,
            'hide_empty'      => false,
            'value_field'     => 'term_id',
        ]);
    }
});

add_filter('parse_query', function($query) {
    global $pagenow, $typenow;
    if ( ! is_admin() ) return;
    if ( $pagenow !== 'upload.php' ) return;
    if ( $typenow !== 'attachment' ) return;

    $tax_query = [];
    $taxonomies = [
        'media_product',
        'product_cat',
        'product_tag',
        ( defined('MEDIA_WC_BRAND_TAXONOMY') ? MEDIA_WC_BRAND_TAXONOMY : 'product_brand' ),
        'brand_category',
        'brand_tag',
        'brand_pattern',
        'media_review',
        'media_review_cat',
        'media_review_tag',
        'attribute_category',
        'attribute_tag',
    ];

    foreach ($taxonomies as $tax) {
        if ( empty($tax) || ! taxonomy_exists($tax) ) continue;
        if ( isset($_GET[$tax]) && (int) $_GET[$tax] > 0 ) {
            $tax_query[] = [
                'taxonomy' => $tax,
                'field'    => 'term_id',
                'terms'    => (int) $_GET[$tax],
            ];
        }
    }

    if ( ! empty($tax_query) ) {
        $query->set('tax_query', $tax_query);
    }
});
