<?php
/**
 * Delete Menu Item Tool.
 *
 * Allows the agent to delete a menu item from a navigation menu by item ID.
 *
 * @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;
}

/**
 * Delete_Menu_Item_Tool class.
 */
class Delete_Menu_Item_Tool extends Tool {

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

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

	/**
	 * Get the description of the tool.
	 *
	 * @return     string The description of the tool.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Deletes a menu item from a navigation menu.';
	}

	/**
	 * Get the parameters 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(
				'item_id' => array(
					'type'        => 'integer',
					'description' => 'The ID of the menu item to delete',
				),
			),
			'required'   => array( 'item_id' ),
		);
	}

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

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

	/**
	 * Execute the tool with the given arguments.
	 *
	 * @param      array $args The arguments for the tool.
	 * @return     array The result of executing the tool.
	 * @since     1.0.0
	 */
	protected function execute( $args ) {
		$item_id = intval( $args['item_id'] );

		// Verify the item exists and is a menu item.
		$item = get_post( $item_id );
		if ( ! $item || 'nav_menu_item' !== $item->post_type ) {
			return $this->error_response( "Menu item with ID {$item_id} not found." );
		}

		$title  = $item->post_title;
		$result = wp_delete_post( $item_id, true );

		if ( ! $result ) {
			return $this->error_response( 'Failed to delete the menu item.' );
		}

		return $this->success_response(
			'Menu item deleted successfully',
			array(
				'deleted' => true,
				'item_id' => $item_id,
				'title'   => $title,
			)
		);
	}
}
