<?php
/**
 * Update Term Tool.
 *
 * Update existing terms in any taxonomy (name, slug, description, parent)
 * using wp_update_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://maximum.software/
 *
 * 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' ) ) {
	return;
}

/**
 * Update_Term_Tool class.
 */
class Update_Term_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Update an existing term in 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 update',
				),
				'name'        => array(
					'type'        => 'string',
					'description' => 'The new name for the term',
				),
				'slug'        => array(
					'type'        => 'string',
					'description' => 'The new slug for the term',
				),
				'description' => array(
					'type'        => 'string',
					'description' => 'The new description for the term in plain text format',
				),
				'parent'      => array(
					'type'        => 'integer',
					'description' => 'New parent term ID (only for hierarchical taxonomies, use 0 to make top-level)',
				),
			),
			'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->edit_terms ) ) {
			return $this->error_response( 'You do not have permission to edit 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' );
		}

		$update_args = array();

		if ( isset( $args['name'] ) && ! empty( $args['name'] ) ) {
			$update_args['name'] = sanitize_text_field( $args['name'] );
		}

		if ( isset( $args['slug'] ) && ! empty( $args['slug'] ) ) {
			$update_args['slug'] = sanitize_title( $args['slug'] );
		}

		if ( isset( $args['description'] ) ) {
			$update_args['description'] = sanitize_textarea_field( $args['description'] );
		}

		if ( isset( $args['parent'] ) ) {
			if ( ! $taxonomy->hierarchical ) {
				return $this->error_response( 'Cannot set parent for non-hierarchical taxonomy' );
			}

			$parent_id = intval( $args['parent'] );
			if ( $parent_id > 0 ) {
				$parent = get_term( $parent_id, $taxonomy_name );
				if ( ! $parent || is_wp_error( $parent ) ) {
					return $this->error_response( 'Parent term not found' );
				}
				// Prevent circular reference
				if ( $parent_id === $term_id ) {
					return $this->error_response( 'A term cannot be its own parent' );
				}
			}
			$update_args['parent'] = $parent_id;
		}

		if ( empty( $update_args ) ) {
			return $this->error_response( 'No fields to update' );
		}

		$result = wp_update_term( $term_id, $taxonomy_name, $update_args );

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

		$updated_term = get_term( $result['term_id'], $taxonomy_name );

		$response_data = array(
			'term_id'     => $updated_term->term_id,
			'name'        => $updated_term->name,
			'slug'        => $updated_term->slug,
			'description' => $updated_term->description,
			'taxonomy'    => $taxonomy_name,
			'url'         => get_term_link( $updated_term ),
		);

		if ( $taxonomy->hierarchical ) {
			$response_data['parent'] = $updated_term->parent;
		}

		return $this->success_response( 'Term updated successfully', $response_data );
	}
}
