<?php

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

trait Niwa_AI_Tools_Woo_Taxonomy {

    /* ==================================================================
     *  WooCommerce PRODUCT TAXONOMY MANAGEMENT — Shared helpers
     * ================================================================== */

    /**
     * Format a WP_Term object for a WooCommerce product taxonomy.
     *
     * @param WP_Term $term     Term object.
     * @param string  $taxonomy Taxonomy slug.
     * @return array
     */
    private function format_wc_term_data( $term, $taxonomy ) {
        $data = array(
            'id'          => intval( $term->term_id ),
            'name'        => $term->name,
            'slug'        => $term->slug,
            'description' => $term->description,
            'parent'      => intval( $term->parent ),
            'count'       => intval( $term->count ),
        );

        /* Add thumbnail for product_cat and product_brand. */
        if ( in_array( $taxonomy, array( 'product_cat', 'product_brand' ), true ) ) {
            $thumb_id             = get_term_meta( $term->term_id, 'thumbnail_id', true );
            $data['thumbnail_id']  = $thumb_id ? intval( $thumb_id ) : 0;
            $data['thumbnail_url'] = $thumb_id ? wp_get_attachment_url( intval( $thumb_id ) ) : '';
        }

        return $data;
    }

    /**
     * Get human-readable label for a WooCommerce product taxonomy.
     *
     * @param string $taxonomy Taxonomy slug.
     * @return string
     */
    private function get_wc_taxonomy_label( $taxonomy ) {
        switch ( $taxonomy ) {
            case 'product_cat':
                return 'WooCommerce kategorija';
            case 'product_tag':
                return 'WooCommerce tag';
            case 'product_brand':
                return 'WooCommerce brend';
            default:
                return 'WooCommerce taksonomija';
        }
    }

    /**
     * Get plural human-readable label for a WooCommerce product taxonomy.
     *
     * @param string $taxonomy Taxonomy slug.
     * @return string
     */
    private function get_wc_taxonomy_label_plural( $taxonomy ) {
        switch ( $taxonomy ) {
            case 'product_cat':
                return 'WooCommerce kategorije';
            case 'product_tag':
                return 'WooCommerce tagovi';
            case 'product_brand':
                return 'WooCommerce brendovi';
            default:
                return 'WooCommerce taksonomije';
        }
    }

    /**
     * Check whether a WooCommerce product taxonomy supports hierarchical parent.
     *
     * @param string $taxonomy Taxonomy slug.
     * @return bool
     */
    private function wc_taxonomy_supports_parent( $taxonomy ) {
        return 'product_cat' === $taxonomy;
    }

    /**
     * Check whether a WooCommerce product taxonomy supports thumbnail_id meta.
     *
     * @param string $taxonomy Taxonomy slug.
     * @return bool
     */
    private function wc_taxonomy_supports_thumbnail( $taxonomy ) {
        return in_array( $taxonomy, array( 'product_cat', 'product_brand' ), true );
    }

    /* ------------------------------------------------------------------
     *  Shared: list_wc_terms
     * ------------------------------------------------------------------ */

