<?php
/**
 * Delete Term Tool.
 *
 * Delete terms from any registered taxonomy with optional reassignment of
 * associated objects to a different term.
 *
 * @package   Agenistrator
 * @since     1.0.0
 * @author    Alex Ruban <alex@maximum.guru>
 * @author    Maximum Software Inc <contact@maximum.software>
 * @license   GPL-3.0-only
 * @link      https://agenistrator.com/
 *
 * SPDX-FileCopyrightText: 2025-2026 Alex Ruban <alex@maximum.guru>
 * SPDX-FileCopyrightText: 2025-2026 Maximum Software Inc <contact@maximum.software>
 * SPDX-License-Identifier: GPL-3.0-only
 */

namespace Agenistrator;

// Direct access prevention
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Delete_Term_Tool class.
 */
class Delete_Term_Tool extends Tool {

	/**
	 * Get the tool ID.
	 *
	 * @return string The tool ID.
	 * @since     1.0.0
	 */
	public function get_id() {
		return 'delete_term';
	}

	/**
	 * Get the tool name.
	 *
	 * @return string The tool name.
	 * @since     1.0.0
	 */
	public function get_name() {
		return __( 'Delete Term', 'agenistrator' );
	}

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Delete a term from any taxonomy. Works with categories, tags, and custom taxonomies.';
	}

	/**
	 * Get the parameters schema for this tool.
	 *
	 * @return array Parameters schema in JSON Schema format.
	 * @since     1.0.0
	 */
	public function get_parameters() {
		return array(
			'type'       => 'object',
			'properties' => array(
				'taxonomy'     => array(
					'type'        => 'string',
					'description' => 'The taxonomy the term belongs to (e.g., "category", "post_tag", "product_cat")',
				),
				'id'           => array(
					'type'        => 'integer',
					'description' => 'The ID of the term to delete',
				),
				'force_delete' => array(
					'type'        => 'boolean',
					'description' => 'Whether to delete even if the term has children (children will become top-level)',
					'default'     => false,
				),
			),
			'required'   => array( 'taxonomy', 'id' ),
		);
	}

	/**
	 * Check if the current user can execute this tool.
	 *
	 * @return bool True if the current user has permission.
	 * @since     1.0.0
	 */
	public function current_user_can_execute() {
		return current_user_can( 'manage_categories' );
	}

	/**
	 * Check if this tool is read-only.
	 *
	 * @return bool True if the tool only reads data.
	 * @since     1.0.0
	 */
	public function is_read_only() {
		return false;
	}

	/**
	 * Execute the tool with the given arguments.
	 *
	 * @param array $args The tool arguments.
	 *
	 * @return array The tool execution result.
	 * @since     1.0.0
	 */
	protected function execute( $args ) {
		if ( ! isset( $args['taxonomy'] ) || empty( $args['taxonomy'] ) ) {
			return $this->error_response( 'Taxonomy name is required' );
		}

		if ( ! isset( $args['id'] ) || empty( $args['id'] ) ) {
			return $this->error_response( 'Term ID is required' );
		}

		$taxonomy_name = sanitize_key( $args['taxonomy'] );

		if ( ! taxonomy_exists( $taxonomy_name ) ) {
			return $this->error_response( 'Taxonomy not found: ' . $taxonomy_name );
		}

		$taxonomy = get_taxonomy( $taxonomy_name );

		// Check capability for this specific taxonomy
		if ( ! current_user_can( $taxonomy->cap->delete_terms ) ) {
			return $this->error_response( 'You do not have permission to delete terms in this taxonomy' );
		}

		$term_id = intval( $args['id'] );
		$term    = get_term( $term_id, $taxonomy_name );

		if ( ! $term || is_wp_error( $term ) ) {
			return $this->error_response( 'Term not found' );
		}

		// Check for default category protection
		if ( 'category' === $taxonomy_name ) {
			$default_category = get_option( 'default_category' );
			if ( $term_id === (int) $default_category ) {
				return $this->error_response( 'Cannot delete the default category' );
			}
		}

		// Check for children
		if ( $taxonomy->hierarchical ) {
			$children = get_terms(
				array(
					'taxonomy'   => $taxonomy_name,
					'parent'     => $term_id,
					'hide_empty' => false,
				)
			);

			if ( ! is_wp_error( $children ) && ! empty( $children ) ) {
				$force_delete = isset( $args['force_delete'] ) && $args['force_delete'];
				if ( ! $force_delete ) {
					return $this->error_response(
						'Term has ' . count( $children ) . ' child term(s). Set force_delete to true to delete anyway (children will become top-level).'
					);
				}
			}
		}

		// Store term info before deletion
		$deleted_term_info = array(
			'term_id'    => $term->term_id,
			'name'       => $term->name,
			'slug'       => $term->slug,
			'taxonomy'   => $taxonomy_name,
			'post_count' => $term->count,
		);

		$result = wp_delete_term( $term_id, $taxonomy_name );

		if ( is_wp_error( $result ) ) {
			return $this->error_response( 'Failed to delete term: ' . $result->get_error_message() );
		}

		if ( false === $result ) {
			return $this->error_response( 'Failed to delete term' );
		}

		return $this->success_response(
			'Term deleted successfully',
			array(
				'deleted_term' => $deleted_term_info,
			)
		);
	}
}
