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

/**
 * Quick/Bulk Edit support for ALL taxonomies on:
 * - post
 * - page
 * - product (WooCommerce)
 * For Media Library, WordPress non ha Quick Edit nativo: aggiungiamo una riga inline "quasi quick edit".
 */
class IronSEO3_QuickEdit_Taxonomies {
    public static function boot() {
        // Classic Quick Edit & Bulk Edit for posts, pages, products
        add_action('quick_edit_custom_box', [__CLASS__, 'render_quick_edit'], 10, 2);
        add_action('bulk_edit_custom_box',  [__CLASS__, 'render_bulk_edit'],  10, 2);
        add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_admin_assets']);

        // Save handler not strettamente necessario (WP salva tax_input[]), ma facciamo fallback sicuro
        add_action('save_post', [__CLASS__, 'save_taxonomies_from_request'], 10, 2);

        // Media Library "quasi quick edit": azione di riga + inline row
        add_filter('media_row_actions', [__CLASS__, 'media_row_action'], 10, 2);
        add_action('admin_footer-upload.php', [__CLASS__, 'print_media_inline_template']);
        add_action('wp_ajax_ironseo3_media_quick_tax', [__CLASS__, 'ajax_media_quick_save']);
    }

    /** Get taxonomies for a given post type, public & show_ui */
    protected static function get_taxonomies_for($post_type) {
        $taxes = get_object_taxonomies($post_type, 'objects');
        if (!is_array($taxes)) return [];
        // filter: show_ui only
        return array_values(array_filter($taxes, function($t){
            return $t instanceof WP_Taxonomy && !empty($t->show_ui);
        }));
    }

    protected static function is_supported_post_type($post_type) {
        return in_array($post_type, ['post','page','product'], true);
    }

    /** Quick Edit form fields */
    
    public static function render_quick_edit($column_name, $post_type) {
        if (!self::is_supported_post_type($post_type)) {
            return;
        }
        if ($column_name !== 'title') {
            // Inject once in the main Quick Edit panel
            return;
        }

        $taxes = self::get_taxonomies_for($post_type);
        if (empty($taxes)) {
            return;
        }

        echo '<fieldset class="inline-edit-col-left ironseo3-qe-tax">';
        echo '<div class="inline-edit-col">';

        foreach ($taxes as $tax) {
            if (!($tax instanceof WP_Taxonomy)) {
                continue;
            }

            $label   = !empty($tax->labels->name) ? esc_html($tax->labels->name) : esc_html($tax->label);
            $taxname = esc_attr($tax->name);

            echo '<div class="ironseo3-qe-taxbox">';
            echo '<span class="title">' . $label . '</span>';

            // Generate a real checklist with proper input names so that
            // WordPress core inline-save can persist the selections.
            $args = [
                'taxonomy'      => $tax->name,
                'checked_ontop' => false,
                'echo'          => false,
            ];
            $checklist_html = wp_terms_checklist(0, $args);
            if (!empty($checklist_html) && !is_wp_error($checklist_html)) {
                // Wrap in our UL for styling; keep original checkbox markup intact.
                echo '<ul class="cat-checklist ' . $taxname . '" data-tax="' . $taxname . '">';
                echo $checklist_html;
                echo '</ul>';
            } else {
                // Fallback: empty list container (should not normally happen).
                echo '<ul class="cat-checklist ' . $taxname . '" data-tax="' . $taxname . '"></ul>';
            }

            echo '</div>';
        }

        echo '</div></fieldset>';
    }

    /** Bulk Edit fields: reuse same markup */
    public static function render_bulk_edit($column_name, $post_type) {
        if (!self::is_supported_post_type($post_type)) {
            return;
        }
        if ($column_name !== 'title') {
            return;
        }
        self::render_quick_edit($column_name, $post_type);
    }
    /** Enqueue small JS to populate checklist & existing tags on open, and for Media inline */
    public static function enqueue_admin_assets($hook) {
        $screen = get_current_screen();
        if (empty($screen)) return;
        if (in_array($screen->id, ['edit-post','edit-page','edit-product','upload'], true)) {
            wp_enqueue_script('ironseo3-qe', plugins_url('includes/admin/assets/js/ironseo3-qe.js', dirname(__FILE__)), ['jquery','inline-edit-post'], '1.0.0', true);
            wp_localize_script('ironseo3-qe', 'ironseo3QE', [
                'nonce' => wp_create_nonce('ironseo3_qe'),
            ]);
            wp_enqueue_style('ironseo3-qe', plugins_url('includes/admin/assets/css/ironseo3-qe.css', dirname(__FILE__)), [], '1.0.0');
        }
    }