    private function preview_list_wc_terms( $args, $taxonomy, $tool_name ) {
        if ( ! class_exists( 'WooCommerce' ) ) {
            return array(
                'success' => false,
                'error'   => 'WooCommerce nije aktivan na ovom sajtu.',
            );
        }

        $per_page   = isset( $args['per_page'] ) ? max( 1, min( 100, intval( $args['per_page'] ) ) ) : 20;
        $page       = isset( $args['page'] ) ? max( 1, intval( $args['page'] ) ) : 1;
        $search     = isset( $args['search'] ) ? sanitize_text_field( trim( (string) $args['search'] ) ) : '';
        $orderby    = isset( $args['orderby'] ) && in_array( (string) $args['orderby'], array( 'name', 'id', 'count', 'slug' ), true )
            ? (string) $args['orderby']
            : 'name';
        $order      = isset( $args['order'] ) && in_array( strtolower( (string) $args['order'] ), array( 'asc', 'desc' ), true )
            ? strtolower( (string) $args['order'] )
            : 'asc';
        $hide_empty = isset( $args['hide_empty'] ) ? (bool) $args['hide_empty'] : false;

        $query_args = array(
            'taxonomy'   => $taxonomy,
            'number'     => $per_page,
            'offset'     => ( $page - 1 ) * $per_page,
            'orderby'    => 'id' === $orderby ? 'term_id' : $orderby,
            'order'      => strtoupper( $order ),
            'hide_empty' => $hide_empty,
        );

        if ( '' !== $search ) {
            $query_args['search'] = $search;
        }

        if ( $this->wc_taxonomy_supports_parent( $taxonomy ) && isset( $args['parent'] ) ) {
            $parent_id = intval( $args['parent'] );
            if ( $parent_id >= 0 ) {
                $query_args['parent'] = $parent_id;
            }
        }

        $terms = get_terms( $query_args );
        if ( is_wp_error( $terms ) ) {
            return array(
                'success' => false,
                'error'   => 'Greska pri preuzimanju ' . $this->get_wc_taxonomy_label_plural( $taxonomy ) . ': ' . $terms->get_error_message(),
            );
        }

        $result = array();
        foreach ( $terms as $term ) {
            $result[] = $this->format_wc_term_data( $term, $taxonomy );
        }

        /* Count total for pagination info. */
        $total_args = $query_args;
        unset( $total_args['number'], $total_args['offset'] );
        $total_args['fields'] = 'count';
        $total = (int) get_terms( $total_args );

        return array(
            'success' => true,
            'action'  => array(
                'type'             => $tool_name,
                'label'            => 'Prikaz ' . $this->get_wc_taxonomy_label_plural( $taxonomy ),
                'summary'          => 'Prikazano ' . count( $result ) . ' od ' . $total . ' ' . $this->get_wc_taxonomy_label_plural( $taxonomy ) . ' (stranica ' . $page . ').',
                'rollback_plan'    => 'Citanje — nema potrebe za rollback.',
                'rollback_support' => 'none',
                'targets'          => array(),
                'args'             => array(),
                'read_only'        => true,
                'data'             => array(
                    'terms'    => $result,
                    'total'    => $total,
                    'page'     => $page,
                    'per_page' => $per_page,
                ),
            ),
        );
    }

    private function execute_list_wc_terms( $args, $taxonomy ) {
        $preview = $this->preview_list_wc_terms(
            $args,
            $taxonomy,
            'list_wc_' . $this->wc_taxonomy_short_key( $taxonomy )
        );
        if ( empty( $preview['success'] ) ) {
            return $preview;
        }

        $data = isset( $preview['action']['data'] ) ? $preview['action']['data'] : array();

        return array(
            'success'          => true,
            'summary'          => isset( $preview['action']['summary'] ) ? (string) $preview['action']['summary'] : '',
            'data'             => $data,
            'executed_actions' => array(
                array(
                    'type' => isset( $preview['action']['type'] ) ? (string) $preview['action']['type'] : '',
                ),
            ),
            'rollback_entries' => array(),
        );
    }

    /* ------------------------------------------------------------------
     *  Shared: create_wc_term
     * ------------------------------------------------------------------ */

    private function preview_create_wc_term( $args, $taxonomy, $tool_name ) {
        if ( ! class_exists( 'WooCommerce' ) ) {
            return array(
                'success' => false,
                'error'   => 'WooCommerce nije aktivan na ovom sajtu.',
            );
        }

        $name = isset( $args['name'] ) ? sanitize_text_field( trim( (string) $args['name'] ) ) : '';
        if ( '' === $name ) {
            return array(
                'success' => false,
                'error'   => 'Naziv ' . $this->get_wc_taxonomy_label( $taxonomy ) . ' (name) je obavezan.',
            );
        }

        /* Check if term with same name already exists. */
        $existing = get_term_by( 'name', $name, $taxonomy );
        if ( $existing && ! is_wp_error( $existing ) ) {
            return array(
                'success' => false,
                'error'   => $this->get_wc_taxonomy_label( $taxonomy ) . ' sa nazivom "' . $name . '" vec postoji (ID: ' . $existing->term_id . ').',
            );
        }

        $slug        = isset( $args['slug'] ) ? sanitize_title( (string) $args['slug'] ) : '';
        $description = isset( $args['description'] ) ? sanitize_textarea_field( (string) $args['description'] ) : '';
        $parent      = 0;
        $image_id    = isset( $args['image_id'] ) ? intval( $args['image_id'] ) : 0;

        if ( $this->wc_taxonomy_supports_parent( $taxonomy ) && isset( $args['parent'] ) ) {
            $parent = intval( $args['parent'] );
            if ( $parent > 0 ) {
                $parent_term = get_term( $parent, $taxonomy );
                if ( ! $parent_term || is_wp_error( $parent_term ) ) {
                    return array(
                        'success' => false,
                        'error'   => 'Roditeljski term (ID: ' . $parent . ') ne postoji u taksonomiji ' . $taxonomy . '.',
                    );
                }
            }
        }

        $summary_parts   = array();
        $summary_parts[] = 'Kreiranje ' . $this->get_wc_taxonomy_label( $taxonomy ) . ': "' . $name . '"';
        if ( '' !== $slug ) {
            $summary_parts[] = 'Slug: ' . $slug;
        }
        if ( '' !== $description ) {
            $summary_parts[] = 'Opis: ' . mb_substr( $description, 0, 60 ) . ( mb_strlen( $description ) > 60 ? '...' : '' );
        }
        if ( $parent > 0 ) {
            $parent_term     = get_term( $parent, $taxonomy );
            $summary_parts[] = 'Roditelj: "' . ( $parent_term && ! is_wp_error( $parent_term ) ? $parent_term->name : 'ID ' . $parent ) . '"';
        }
        if ( $image_id > 0 ) {
            $summary_parts[] = 'Slika ID: ' . $image_id;
        }

        $action_args = array(
            'name'        => $name,
            'slug'        => $slug,
            'description' => $description,
            'taxonomy'    => $taxonomy,
        );

        if ( $this->wc_taxonomy_supports_parent( $taxonomy ) ) {
            $action_args['parent'] = $parent;
        }

        if ( $this->wc_taxonomy_supports_thumbnail( $taxonomy ) && $image_id > 0 ) {
            $action_args['image_id'] = $image_id;
        }

        return array(
            'success' => true,
            'action'  => array(
                'type'             => $tool_name,
                'label'            => 'Kreiraj ' . $this->get_wc_taxonomy_label( $taxonomy ),
                'summary'          => implode( ' | ', $summary_parts ),
                'rollback_plan'    => 'Brise kreirani WooCommerce term iz taksonomije.',
                'rollback_support' => 'full',
                'targets'          => array(),
                'args'             => $action_args,
            ),
        );
    }

