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

if ( ! defined('MEDIA_WC_BRAND_TAXONOMY') ) {
    define('MEDIA_WC_BRAND_TAXONOMY', 'product_brand');
}

/**
 * Base list of taxonomies that should support SameAs.
 * This is extended at runtime with ALL taxonomies attached to 'post'.
 */
function ironseo3_media_sameas_taxonomies() {
    $taxes = array(
        'media_product',
        'brand_category',
        'brand_tag',
        'brand_pattern',
        'media_review',
        'media_review_cat',
        'media_review_tag',
        'attribute_category',
        'attribute_tag',
        'product_cat',
        'product_tag',
    );

    if ( taxonomy_exists(MEDIA_WC_BRAND_TAXONOMY) ) {
        $taxes[] = MEDIA_WC_BRAND_TAXONOMY;
    }

    if ( function_exists('wc_get_attribute_taxonomies') ) {
        $attribute_taxonomies = wc_get_attribute_taxonomies();
        if ( is_array($attribute_taxonomies) ) {
            foreach ( $attribute_taxonomies as $att ) {
                if ( ! empty($att->attribute_name) ) {
                    $taxes[] = 'pa_' . sanitize_title( $att->attribute_name );
                }
            }
        }
    }

    
    $taxes[] = 'page_media_category';
    $taxes[] = 'page_media_tag';
    $taxes[] = 'page_media_category_pattern';
    $taxes[] = 'page_media_tag_pattern';
return array_values( array_unique( array_filter( $taxes ) ) );
}

/** Render field on term edit screen */
function ironseo3_sameas_render_field($taxonomy, $term) {
    $value = get_term_meta($term->term_id, 'same_as', true);
    $value = is_array($value) ? $value : array();
    $text  = implode("\n", array_map('esc_url', $value));
    ?>
    <tr class="form-field term-sameas-wrap">
        <th scope="row"><label for="same_as"><?php echo esc_html__('SameAs (uno per riga)','iron-seo-3core'); ?></label></th>
        <td>
            <textarea name="same_as" id="same_as" rows="5" style="width: 100%;" placeholder="https://...&#10;https://..."><?php echo esc_textarea($text); ?></textarea>
            <p class="description"><?php echo esc_html__('Inserisci uno o più URL (uno per linea). Saranno salvati come array e mostrati come link.', 'iron-seo-3core'); ?></p>
        </td>
    </tr>
    <?php
}

/** Render field on term add screen */
function ironseo3_sameas_render_add_field($taxonomy) {
    ?>
    <div class="form-field term-sameas-wrap">
        <label for="same_as"><?php echo esc_html__('SameAs (uno per riga)','iron-seo-3core'); ?></label>
        <textarea name="same_as" id="same_as" rows="5" style="width: 100%;" placeholder="https://...&#10;https://..."></textarea>
        <p class="description"><?php echo esc_html__('Inserisci uno o più URL (uno per linea).', 'iron-seo-3core'); ?></p>
    </div>
    <?php
}

/** Admin bindings */
add_action('admin_init', function() {
    // Base configured taxonomies
    $taxes = ironseo3_media_sameas_taxonomies();

    // Merge ALL taxonomies attached to 'post'
    $post_taxes = function_exists('get_object_taxonomies') ? get_object_taxonomies('post') : array();
    if ( ! is_array($taxes) )      { $taxes = array(); }
    if ( ! is_array($post_taxes) ) { $post_taxes = array(); }
    $taxes = array_values( array_unique( array_merge($taxes, $post_taxes) ) );

    foreach ( $taxes as $tax ) {
        if ( ! is_string($tax) || $tax === '' ) { continue; }

        // Add/Edit fields
        add_action("{$tax}_add_form_fields", function($taxonomy) use ($tax) {
            ironseo3_sameas_render_add_field($tax);
        });
        add_action("{$tax}_edit_form_fields", function($term, $taxonomy) use ($tax) {
            ironseo3_sameas_render_field($tax, $term);
        }, 10, 2);

        // Save handlers
        $save_cb = function($term_id) {
            if ( ! current_user_can('manage_categories') ) { return; }
            $value = isset($_POST['same_as']) ? $_POST['same_as'] : '';
            $value = is_array($value) ? $value : preg_split('/\r\n|\r|\n/', (string) $value);
            $clean = array();
            foreach ( $value as $line ) {
                $line = trim($line);
                if ( $line === '' ) { continue; }
                $url = esc_url_raw($line);
                if ( $url ) { $clean[] = $url; }
            }
            $clean = array_values( array_unique( $clean ) );
            update_term_meta($term_id, 'same_as', $clean);
        };
        add_action("created_{$tax}", $save_cb, 10, 1);
        add_action("edited_{$tax}",  $save_cb, 10, 1);

        // Columns
        add_filter("manage_edit-{$tax}_columns", function($columns) {
            if ( ! is_array($columns) ) { $columns = array(); }
            $columns['same_as'] = __('SameAs', 'iron-seo-3core');
            return $columns;
        });
        add_filter("manage_{$tax}_custom_column", function($content, $column_name, $term_id) {
            if ( $column_name !== 'same_as' ) { return $content; }
            $value = get_term_meta($term_id, 'same_as', true);
            if ( empty($value) || ! is_array($value) ) { return ''; }
            $items = array_map(function($u){
                $u_esc = esc_url($u);
                return '<a href="'. $u_esc .'" target="_blank" rel="noopener">'. esc_html($u) .'</a>';
            }, $value);
            return implode('<br>', $items);
        }, 10, 3);
    }
});
