<?php
/**
 * Yoast Sitemap Compatibility for Iron SEO 3 FREE
 * Ensures custom media taxonomies are public/REST-visible and included in Yoast XML sitemaps.
 */

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

// 1) Force taxonomy args to be public and REST-visible for our media taxonomies
add_filter( 'register_taxonomy_args', function( $args, $taxonomy ) {
    // Known/likely slugs for Stefano's media taxonomies (Italian + English fallbacks)
    $targets = array(
        'categoria_immagini', 'tag_immagini',
        'categoria_video', 'tag_video',
        'categoria_allegati', 'tag_allegati',
        'image_category', 'image_tag',
        'video_category', 'video_tag',
        'attachment_category', 'attachment_tag',
        'categoria-immagini', 'tag-immagini',
        'categoria-video', 'tag-video',
        'categoria-allegati', 'tag-allegati',
    );

    if ( in_array( $taxonomy, $targets, true ) || false !== strpos( $taxonomy, 'media' ) ) {
        $args['public']             = true;
        $args['show_ui']            = true;
        $args['show_in_rest']       = true;
        $args['show_tagcloud']      = true;
        $args['show_in_nav_menus']  = true;
        if ( empty( $args['rewrite'] ) || ! is_array( $args['rewrite'] ) ) {
            $args['rewrite'] = array( 'slug' => $taxonomy, 'with_front' => false );
        } else {
            $args['rewrite']['with_front'] = false;
            if ( empty( $args['rewrite']['slug'] ) ) {
                $args['rewrite']['slug'] = $taxonomy;
            }
        }
    }
    return $args;
}, 10, 2 );

// 2) Ask Yoast to include our media taxonomies in the XML sitemap index
add_filter( 'wpseo_sitemap_taxonomies', function( $taxonomies ) {
    // Collect all registered taxonomies and heuristically include media-related ones
    $all = get_taxonomies( array(), 'names' );
    foreach ( $all as $tx ) {
        // Heuristics: include image/video/attachment/alleg/immag patterns
        if ( false !== strpos( $tx, 'image' )
          || false !== strpos( $tx, 'video' )
          || false !== strpos( $tx, 'attach' )
          || false !== strpos( $tx, 'alleg' )
          || false !== strpos( $tx, 'immag' ) ) {
            if ( ! in_array( $tx, $taxonomies, true ) ) {
                $taxonomies[] = $tx;
            }
        }
    }
    return $taxonomies;
} );

// 3) Optional: make sure Yoast doesn't exclude them accidentally
add_filter( 'wpseo_sitemap_exclude_taxonomy', function( $excluded, $taxonomy ) {
    if ( false !== strpos( $taxonomy, 'image' )
      || false !== strpos( $taxonomy, 'video' )
      || false !== strpos( $taxonomy, 'attach' )
      || false !== strpos( $taxonomy, 'alleg' )
      || false !== strpos( $taxonomy, 'immag' ) ) {
        return false; // do not exclude
    }
    return $excluded;
}, 10, 2 );