    private function validate_create_wc_term_action_args( $args ) {
        if ( empty( $args['name'] ) || '' === trim( (string) $args['name'] ) ) {
            return array(
                'success' => false,
                'error'   => 'Naziv terma (name) nedostaje.',
            );
        }

        $valid_taxonomies = array( 'product_cat', 'product_tag', 'product_brand' );
        if ( empty( $args['taxonomy'] ) || ! in_array( (string) $args['taxonomy'], $valid_taxonomies, true ) ) {
            return array(
                'success' => false,
                'error'   => 'Nevalidna WooCommerce taksonomija za kreiranje terma.',
            );
        }

        return array( 'success' => true );
    }

    private function execute_create_wc_term_action( $action ) {
        if ( ! class_exists( 'WooCommerce' ) ) {
            return array(
                'success' => false,
                'error'   => 'WooCommerce nije aktivan na ovom sajtu.',
            );
        }

        $args     = isset( $action['args'] ) && is_array( $action['args'] ) ? $action['args'] : array();
        $name     = sanitize_text_field( (string) $args['name'] );
        $taxonomy = (string) $args['taxonomy'];

        $term_args = array();
        if ( ! empty( $args['slug'] ) ) {
            $term_args['slug'] = sanitize_title( (string) $args['slug'] );
        }
        if ( ! empty( $args['description'] ) ) {
            $term_args['description'] = sanitize_textarea_field( (string) $args['description'] );
        }
        if ( $this->wc_taxonomy_supports_parent( $taxonomy ) && isset( $args['parent'] ) && intval( $args['parent'] ) > 0 ) {
            $term_args['parent'] = intval( $args['parent'] );
        }

        $result = wp_insert_term( $name, $taxonomy, $term_args );
        if ( is_wp_error( $result ) ) {
            return array(
                'success' => false,
                'error'   => $this->get_wc_taxonomy_label( $taxonomy ) . ' nije kreirana: ' . $result->get_error_message(),
            );
        }

        $term_id = intval( $result['term_id'] );

        /* Set thumbnail_id meta if provided. */
        if ( $this->wc_taxonomy_supports_thumbnail( $taxonomy ) && ! empty( $args['image_id'] ) ) {
            update_term_meta( $term_id, 'thumbnail_id', intval( $args['image_id'] ) );
        }

        $term  = get_term( $term_id, $taxonomy );
        $label = ( $term && ! is_wp_error( $term ) ) ? $term->name : $name;

        return array(
            'success'          => true,
            'summary'          => 'Kreirana ' . $this->get_wc_taxonomy_label( $taxonomy ) . ' "' . $label . '" (ID: ' . $term_id . ').',
            'executed_actions' => array(
                array(
                    'type'    => isset( $action['type'] ) ? (string) $action['type'] : 'create_wc_term',
                    'term_id' => $term_id,
                ),
            ),
            'rollback_entries' => array(
                array(
                    'type'     => 'wc_term_delete',
                    'term_id'  => $term_id,
                    'taxonomy' => $taxonomy,
                ),
            ),
        );
    }

