<?php
namespace Smart_Media_Cleanup;

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

class Virtual_Folders {

	const TAXONOMY = 'smc_media_folder';

	private $settings;

	public function __construct() {
		$this->settings = Plugin::instance()->get_settings()->get();

		// Taxonomy must always be registered so term data persists even when the feature is toggled off.
		add_action( 'init', array( $this, 'register_taxonomy' ) );

		if ( empty( $this->settings['enable_virtual_folders'] ) ) {
			return;
		}

		add_action( 'add_attachment',              array( $this, 'auto_assign_folder' ) );
		add_action( 'edit_attachment',             array( $this, 'auto_assign_folder' ) );
		// wp_after_insert_post fires after ALL meta and terms are written — more reliable than save_post.
		add_action( 'wp_after_insert_post',        array( $this, 'assign_post_attachments' ), 10, 2 );
		add_filter( 'ajax_query_attachments_args', array( $this, 'filter_by_folder' ) );
		add_action( 'admin_enqueue_scripts',       array( $this, 'enqueue_scripts' ) );
		add_action( 'admin_footer-upload.php',     array( $this, 'render_panel_html' ) );
		add_action( 'before_delete_post',          array( $this, 'cleanup_post_folder' ) );

		add_action( 'wp_ajax_smc_get_folders',    array( $this, 'ajax_get_folders' ) );
		add_action( 'wp_ajax_smc_create_folder',  array( $this, 'ajax_create_folder' ) );
		add_action( 'wp_ajax_smc_rename_folder',  array( $this, 'ajax_rename_folder' ) );
		add_action( 'wp_ajax_smc_delete_folder',  array( $this, 'ajax_delete_folder' ) );
		add_action( 'wp_ajax_smc_assign_folder',  array( $this, 'ajax_assign_folder' ) );
		add_action( 'wp_ajax_smc_sync_folders',      array( $this, 'ajax_sync_folders' ) );
		add_action( 'wp_ajax_smc_bulk_assign_folder', array( $this, 'ajax_bulk_assign_folder' ) );
	}

	// -------------------------------------------------------------------------
	// Taxonomy
	// -------------------------------------------------------------------------

	public function register_taxonomy() {
		register_taxonomy(
			self::TAXONOMY,
			'attachment',
			array(
				'hierarchical'      => true,
				'public'            => false,
				'show_ui'           => false,
				'show_in_nav_menus' => false,
				'rewrite'           => false,
				'query_var'         => false,
				'labels'            => array(
					'name' => esc_html__( 'Media Folders', 'smart-media-cleanup' ),
				),
			)
		);
	}

	// -------------------------------------------------------------------------
	// Auto-assignment on upload
	// -------------------------------------------------------------------------

	public function auto_assign_folder( $attachment_id ) {
		// Skip if already assigned to a folder.
		$existing = wp_get_object_terms( $attachment_id, self::TAXONOMY, array( 'fields' => 'ids' ) );
		if ( ! is_wp_error( $existing ) && ! empty( $existing ) ) {
			return;
		}

		$attachment = get_post( $attachment_id );
		if ( ! $attachment || ! $attachment->post_parent ) {
			return;
		}

		$parent = get_post( $attachment->post_parent );
		if ( ! $parent || 'attachment' === $parent->post_type ) {
			return;
		}

		$post_type    = $parent->post_type;
		$folder_names = isset( $this->settings['folder_names'] ) ? (array) $this->settings['folder_names'] : array();

		if ( empty( $folder_names[ $post_type ] ) ) {
			return;
		}

		$cpt_term_id = $this->get_or_create_cpt_folder( $post_type );
		if ( ! $cpt_term_id ) {
			return;
		}

		$post_term_id = $this->get_or_create_post_folder( $parent, $cpt_term_id );
		if ( ! $post_term_id ) {
			return;
		}

		wp_set_object_terms( $attachment_id, array( $post_term_id ), self::TAXONOMY );
	}

	// -------------------------------------------------------------------------
	// Assign attachments on post save (covers JetEngine, WooCommerce, ACF, Elementor)
	// -------------------------------------------------------------------------

	public function assign_post_attachments( $post_id, $post ) {
		if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
			return;
		}
		if ( in_array( $post->post_status, array( 'auto-draft', 'trash', 'inherit' ), true ) ) {
			return;
		}

		$folder_names = isset( $this->settings['folder_names'] ) ? (array) $this->settings['folder_names'] : array();
		if ( empty( $folder_names[ $post->post_type ] ) ) {
			return;
		}

		$ids = $this->collect_post_attachment_ids( $post_id );
		if ( empty( $ids ) ) {
			return;
		}

