<?php
/**
 * Heavy Quick Edit for Posts & Pages: mostra il 100%% delle tassonomie registrate
 * (gerarchiche e non gerarchiche) e le salva correttamente.
 */
if (!defined('ABSPATH')) { exit; }

/**
 * Carica CSS/JS solo nella schermata elenco articoli/pagine.
 */
add_action('admin_enqueue_scripts', function($hook){
    if ($hook !== 'edit.php') { return; }
    $screen = get_current_screen();
    if (empty($screen) || !in_array($screen->post_type, array('post','page'), true)) { return; }

    wp_enqueue_style(
        'ironseo-quick-edit-heavy-css',
        plugins_url('assets/css/quick-edit-heavy.css', dirname(__FILE__)),
        array(),
        '1.0.0'
    );

    wp_enqueue_script(
        'ironseo-quick-edit-heavy',
        plugins_url('assets/js/quick-edit-heavy.js', dirname(__FILE__)),
        array('jquery'),
        '1.0.0',
        true
    );
});

/**
 * Render dei campi nel Quick Edit / Bulk Edit.
 * Mostra TUTTE le voci delle tassonomie collegate al post type.
 */
function ironseo_render_quick_edit_all_taxonomies($column_name, $post_type){
    // Supportiamo solo post e page in questo file
    if (!in_array($post_type, array('post','page'), true)) { return; }

    // Stampiamo il blocco una sola volta
    static $printed = false;
    if ($printed) { return; }
    $printed = true;

    $taxonomies = get_object_taxonomies($post_type, 'objects');
    if (empty($taxonomies)) { return; }
    ?>
    <fieldset class="inline-edit-col-right ironseo-qe-heavy">
        <div class="inline-edit-col">
            <div class="ironseo-qe-wrap">
                <h4><?php esc_html_e('Tassonomie (Iron SEO 3 – Quick Edit)', 'iron-seo-3core'); ?></h4>
                <?php foreach ($taxonomies as $tax) : 
                    // Nascondi formati standard non utili
                    if (!$tax->show_ui || $tax->name === 'post_format') { continue; }

                    $is_hier = $tax->hierarchical;
                    $tax_id = 'ironseo_qe_' . esc_attr($tax->name);
                    ?>
                    <div class="ironseo-qe-tax">
                        <label class="ironseo-qe-tax__title">
                            <strong><?php echo esc_html($tax->labels->name); ?></strong>
                        </label>
                        <div class="ironseo-qe-tax__body" data-tax="<?php echo esc_attr($tax->name); ?>">
                            <?php if ($is_hier): ?>
                                <div class="ironseo-qe-checklist" id="<?php echo esc_attr($tax_id); ?>">
                                    <?php
                                    // MOSTRA TUTTI I TERMINI: niente limiti, hide_empty = false
                                    wp_terms_checklist(0, array(
                                        'taxonomy'      => $tax->name,
                                        'checked_ontop' => false,
                                        'popular_cats'  => array(),
                                    ));
                                    ?>
                                </div>
                            <?php else: ?>
                                <input type="text"
                                    class="ironseo-qe-tags"
                                    name="ironseo_terms[<?php echo esc_attr($tax->name); ?>]"
                                    value=""
                                    placeholder="<?php esc_attr_e('tag1, tag2, ...', 'iron-seo-3core'); ?>" />
                                <p class="description">
                                    <?php esc_html_e('Termini separati da virgola', 'iron-seo-3core'); ?>
                                </p>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </fieldset>
    <?php
}
add_action('quick_edit_custom_box', 'ironseo_render_quick_edit_all_taxonomies', 10, 2);
add_action('bulk_edit_custom_box',  'ironseo_render_quick_edit_all_taxonomies', 10, 2);

/**
 * Salvataggio dei termini per tutte le tassonomie in Quick/Bulk Edit.
 */
add_action('save_post', function($post_id){
    // Evita autosave e revisioni
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; }
    if (wp_is_post_revision($post_id)) { return; }

    if (!isset($_POST['post_type']) || !in_array($_POST['post_type'], array('post','page'), true)) { return; }
    if (!current_user_can('edit_post', $post_id)) { return; }

    $post_type  = get_post_type($post_id);
    $taxonomies = get_object_taxonomies($post_type, 'objects');
    if (empty($taxonomies)) { return; }

    foreach ($taxonomies as $tax) {
        if (!$tax->show_ui || $tax->name === 'post_format') { continue; }

        if ($tax->hierarchical) {
            // Checklist: tax_input[tax][]
            if (isset($_POST['tax_input'][$tax->name])) {
                $term_ids = array_map('intval', (array) $_POST['tax_input'][$tax->name]);
                wp_set_object_terms($post_id, $term_ids, $tax->name, false);
            } else {
                // Nessun termine selezionato -> svuota tassonomia
                wp_set_object_terms($post_id, array(), $tax->name, false);
            }
        } else {
            // Input testo: ironseo_terms[tax] = "tag1, tag2, ..."
            if (isset($_POST['ironseo_terms'][$tax->name])) {
                $raw   = wp_unslash($_POST['ironseo_terms'][$tax->name]);
                $names = array_filter(array_map('trim', explode(',', $raw)));
                wp_set_object_terms($post_id, $names, $tax->name, false);
            }
        }
    }
}, 15);