    /* ------------------------------------------------------------------
     *  Shared: update_wc_term
     * ------------------------------------------------------------------ */

    private function preview_update_wc_term( $args, $taxonomy, $tool_name, $id_field ) {
        if ( ! class_exists( 'WooCommerce' ) ) {
            return array(
                'success' => false,
                'error'   => 'WooCommerce nije aktivan na ovom sajtu.',
            );
        }

        $term_id = isset( $args[ $id_field ] ) ? intval( $args[ $id_field ] ) : 0;

        if ( $term_id <= 0 ) {
            return array(
                'success' => false,
                'error'   => $this->get_wc_taxonomy_label( $taxonomy ) . ' ID je obavezan za update.',
            );
        }

        $term = get_term( $term_id, $taxonomy );
        if ( ! $term || is_wp_error( $term ) ) {
            return array(
                'success' => false,
                'error'   => $this->get_wc_taxonomy_label( $taxonomy ) . ' (ID: ' . $term_id . ') nije pronadjena.',
            );
        }

        /* Capture previous values for rollback. */
        $previous_thumbnail_id = 0;
        if ( $this->wc_taxonomy_supports_thumbnail( $taxonomy ) ) {
            $previous_thumbnail_id = intval( get_term_meta( $term_id, 'thumbnail_id', true ) );
        }

        $rollback_snapshot = array(
            'type'                 => 'wc_term_restore',
            'term_id'              => $term_id,
            'taxonomy'             => $taxonomy,
            'previous_name'        => $term->name,
            'previous_slug'        => $term->slug,
            'previous_description' => $term->description,
            'previous_parent'      => intval( $term->parent ),
        );

        if ( $this->wc_taxonomy_supports_thumbnail( $taxonomy ) ) {
            $rollback_snapshot['previous_thumbnail_id'] = $previous_thumbnail_id;
        }

        /* Detect what is changing. */
        $changes     = array();
        $update_args = array();

        if ( isset( $args['name'] ) && '' !== trim( (string) $args['name'] ) ) {
            $update_args['name'] = sanitize_text_field( (string) $args['name'] );
            $changes[] = 'naziv: "' . $term->name . '" -> "' . $update_args['name'] . '"';
        }
        if ( isset( $args['slug'] ) ) {
            $update_args['slug'] = sanitize_title( (string) $args['slug'] );
            $changes[] = 'slug: "' . $term->slug . '" -> "' . $update_args['slug'] . '"';
        }
        if ( isset( $args['description'] ) ) {
            $update_args['description'] = sanitize_textarea_field( (string) $args['description'] );
            $desc_preview = mb_substr( $update_args['description'], 0, 40 );
            $changes[] = 'opis: "' . $desc_preview . ( mb_strlen( $update_args['description'] ) > 40 ? '...' : '' ) . '"';
        }
        if ( $this->wc_taxonomy_supports_parent( $taxonomy ) && isset( $args['parent'] ) ) {
            $new_parent = intval( $args['parent'] );
            if ( $new_parent > 0 ) {
                $parent_term = get_term( $new_parent, $taxonomy );
                if ( ! $parent_term || is_wp_error( $parent_term ) ) {
                    return array(
                        'success' => false,
                        'error'   => 'Roditeljski term (ID: ' . $new_parent . ') ne postoji u taksonomiji ' . $taxonomy . '.',
                    );
                }
            }
            $update_args['parent'] = $new_parent;
            $changes[] = 'roditelj: ' . intval( $term->parent ) . ' -> ' . $new_parent;
        }

        $image_id_changed = false;
        if ( $this->wc_taxonomy_supports_thumbnail( $taxonomy ) && isset( $args['image_id'] ) ) {
            $new_image_id     = intval( $args['image_id'] );
            $image_id_changed = true;
            $changes[] = 'slika: ' . $previous_thumbnail_id . ' -> ' . $new_image_id;
        }

        if ( empty( $changes ) ) {
            return array(
                'success' => false,
                'error'   => 'Nijedna promena nije navedena za ' . $this->get_wc_taxonomy_label( $taxonomy ) . ' (ID: ' . $term_id . ').',
            );
        }

        $summary = 'Azuriranje ' . $this->get_wc_taxonomy_label( $taxonomy ) . ' "' . $term->name . '" (ID: ' . $term_id . '). Promene: ' . implode( ', ', $changes );

        $action_args = array_merge(
            $update_args,
            array(
                'term_id'           => $term_id,
                'taxonomy'          => $taxonomy,
                'rollback_snapshot' => $rollback_snapshot,
            )
        );

        if ( $image_id_changed ) {
            $action_args['image_id'] = intval( $args['image_id'] );
        }

        return array(
            'success' => true,
            'action'  => array(
                'type'             => $tool_name,
                'label'            => 'Azuriraj ' . $this->get_wc_taxonomy_label( $taxonomy ),
                'summary'          => $summary,
                'rollback_plan'    => 'Vraca prethodne vrednosti (naziv, slug, opis, roditelj, slika).',
                'rollback_support' => 'full',
                'targets'          => array(
                    array(
                        'term_id' => $term_id,
                        'name'    => $term->name,
                        'slug'    => $term->slug,
                    ),
                ),
                'args'             => $action_args,
            ),
        );
    }

