<?php
/**
 * Get Term Details Tool.
 *
 * Retrieve detailed information about a specific term including name, slug,
 * description, parent, count, and term meta.
 *
 * @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;
}

/**
 * Get_Term_Details_Tool class.
 */
class Get_Term_Details_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Get detailed information about a specific term by ID or slug from any taxonomy.';
	}

	/**
	 * 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 retrieve',
				),
				'slug'     => array(
					'type'        => 'string',
					'description' => 'The slug of the term to retrieve',
				),
			),
			'required'   => array( 'taxonomy' ),
		);
	}

	/**
	 * 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( 'read' );
	}

	/**
	 * 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 true;
	}

	/**
	 * 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' );
		}

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

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

		$term = null;

		if ( isset( $args['id'] ) && ! empty( $args['id'] ) ) {
			$term = get_term( intval( $args['id'] ), $taxonomy_name );
		} elseif ( isset( $args['slug'] ) && ! empty( $args['slug'] ) ) {
			$term = get_term_by( 'slug', sanitize_text_field( $args['slug'] ), $taxonomy_name );
		} else {
			return $this->error_response( 'Either term ID or slug is required' );
		}

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

		$taxonomy = get_taxonomy( $taxonomy_name );

		$term_data = array(
			'id'             => $term->term_id,
			'name'           => $term->name,
			'slug'           => $term->slug,
			'description'    => $term->description,
			'count'          => $term->count,
			'taxonomy'       => $term->taxonomy,
			'taxonomy_label' => $taxonomy->label,
			'url'            => get_term_link( $term ),
		);

		// Add parent info for hierarchical taxonomies
		if ( $taxonomy->hierarchical ) {
			$term_data['parent'] = $term->parent;
			if ( $term->parent > 0 ) {
				$parent = get_term( $term->parent, $taxonomy_name );
				if ( $parent && ! is_wp_error( $parent ) ) {
					$term_data['parent_info'] = array(
						'id'   => $parent->term_id,
						'name' => $parent->name,
						'slug' => $parent->slug,
					);
				}
			}

			// Get children
			$children = get_terms(
				array(
					'taxonomy'   => $taxonomy_name,
					'parent'     => $term->term_id,
					'hide_empty' => false,
				)
			);

			if ( ! is_wp_error( $children ) && ! empty( $children ) ) {
				$term_data['children'] = array();
				foreach ( $children as $child ) {
					$term_data['children'][] = array(
						'id'    => $child->term_id,
						'name'  => $child->name,
						'slug'  => $child->slug,
						'count' => $child->count,
					);
				}
			}
		}

		// Get term meta
		$meta = get_term_meta( $term->term_id );
		if ( ! empty( $meta ) ) {
			$term_data['meta'] = array();
			foreach ( $meta as $key => $values ) {
				$term_data['meta'][ $key ] = count( $values ) === 1 ? $values[0] : $values;
			}
		}

		// Get recent posts with this term
		$post_types   = $taxonomy->object_type;
		$recent_posts = get_posts(
			array(
				'post_type'      => $post_types,
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- Standard taxonomy lookup to find term usage; limited to 5 posts, on-demand admin tool.
				'tax_query'      => array(
					array(
						'taxonomy' => $taxonomy_name,
						'field'    => 'term_id',
						'terms'    => $term->term_id,
					),
				),
				'posts_per_page' => 5,
				'post_status'    => 'publish',
			)
		);

		if ( ! empty( $recent_posts ) ) {
			$term_data['recent_posts'] = array();
			foreach ( $recent_posts as $post ) {
				$term_data['recent_posts'][] = array(
					'id'    => $post->ID,
					'title' => $post->post_title,
					'type'  => $post->post_type,
					'date'  => $post->post_date,
				);
			}
		}

		return $this->success_response(
			'Term retrieved successfully',
			array(
				'term' => $term_data,
			)
		);
	}
}