		$cpt_term_id = $this->get_or_create_cpt_folder( $post->post_type );
		if ( ! $cpt_term_id ) {
			return;
		}

		$post_term_id = $this->get_or_create_post_folder( $post, $cpt_term_id );
		if ( ! $post_term_id ) {
			return;
		}

		foreach ( $ids as $attachment_id ) {
			$existing = wp_get_object_terms( $attachment_id, self::TAXONOMY, array( 'fields' => 'ids' ) );
			if ( ! is_wp_error( $existing ) && ! empty( $existing ) ) {
				continue;
			}
			wp_set_object_terms( $attachment_id, array( $post_term_id ), self::TAXONOMY );
		}
	}

	private function collect_post_attachment_ids( $post_id ) {
		$ids = array();

		// Featured image.
		$thumb_id = get_post_thumbnail_id( $post_id );
		if ( $thumb_id ) {
			$ids[] = (int) $thumb_id;
		}

		// Media attached via post_parent.
		$children = get_children( array(
			'post_parent' => $post_id,
			'post_type'   => 'attachment',
			'fields'      => 'ids',
		) );
		if ( ! empty( $children ) ) {
			$ids = array_merge( $ids, array_map( 'intval', (array) $children ) );
		}

		// Configured meta keys (JetEngine, ACF, WooCommerce galleries, etc.).
		$meta_keys = array_filter( (array) ( $this->settings['meta_keys'] ?? array() ) );

		if ( class_exists( 'WooCommerce', false ) || defined( 'WC_VERSION' ) ) {
			$meta_keys[] = '_product_image_gallery';
		}

		foreach ( array_unique( $meta_keys ) as $key ) {
			$raw  = get_post_meta( $post_id, $key, true );
			$ids  = array_merge( $ids, $this->parse_ids_from_meta( $raw ) );
		}

		return array_values( array_unique( array_filter( $ids ) ) );
	}

	private function parse_ids_from_meta( $raw ) {
		if ( empty( $raw ) ) {
			return array();
		}

		$ids = array();

		if ( is_array( $raw ) ) {
			foreach ( $raw as $item ) {
				if ( is_numeric( $item ) ) {
					$ids[] = (int) $item;
				}
			}
			return $ids;
		}

		if ( ! is_string( $raw ) ) {
			return array();
		}

		$raw = trim( $raw );

		if ( ctype_digit( $raw ) ) {
			return array( (int) $raw );
		}

		if ( '[' === $raw[0] || '{' === $raw[0] ) {
			$decoded = json_decode( $raw, true );
			if ( is_array( $decoded ) ) {
				array_walk_recursive(
					$decoded,
					function ( $val ) use ( &$ids ) {
						if ( is_numeric( $val ) ) {
							$ids[] = (int) $val;
						}
					}
				);
				return $ids;
			}
		}

		if ( is_serialized( $raw ) ) {
			// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
			$unserialized = @unserialize( $raw );
			if ( is_array( $unserialized ) ) {
				array_walk_recursive(
					$unserialized,
					function ( $val ) use ( &$ids ) {
						if ( is_numeric( $val ) ) {
							$ids[] = (int) $val;
						}
					}
				);
				return $ids;
			}
		}

		// Comma-separated IDs (_product_image_gallery, JetEngine galleries).
		if ( false !== strpos( $raw, ',' ) ) {
			foreach ( explode( ',', $raw ) as $part ) {
				$part = trim( $part );
				if ( is_numeric( $part ) ) {
					$ids[] = (int) $part;
				}
			}
			return $ids;
		}

		return array();
	}

	private function get_or_create_cpt_folder( $post_type ) {
		$folder_names = isset( $this->settings['folder_names'] ) ? (array) $this->settings['folder_names'] : array();
		$folder_name  = $folder_names[ $post_type ] ?? '';

		if ( empty( $folder_name ) ) {
			$pto         = get_post_type_object( $post_type );
			$folder_name = $pto ? $pto->labels->name : $post_type;
		}

		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value
		$terms = get_terms( array(
			'taxonomy'   => self::TAXONOMY,
			'meta_key'   => '_smc_cpt', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
			'meta_value' => $post_type, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
			'hide_empty' => false,
			'parent'     => 0,
			'number'     => 1,
		) );

		if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
			$term = $terms[0];
			if ( $term->name !== $folder_name ) {
				wp_update_term( $term->term_id, self::TAXONOMY, array( 'name' => $folder_name ) );
			}
			return $term->term_id;
		}

		$result = wp_insert_term( $folder_name, self::TAXONOMY, array( 'parent' => 0 ) );
		if ( is_wp_error( $result ) ) {
			return false;
		}

		add_term_meta( $result['term_id'], '_smc_folder_type', 'cpt', true );
		add_term_meta( $result['term_id'], '_smc_cpt', $post_type, true );

		return $result['term_id'];
	}

	private function get_or_create_post_folder( $post, $parent_term_id ) {
		$post_id   = $post->ID;
		$post_name = '' !== $post->post_title ? $post->post_title : sprintf( '#%d', $post_id );

		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value
		$terms = get_terms( array(
			'taxonomy'   => self::TAXONOMY,
			'meta_key'   => '_smc_post_id', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
			'meta_value' => $post_id, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
			'hide_empty' => false,
			'parent'     => $parent_term_id,
			'number'     => 1,
		) );

		if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
			$term = $terms[0];
			if ( $term->name !== $post_name ) {
				wp_update_term( $term->term_id, self::TAXONOMY, array( 'name' => $post_name ) );
			}
			return $term->term_id;
		}

		$result = wp_insert_term( $post_name, self::TAXONOMY, array( 'parent' => $parent_term_id ) );

		if ( is_wp_error( $result ) ) {
			if ( 'term_exists' === $result->get_error_code() ) {
				$existing_id = $result->get_error_data();
				$existing_id = is_array( $existing_id ) ? (int) $existing_id['term_id'] : (int) $existing_id;
				add_term_meta( $existing_id, '_smc_post_id', $post_id );
				add_term_meta( $existing_id, '_smc_folder_type', 'post', true );
				return $existing_id;
			}
			return false;
		}

		add_term_meta( $result['term_id'], '_smc_folder_type', 'post', true );
		add_term_meta( $result['term_id'], '_smc_post_id', $post_id, true );

		return $result['term_id'];
	}

	// -------------------------------------------------------------------------
	// Media library filtering
	// -------------------------------------------------------------------------

	public function filter_by_folder( $query ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.NonceVerification.Recommended
		if ( ! isset( $_REQUEST['smc_folder'] ) ) {
			return $query;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.NonceVerification.Recommended
		$folder_id = (int) $_REQUEST['smc_folder'];

		if ( $folder_id > 0 ) {
			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
			$query['tax_query'] = array(
				array(
					'taxonomy' => self::TAXONOMY,
					'field'    => 'term_id',
					'terms'    => $folder_id,
				),
			);
		} elseif ( -1 === $folder_id ) {
			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
			$query['tax_query'] = array(
				array(
					'taxonomy' => self::TAXONOMY,
					'operator' => 'NOT EXISTS',
				),
			);
		}

		return $query;
	}

	// -------------------------------------------------------------------------
	// Scripts & panel
	// -------------------------------------------------------------------------

	public function enqueue_scripts( $hook ) {
		if ( 'upload.php' !== $hook ) {
			return;
		}

		wp_enqueue_style(
			'smc-media-folders',
			SMC_URL . 'admin/css/media-folders.css',
			array(),
			SMC_VERSION
		);

		wp_enqueue_script(
			'smc-media-folders',
			SMC_URL . 'admin/js/media-folders.js',
			array( 'jquery', 'media-views' ),
			SMC_VERSION,
			true
		);

		wp_localize_script(
			'smc-media-folders',
			'smcFolders',
			array(
				'folders' => $this->get_folder_tree(),
				'nonce'   => wp_create_nonce( 'smc_folders' ),
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'i18n'    => array(
					'folders'       => __( 'Folders', 'smart-media-cleanup' ),
					'allMedia'      => __( 'All Media', 'smart-media-cleanup' ),
					'uncategorized' => __( 'Uncategorized', 'smart-media-cleanup' ),
					'addFolder'     => __( 'New Folder', 'smart-media-cleanup' ),
					'rename'        => __( 'Rename', 'smart-media-cleanup' ),
					'deleteFolder'  => __( 'Delete Folder', 'smart-media-cleanup' ),
					'confirmDelete' => __( 'Delete this folder? Media inside will be moved to Uncategorized.', 'smart-media-cleanup' ),
					'folderName'    => __( 'Folder name', 'smart-media-cleanup' ),
					'newName'       => __( 'New name', 'smart-media-cleanup' ),
					'ok'            => __( 'OK', 'smart-media-cleanup' ),
					'cancel'        => __( 'Cancel', 'smart-media-cleanup' ),
					'error'         => __( 'Something went wrong. Please try again.', 'smart-media-cleanup' ),
					'searchFolders'   => __( 'Search folders…', 'smart-media-cleanup' ),
					'selected'        => __( 'selected', 'smart-media-cleanup' ),
					'clickFolderToMove' => __( 'Click a folder to move them', 'smart-media-cleanup' ),
				),
			)
		);
	}

	public function render_panel_html() {
		?>
		<div id="smc-folders-panel" style="display:none;"></div>
		<div id="smc-folder-modal" style="display:none;" role="dialog" aria-modal="true" aria-labelledby="smc-modal-title">
			<div class="smc-modal-backdrop"></div>
			<div class="smc-modal-box">
				<h3 id="smc-modal-title"></h3>
				<p id="smc-modal-message"></p>
				<input type="text" id="smc-modal-input" class="regular-text" style="display:none;">
				<p class="smc-modal-actions">
					<button id="smc-modal-ok" class="button button-primary"></button>
					<button id="smc-modal-cancel" class="button">
						<?php esc_html_e( 'Cancel', 'smart-media-cleanup' ); ?>
					</button>
				</p>
			</div>
		</div>
		<?php
	}

	// -------------------------------------------------------------------------
	// Folder tree builder
	// -------------------------------------------------------------------------

	private function get_folder_tree() {
		$terms = get_terms( array(
			'taxonomy'   => self::TAXONOMY,
			'hide_empty' => false,
			'orderby'    => 'name',
			'order'      => 'ASC',
		) );

		if ( is_wp_error( $terms ) || empty( $terms ) ) {
			return array();
		}

		$map = array();
		foreach ( $terms as $term ) {
			$map[ $term->term_id ] = array(
				'id'       => $term->term_id,
				'name'     => $term->name,
				'count'    => (int) $term->count,
				'parent'   => (int) $term->parent,
				'type'     => get_term_meta( $term->term_id, '_smc_folder_type', true ) ?: 'manual',
				'children' => array(),
			);
		}

		$tree = array();
		foreach ( $map as $id => &$item ) {
			if ( 0 === $item['parent'] ) {
				$tree[] = &$item;
			} elseif ( isset( $map[ $item['parent'] ] ) ) {
				$map[ $item['parent'] ]['children'][] = &$item;
			}
		}
		unset( $item );

		return array_values( $tree );
	}

	// -------------------------------------------------------------------------
	// AJAX handlers
	// -------------------------------------------------------------------------

	public function ajax_get_folders() {
		check_ajax_referer( 'smc_folders', 'nonce' );
		if ( ! current_user_can( 'upload_files' ) ) {
			wp_send_json_error( null, 403 );
		}
		wp_send_json_success( $this->get_folder_tree() );
	}

	public function ajax_create_folder() {
		check_ajax_referer( 'smc_folders', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( null, 403 );
		}

		$name      = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
		$parent_id = absint( $_POST['parent_id'] ?? 0 );

		if ( empty( $name ) ) {
			wp_send_json_error( array( 'message' => __( 'Folder name is required.', 'smart-media-cleanup' ) ) );
		}

		$result = wp_insert_term( $name, self::TAXONOMY, array( 'parent' => $parent_id ) );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		add_term_meta( $result['term_id'], '_smc_folder_type', 'manual', true );

		wp_send_json_success( array(
			'id'       => $result['term_id'],
			'name'     => $name,
			'count'    => 0,
			'parent'   => $parent_id,
			'type'     => 'manual',
			'children' => array(),
		) );
	}

	public function ajax_rename_folder() {
		check_ajax_referer( 'smc_folders', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( null, 403 );
		}

		$term_id = absint( $_POST['id'] ?? 0 );
		$name    = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';

		if ( ! $term_id || empty( $name ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid request.', 'smart-media-cleanup' ) ) );
		}

		$result = wp_update_term( $term_id, self::TAXONOMY, array( 'name' => $name ) );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success( array( 'id' => $term_id, 'name' => $name ) );
	}

	public function ajax_delete_folder() {
		check_ajax_referer( 'smc_folders', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( null, 403 );
		}

		$term_id = absint( $_POST['id'] ?? 0 );
		if ( ! $term_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid folder ID.', 'smart-media-cleanup' ) ) );
		}

		$children = get_terms( array(
			'taxonomy'   => self::TAXONOMY,
			'parent'     => $term_id,
			'hide_empty' => false,
			'fields'     => 'ids',
		) );

		if ( ! is_wp_error( $children ) ) {
			foreach ( $children as $child_id ) {
				wp_delete_term( (int) $child_id, self::TAXONOMY );
			}
		}

		wp_delete_term( $term_id, self::TAXONOMY );

		wp_send_json_success( array( 'id' => $term_id ) );
	}

	public function ajax_assign_folder() {
		check_ajax_referer( 'smc_folders', 'nonce' );
		if ( ! current_user_can( 'upload_files' ) ) {
			wp_send_json_error( null, 403 );
		}

		$attachment_id = absint( $_POST['attachment_id'] ?? 0 );
		$folder_id     = absint( wp_unslash( $_POST['folder_id'] ?? '0' ) );

		if ( ! $attachment_id || 'attachment' !== get_post_type( $attachment_id ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid attachment.', 'smart-media-cleanup' ) ) );
		}

		if ( $folder_id > 0 ) {
			wp_set_object_terms( $attachment_id, array( $folder_id ), self::TAXONOMY );
		} else {
			wp_set_object_terms( $attachment_id, array(), self::TAXONOMY );
		}

		wp_send_json_success();
	}

	public function ajax_sync_folders() {
		check_ajax_referer( 'smc_folders', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( null, 403 );
		}

		$folder_names = isset( $this->settings['folder_names'] ) ? (array) $this->settings['folder_names'] : array();
		$post_types   = array_keys( array_filter( $folder_names ) );

		if ( empty( $post_types ) ) {
			wp_send_json_error( array( 'message' => __( 'No folder names configured. Add folder names in Settings first.', 'smart-media-cleanup' ) ) );
		}

		$assigned = 0;

		foreach ( $post_types as $post_type ) {
			$posts = get_posts( array(
				'post_type'      => $post_type,
				'post_status'    => array( 'publish', 'draft', 'private' ),
				'posts_per_page' => -1,
				'fields'         => 'ids',
			) );

			foreach ( $posts as $post_id ) {
				$post = get_post( $post_id );
				if ( ! $post ) {
					continue;
				}

				$ids = $this->collect_post_attachment_ids( $post_id );
				if ( empty( $ids ) ) {
					continue;
				}

				$cpt_term_id = $this->get_or_create_cpt_folder( $post_type );
				if ( ! $cpt_term_id ) {
					continue;
				}

				$post_term_id = $this->get_or_create_post_folder( $post, $cpt_term_id );
				if ( ! $post_term_id ) {
					continue;
				}

				foreach ( $ids as $attachment_id ) {
					$existing = wp_get_object_terms( $attachment_id, self::TAXONOMY, array( 'fields' => 'ids' ) );
					if ( ! is_wp_error( $existing ) && ! empty( $existing ) ) {
						continue;
					}
					wp_set_object_terms( $attachment_id, array( $post_term_id ), self::TAXONOMY );
					$assigned++;
				}
			}
		}

		wp_send_json_success( array(
			/* translators: %d: number of images assigned to folders */
			'message' => sprintf( __( 'Done. %d image(s) assigned to folders.', 'smart-media-cleanup' ), $assigned ),
		) );
	}

	public function ajax_bulk_assign_folder() {
		check_ajax_referer( 'smc_folders', 'nonce' );
		if ( ! current_user_can( 'upload_files' ) ) {
			wp_send_json_error( null, 403 );
		}

		$folder_id      = absint( wp_unslash( $_POST['folder_id'] ?? '0' ) );
		$raw_ids        = isset( $_POST['attachment_ids'] ) ? array_map( 'absint', (array) wp_unslash( $_POST['attachment_ids'] ) ) : array();
		$attachment_ids = array_filter( $raw_ids );

		if ( empty( $attachment_ids ) ) {
			wp_send_json_error( array( 'message' => __( 'No images selected.', 'smart-media-cleanup' ) ) );
		}

		$assigned = 0;
		foreach ( $attachment_ids as $attachment_id ) {
			if ( 'attachment' !== get_post_type( $attachment_id ) ) {
				continue;
			}
			if ( $folder_id > 0 ) {
				wp_set_object_terms( $attachment_id, array( $folder_id ), self::TAXONOMY );
			} else {
				wp_set_object_terms( $attachment_id, array(), self::TAXONOMY );
			}
			$assigned++;
		}

		wp_send_json_success( array( 'count' => $assigned ) );
	}

	// -------------------------------------------------------------------------
	// Cleanup empty post subfolder on post delete
	// -------------------------------------------------------------------------

	public function cleanup_post_folder( $post_id ) {
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value
		$terms = get_terms( array(
			'taxonomy'   => self::TAXONOMY,
			'meta_key'   => '_smc_post_id', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
			'meta_value' => $post_id, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
			'hide_empty' => false,
		) );

		if ( empty( $terms ) || is_wp_error( $terms ) ) {
			return;
		}

		foreach ( $terms as $term ) {
			if ( 0 === (int) $term->count ) {
				wp_delete_term( $term->term_id, self::TAXONOMY );
			}
		}
	}
}