    private function validate_update_wc_term_action_args( $args ) {
        if ( empty( $args['term_id'] ) || intval( $args['term_id'] ) <= 0 ) {
            return array(
                'success' => false,
                'error'   => 'Term ID nedostaje za update.',
            );
        }

        $valid_taxonomies = array( 'product_cat', 'product_tag', 'product_brand' );
        if ( empty( $args['taxonomy'] ) || ! in_array( (string) $args['taxonomy'], $valid_taxonomies, true ) ) {
            return array(
                'success' => false,
                'error'   => 'Nevalidna WooCommerce taksonomija za update terma.',
            );
        }

        return array( 'success' => true );
    }

    private function execute_update_wc_term_action( $action ) {
        if ( ! class_exists( 'WooCommerce' ) ) {
            return array(
                'success' => false,
                'error'   => 'WooCommerce nije aktivan na ovom sajtu.',
            );
        }

        $args     = isset( $action['args'] ) && is_array( $action['args'] ) ? $action['args'] : array();
        $term_id  = intval( $args['term_id'] );
        $taxonomy = (string) $args['taxonomy'];

        $term = get_term( $term_id, $taxonomy );
        if ( ! $term || is_wp_error( $term ) ) {
            return array(
                'success' => false,
                'error'   => $this->get_wc_taxonomy_label( $taxonomy ) . ' (ID: ' . $term_id . ') ne postoji.',
            );
        }

        $update_data = array();
        if ( isset( $args['name'] ) )        { $update_data['name']        = sanitize_text_field( (string) $args['name'] ); }
        if ( isset( $args['slug'] ) )        { $update_data['slug']        = sanitize_title( (string) $args['slug'] ); }
        if ( isset( $args['description'] ) ) { $update_data['description'] = sanitize_textarea_field( (string) $args['description'] ); }
        if ( $this->wc_taxonomy_supports_parent( $taxonomy ) && isset( $args['parent'] ) ) {
            $update_data['parent'] = intval( $args['parent'] );
        }

        if ( ! empty( $update_data ) ) {
            $result = wp_update_term( $term_id, $taxonomy, $update_data );
            if ( is_wp_error( $result ) ) {
                return array(
                    'success' => false,
                    'error'   => $this->get_wc_taxonomy_label( $taxonomy ) . ' update nije uspeo: ' . $result->get_error_message(),
                );
            }
        }

        /* Update thumbnail_id meta if provided. */
        if ( $this->wc_taxonomy_supports_thumbnail( $taxonomy ) && array_key_exists( 'image_id', $args ) ) {
            $new_image_id = intval( $args['image_id'] );
            if ( $new_image_id > 0 ) {
                update_term_meta( $term_id, 'thumbnail_id', $new_image_id );
            } else {
                delete_term_meta( $term_id, 'thumbnail_id' );
            }
        }

        $updated_term = get_term( $term_id, $taxonomy );
        $label = ( $updated_term && ! is_wp_error( $updated_term ) ) ? $updated_term->name : $term->name;

        $rollback_entries = array();
        if ( ! empty( $args['rollback_snapshot'] ) && is_array( $args['rollback_snapshot'] ) ) {
            $rollback_entries[] = $args['rollback_snapshot'];
        }

        return array(
            'success'          => true,
            'summary'          => 'Azurirana ' . $this->get_wc_taxonomy_label( $taxonomy ) . ' "' . $label . '" (ID: ' . $term_id . ').',
            'executed_actions' => array(
                array(
                    'type'    => isset( $action['type'] ) ? (string) $action['type'] : 'update_wc_term',
                    'term_id' => $term_id,
                ),
            ),
            'rollback_entries' => $rollback_entries,
        );
    }

