<?php
/**
 * Custom Walker for category checklist that applies display name filter
 * Allows external plugins to customize category names in the editor dialog
 *
 * @package WCABE
 */

defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );

class W3ExABulkEdit_Walker_Category_Hierarchy extends Walker_Category_Checklist {

	private $all_categories = null;

	public function __construct() {
		// Pre-fetch all categories with parent info
		$this->all_categories = get_terms( array(
			'taxonomy'   => 'product_cat',
			'hide_empty' => false,
			'fields'     => 'all',
		) );
	}

	public function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) {
		if ( empty( $args['taxonomy'] ) ) {
			$taxonomy = 'category';
		} else {
			$taxonomy = $args['taxonomy'];
		}

		if ( $taxonomy == 'category' ) {
			$name = 'post_category';
		} else {
			$name = 'tax_input[' . $taxonomy . ']';
		}

		$args['popular_cats']  = empty( $args['popular_cats'] ) ? array() : $args['popular_cats'];
		$class                 = in_array( $category->term_id, $args['popular_cats'] ) ? ' class="popular-category"' : '';
		$args['selected_cats'] = empty( $args['selected_cats'] ) ? array() : $args['selected_cats'];

		// Build category object for filter
		$cat_obj = (object) array(
			'term_id'         => $category->term_id,
			'category_id'     => $category->term_id,
			'category_name'   => $category->name,
			'category_parent' => $category->parent,
		);

		// Build all_categories array for filter
		$all_cats = array();
		if ( $this->all_categories && ! is_wp_error( $this->all_categories ) ) {
			foreach ( $this->all_categories as $c ) {
				$all_cats[] = (object) array(
					'term_id'         => $c->term_id,
					'category_id'     => $c->term_id,
					'category_name'   => $c->name,
					'category_parent' => $c->parent,
				);
			}
		}

		// Apply filter for display name
		$display_name = apply_filters(
			'wcabe_category_editor_display_name',
			$category->name,
			$cat_obj,
			$all_cats
		);

		if ( ! empty( $args['list_only'] ) ) {
			$aria_checked = 'false';
			$inner_class  = 'category';

			if ( in_array( $category->term_id, $args['selected_cats'] ) ) {
				$inner_class .= ' selected';
				$aria_checked = 'true';
			}

			$output .= "\n" . '<li' . $class . '>' .
				'<div class="' . $inner_class . '" data-term-id=' . $category->term_id .
				' tabindex="0" role="checkbox" aria-checked="' . $aria_checked . '">' .
				esc_html( $display_name ) . '</div>';
		} else {
			$output .= "\n<li id='{$taxonomy}-{$category->term_id}'$class>" .
				'<label class="selectit"><input value="' . $category->term_id . '" type="checkbox" name="' . $name . '[]" id="in-' . $taxonomy . '-' . $category->term_id . '"' .
				checked( in_array( $category->term_id, $args['selected_cats'] ), true, false ) .
				disabled( empty( $args['disabled'] ), false, false ) . ' /> ' .
				esc_html( $display_name ) . '</label>';
		}
	}
}
