<?php
/**
 * Create Term Tool.
 *
 * Create new terms in any registered taxonomy with name, slug, description,
 * and parent support using wp_insert_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;
}

/**
 * Create_Term_Tool class.
 */
class Create_Term_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Create a new 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 to create the term in (e.g., "category", "post_tag", "product_cat")',
				),
				'name'        => array(
					'type'        => 'string',
					'description' => 'The name of the term',
				),
				'slug'        => array(
					'type'        => 'string',
					'description' => 'The slug for the term (auto-generated if not provided)',
				),
				'description' => array(
					'type'        => 'string',
					'description' => 'The description of the term in plain text format',
				),
				'parent'      => array(
					'type'        => 'integer',
					'description' => 'Parent term ID for creating a child term (only for hierarchical taxonomies)',
				),
			),
			'required'   => array( 'taxonomy', 'name' ),
		);
	}

	/**
	 * 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['name'] ) || empty( $args['name'] ) ) {
			return $this->error_response( 'Term name 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 create terms in this taxonomy' );
		}

		$term_args = array();

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

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

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

			$parent = get_term( intval( $args['parent'] ), $taxonomy_name );
			if ( ! $parent || is_wp_error( $parent ) ) {
				return $this->error_response( 'Parent term not found' );
			}
			$term_args['parent'] = intval( $args['parent'] );
		}

		$result = wp_insert_term(
			sanitize_text_field( $args['name'] ),
			$taxonomy_name,
			$term_args
		);

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

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

		$response_data = array(
			'term_id'  => $result['term_id'],
			'name'     => $term->name,
			'slug'     => $term->slug,
			'taxonomy' => $taxonomy_name,
			'url'      => get_term_link( $term ),
		);

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

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