    /* ------------------------------------------------------------------
     *  Shared: delete_wc_term
     * ------------------------------------------------------------------ */

    private function preview_delete_wc_term( $args, $taxonomy, $tool_name, $id_field ) {
        if ( ! class_exists( 'WooCommerce' ) ) {
            return array(
                'success' => false,
                'error'   => 'WooCommerce nije aktivan na ovom sajtu.',
            );
        }

        $term_id = isset( $args[ $id_field ] ) ? intval( $args[ $id_field ] ) : 0;
        $force   = isset( $args['force'] ) ? (bool) $args['force'] : false;

        if ( $term_id <= 0 ) {
            return array(
                'success' => false,
                'error'   => $this->get_wc_taxonomy_label( $taxonomy ) . ' ID je obavezan za brisanje.',
            );
        }

        $term = get_term( $term_id, $taxonomy );
        if ( ! $term || is_wp_error( $term ) ) {
            return array(
                'success' => false,
                'error'   => $this->get_wc_taxonomy_label( $taxonomy ) . ' (ID: ' . $term_id . ') nije pronadjena.',
            );
        }

        /* Safety: cannot delete the default product category. */
        if ( 'product_cat' === $taxonomy ) {
            $default_product_cat = intval( get_option( 'default_product_cat', 0 ) );
            if ( $term_id === $default_product_cat ) {
                return array(
                    'success' => false,
                    'error'   => 'Ne moze se obrisati podrazumevana WooCommerce kategorija proizvoda (ID: ' . $term_id . ').',
                );
            }
        }

        if ( ! $force ) {
            return array(
                'success' => false,
                'error'   => 'Brisanje ' . $this->get_wc_taxonomy_label( $taxonomy ) . ' "' . $term->name . '" zahteva force=true. Ova akcija je destruktivna i ne moze se ponistiti.',
            );
        }

        $summary_parts   = array();
        $summary_parts[] = 'Brisanje ' . $this->get_wc_taxonomy_label( $taxonomy ) . ': "' . $term->name . '" (ID: ' . $term_id . ')';
        if ( $term->count > 0 ) {
            $summary_parts[] = 'UPOZORENJE: ' . $term->count . ' proizvoda koristi ovu ' . $this->get_wc_taxonomy_label( $taxonomy );
        }

        return array(
            'success' => true,
            'action'  => array(
                'type'             => $tool_name,
                'label'            => 'Obrisi ' . $this->get_wc_taxonomy_label( $taxonomy ),
                'summary'          => implode( ' | ', $summary_parts ),
                'rollback_plan'    => 'Brisanje WooCommerce terma je trajno — rollback nije moguc.',
                'rollback_support' => 'none',
                'targets'          => array(
                    array(
                        'term_id' => $term_id,
                        'name'    => $term->name,
                        'slug'    => $term->slug,
                    ),
                ),
                'args'             => array(
                    'term_id'  => $term_id,
                    'taxonomy' => $taxonomy,
                    'force'    => true,
                ),
            ),
        );
    }

    private function validate_delete_wc_term_action_args( $args ) {
        if ( empty( $args['term_id'] ) || intval( $args['term_id'] ) <= 0 ) {
            return array(
                'success' => false,
                'error'   => 'Term ID nedostaje za brisanje.',
            );
        }

        $valid_taxonomies = array( 'product_cat', 'product_tag', 'product_brand' );
        if ( empty( $args['taxonomy'] ) || ! in_array( (string) $args['taxonomy'], $valid_taxonomies, true ) ) {
            return array(
                'success' => false,
                'error'   => 'Nevalidna WooCommerce taksonomija za brisanje terma.',
            );
        }

        return array( 'success' => true );
    }