    /** Fallback save (Quick/Bulk Edit) */
    public static function save_taxonomies_from_request($post_id, $post) {
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
        if (!current_user_can('edit_post', $post_id)) return;
        if (empty($_POST['tax_input']) || !is_array($_POST['tax_input'])) return;

        foreach ($_POST['tax_input'] as $tax => $value) {
            $taxonomy = get_taxonomy($tax);
            if (!$taxonomy) continue;
            if (is_array($value)) {
                // hierarchical: array of term IDs
                $term_ids = array_map('intval', $value);
                wp_set_post_terms($post_id, $term_ids, $tax, false);
            } else {
                // non-hierarchical: comma-separated names
                $names = array_filter(array_map('trim', explode(',', (string)$value)));
                wp_set_post_terms($post_id, $names, $tax, false);
            }
        }
    }

    /** MEDIA LIBRARY: add row action */
    public static function media_row_action($actions, $post) {
        if ($post->post_type !== 'attachment') return $actions;
        $actions['ironseo3_quick_tax'] = '<a href="#" class="ironseo3-media-quick-tax" data-post="'.$post->ID.'">'.esc_html__('Assign Taxonomies', 'iron-seo-3core').'</a>';
        return $actions;
    }

    /** MEDIA LIBRARY: inline template appended to footer */
    public static function print_media_inline_template() {
        $taxes = self::get_taxonomies_for('attachment');
        if (empty($taxes)) return;
        ?>
        <script type="text/html" id="tmpl-ironseo3-media-qe">
            <tr class="ironseo3-media-inline inline-editor">
                <td colspan="6">
                    <fieldset class="inline-edit-col-left ironseo3-qe-tax">
                        <div class="inline-edit-col">
                            <?php foreach ($taxes as $tax): ?>
                                <div class="ironseo3-qe-taxbox">
                                    <span class="title"><?php echo esc_html($tax->labels->name); ?></span>
                                    <?php if ($tax->hierarchical): ?>
                                        <ul class="cat-checklist <?php echo esc_attr($tax->name); ?>" data-tax="<?php echo esc_attr($tax->name); ?>"></ul>
                                    <?php else: ?>
                                        <input type="text" class="text <?php echo esc_attr($tax->name); ?>" name="tax_input[<?php echo esc_attr($tax->name); ?>]" value="" data-tax="<?php echo esc_attr($tax->name); ?>" />
                                        <p class="description"><?php echo esc_html__('Comma-separated.', 'iron-seo-3core'); ?></p>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                            <p class="submit inline-edit-save">
                                <button type="button" class="button cancel"><?php echo esc_html__('Cancel'); ?></button>
                                <button type="button" class="button button-primary save"><?php echo esc_html__('Update'); ?></button>
                            </p>
                        </div>
                    </fieldset>
                </td>
            </tr>
        </script>
        <?php
    }

    /** MEDIA LIBRARY: AJAX save */
    public static function ajax_media_quick_save() {
        check_ajax_referer('ironseo3_qe', 'nonce');
        $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
        if (!$post_id || !current_user_can('edit_post', $post_id)) {
            wp_send_json_error(['message' => 'Permission denied']);
        }
        $tax_input = isset($_POST['tax_input']) && is_array($_POST['tax_input']) ? $_POST['tax_input'] : [];
        foreach ($tax_input as $tax => $value) {
            $taxonomy = get_taxonomy($tax);
            if (!$taxonomy) {
                continue;
            }

            // For MEDIA quick edit we accept either an array of term IDs/names
            // coming from checkbox lists, or a comma-separated string.
            if (is_array($value)) {
                $value = array_filter(array_map('trim', $value));
                if ($taxonomy->hierarchical) {
                    // Hierarchical: treat as term IDs.
                    $terms = array_map('intval', $value);
                } else {
                    // Non-hierarchical: treat as term names/slugs.
                    $terms = $value;
                }
            } else {
                // Fallback string parsing, mainly for tag-style fields.
                $terms = array_filter(array_map('trim', explode(',', (string) $value)));
            }

            wp_set_post_terms($post_id, $terms, $tax, false);
        }
        wp_send_json_success(['updated' => true]);
    }
}
IronSEO3_QuickEdit_Taxonomies::boot();