    private function execute_delete_wc_term_action( $action ) {
        if ( ! class_exists( 'WooCommerce' ) ) {
            return array(
                'success' => false,
                'error'   => 'WooCommerce nije aktivan na ovom sajtu.',
            );
        }

        $args     = isset( $action['args'] ) && is_array( $action['args'] ) ? $action['args'] : array();
        $term_id  = intval( $args['term_id'] );
        $taxonomy = (string) $args['taxonomy'];

        $term = get_term( $term_id, $taxonomy );
        if ( ! $term || is_wp_error( $term ) ) {
            return array(
                'success' => false,
                'error'   => $this->get_wc_taxonomy_label( $taxonomy ) . ' (ID: ' . $term_id . ') ne postoji.',
            );
        }

        /* Safety: cannot delete the default product category. */
        if ( 'product_cat' === $taxonomy ) {
            $default_product_cat = intval( get_option( 'default_product_cat', 0 ) );
            if ( $term_id === $default_product_cat ) {
                return array(
                    'success' => false,
                    'error'   => 'Ne moze se obrisati podrazumevana WooCommerce kategorija proizvoda (ID: ' . $term_id . ').',
                );
            }
        }

        $term_name = $term->name;

        $result = wp_delete_term( $term_id, $taxonomy );
        if ( is_wp_error( $result ) ) {
            return array(
                'success' => false,
                'error'   => $this->get_wc_taxonomy_label( $taxonomy ) . ' brisanje nije uspelo: ' . $result->get_error_message(),
            );
        }

        if ( false === $result ) {
            return array(
                'success' => false,
                'error'   => $this->get_wc_taxonomy_label( $taxonomy ) . ' (ID: ' . $term_id . ') nije mogla biti obrisana.',
            );
        }

        return array(
            'success'          => true,
            'summary'          => 'Obrisana ' . $this->get_wc_taxonomy_label( $taxonomy ) . ' "' . $term_name . '" (ID: ' . $term_id . ').',
            'executed_actions' => array(
                array(
                    'type'    => isset( $action['type'] ) ? (string) $action['type'] : 'delete_wc_term',
                    'term_id' => $term_id,
                ),
            ),
            'rollback_entries' => array(),
        );
    }

    /* ------------------------------------------------------------------
     *  Short key helper for building tool names dynamically.
     * ------------------------------------------------------------------ */

    private function wc_taxonomy_short_key( $taxonomy ) {
        switch ( $taxonomy ) {
            case 'product_cat':
                return 'categories';
            case 'product_tag':
                return 'tags';
            case 'product_brand':
                return 'brands';
            default:
                return 'terms';
        }
    }

    /* ==================================================================
     *  WooCommerce PRODUCT CATEGORIES — Public-facing delegation
     * ================================================================== */

    /* --- list_wc_categories --- */

    private function preview_list_wc_categories( $args ) {
        return $this->preview_list_wc_terms( $args, 'product_cat', 'list_wc_categories' );
    }

    public function execute_list_wc_categories( $args ) {
        return $this->execute_list_wc_terms( is_array( $args ) ? $args : array(), 'product_cat' );
    }

    /* --- create_wc_category --- */

    private function preview_create_wc_category( $args ) {
        return $this->preview_create_wc_term( $args, 'product_cat', 'create_wc_category' );
    }

    private function validate_create_wc_category_action_args( $args ) {
        return $this->validate_create_wc_term_action_args( $args );
    }

    private function execute_create_wc_category_action( $action ) {
        return $this->execute_create_wc_term_action( $action );
    }

    /* --- update_wc_category --- */

    private function preview_update_wc_category( $args ) {
        return $this->preview_update_wc_term( $args, 'product_cat', 'update_wc_category', 'category_id' );
    }

    private function validate_update_wc_category_action_args( $args ) {
        return $this->validate_update_wc_term_action_args( $args );
    }

    private function execute_update_wc_category_action( $action ) {
        return $this->execute_update_wc_term_action( $action );
    }

    /* --- delete_wc_category --- */

    private function preview_delete_wc_category( $args ) {
        return $this->preview_delete_wc_term( $args, 'product_cat', 'delete_wc_category', 'category_id' );
    }

    private function validate_delete_wc_category_action_args( $args ) {
        return $this->validate_delete_wc_term_action_args( $args );
    }

    private function execute_delete_wc_category_action( $action ) {
        return $this->execute_delete_wc_term_action( $action );
    }

    /* ==================================================================
     *  WooCommerce PRODUCT TAGS — Public-facing delegation
     * ================================================================== */

    /* --- list_wc_tags --- */

    private function preview_list_wc_tags( $args ) {
        return $this->preview_list_wc_terms( $args, 'product_tag', 'list_wc_tags' );
    }

    public function execute_list_wc_tags( $args ) {
        return $this->execute_list_wc_terms( is_array( $args ) ? $args : array(), 'product_tag' );
    }

    /* --- create_wc_tag --- */

    private function preview_create_wc_tag( $args ) {
        return $this->preview_create_wc_term( $args, 'product_tag', 'create_wc_tag' );
    }

    private function validate_create_wc_tag_action_args( $args ) {
        return $this->validate_create_wc_term_action_args( $args );
    }

    private function execute_create_wc_tag_action( $action ) {
        return $this->execute_create_wc_term_action( $action );
    }

    /* --- update_wc_tag --- */

    private function preview_update_wc_tag( $args ) {
        return $this->preview_update_wc_term( $args, 'product_tag', 'update_wc_tag', 'tag_id' );
    }

    private function validate_update_wc_tag_action_args( $args ) {
        return $this->validate_update_wc_term_action_args( $args );
    }

    private function execute_update_wc_tag_action( $action ) {
        return $this->execute_update_wc_term_action( $action );
    }

    /* --- delete_wc_tag --- */

    private function preview_delete_wc_tag( $args ) {
        return $this->preview_delete_wc_term( $args, 'product_tag', 'delete_wc_tag', 'tag_id' );
    }

    private function validate_delete_wc_tag_action_args( $args ) {
        return $this->validate_delete_wc_term_action_args( $args );
    }

    private function execute_delete_wc_tag_action( $action ) {
        return $this->execute_delete_wc_term_action( $action );
    }

    /* ==================================================================
     *  WooCommerce PRODUCT BRANDS — Public-facing delegation
     * ================================================================== */

    /* --- list_wc_brands --- */

    private function preview_list_wc_brands( $args ) {
        if ( ! taxonomy_exists( 'product_brand' ) ) {
            return array(
                'success' => false,
                'error'   => 'Product brands taxonomy is not registered. Install WooCommerce Brands or similar plugin.',
            );
        }
        return $this->preview_list_wc_terms( $args, 'product_brand', 'list_wc_brands' );
    }

    public function execute_list_wc_brands( $args ) {
        if ( ! taxonomy_exists( 'product_brand' ) ) {
            return array(
                'success' => false,
                'error'   => 'Product brands taxonomy is not registered. Install WooCommerce Brands or similar plugin.',
            );
        }
        return $this->execute_list_wc_terms( is_array( $args ) ? $args : array(), 'product_brand' );
    }

    /* --- create_wc_brand --- */

    private function preview_create_wc_brand( $args ) {
        if ( ! taxonomy_exists( 'product_brand' ) ) {
            return array(
                'success' => false,
                'error'   => 'Product brands taxonomy is not registered. Install WooCommerce Brands or similar plugin.',
            );
        }
        return $this->preview_create_wc_term( $args, 'product_brand', 'create_wc_brand' );
    }

    private function validate_create_wc_brand_action_args( $args ) {
        return $this->validate_create_wc_term_action_args( $args );
    }

    private function execute_create_wc_brand_action( $action ) {
        if ( ! taxonomy_exists( 'product_brand' ) ) {
            return array(
                'success' => false,
                'error'   => 'Product brands taxonomy is not registered. Install WooCommerce Brands or similar plugin.',
            );
        }
        return $this->execute_create_wc_term_action( $action );
    }

    /* --- update_wc_brand --- */

    private function preview_update_wc_brand( $args ) {
        if ( ! taxonomy_exists( 'product_brand' ) ) {
            return array(
                'success' => false,
                'error'   => 'Product brands taxonomy is not registered. Install WooCommerce Brands or similar plugin.',
            );
        }
        return $this->preview_update_wc_term( $args, 'product_brand', 'update_wc_brand', 'brand_id' );
    }

    private function validate_update_wc_brand_action_args( $args ) {
        return $this->validate_update_wc_term_action_args( $args );
    }

    private function execute_update_wc_brand_action( $action ) {
        if ( ! taxonomy_exists( 'product_brand' ) ) {
            return array(
                'success' => false,
                'error'   => 'Product brands taxonomy is not registered. Install WooCommerce Brands or similar plugin.',
            );
        }
        return $this->execute_update_wc_term_action( $action );
    }

    /* --- delete_wc_brand --- */

    private function preview_delete_wc_brand( $args ) {
        if ( ! taxonomy_exists( 'product_brand' ) ) {
            return array(
                'success' => false,
                'error'   => 'Product brands taxonomy is not registered. Install WooCommerce Brands or similar plugin.',
            );
        }
        return $this->preview_delete_wc_term( $args, 'product_brand', 'delete_wc_brand', 'brand_id' );
    }

    private function validate_delete_wc_brand_action_args( $args ) {
        return $this->validate_delete_wc_term_action_args( $args );
    }

    private function execute_delete_wc_brand_action( $action ) {
        if ( ! taxonomy_exists( 'product_brand' ) ) {
            return array(
                'success' => false,
                'error'   => 'Product brands taxonomy is not registered. Install WooCommerce Brands or similar plugin.',
            );
        }
        return $this->execute_delete_wc_term_action( $action );
    }
}
