<?php
/**
 * Update Menu Item Tool.
 *
 * Allows the agent to update an existing menu item including title, URL,
 * position, parent, classes, and target attributes.
 *
 * @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_Menu_Item_Tool class.
 */
class Update_Menu_Item_Tool extends Tool {

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

	/**
	 * Get the tool name.
	 *
	 * @return     string The tool name.
	 * @since     1.0.0
	 */
	public function get_name() {
		return __( 'Update 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 'Updates an existing menu item.';
	}

	/**
	 * 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(
				'menu_id'   => array(
					'type'        => 'integer',
					'description' => 'The ID of the menu containing the item',
				),
				'item_id'   => array(
					'type'        => 'integer',
					'description' => 'The ID of the menu item to update',
				),
				'title'     => array(
					'type'        => 'string',
					'description' => 'The new title/label of the menu item',
				),
				'url'       => array(
					'type'        => 'string',
					'description' => 'The new URL for custom link items in valid URL format',
				),
				'parent_id' => array(
					'type'        => 'integer',
					'description' => 'The ID of the parent menu item',
				),
				'position'  => array(
					'type'        => 'integer',
					'description' => 'The new position/order of the menu item',
				),
				'target'    => array(
					'type'        => 'string',
					'description' => 'Link target (e.g., "_blank" for new window)',
				),
				'classes'   => array(
					'type'        => 'array',
					'items'       => array( 'type' => 'string' ),
					'description' => 'CSS classes for the menu item',
				),
			),
			'required'   => array( 'menu_id', '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 ) {
		$menu_id = intval( $args['menu_id'] );
		$item_id = intval( $args['item_id'] );

		$menu = wp_get_nav_menu_object( $menu_id );
		if ( ! $menu ) {
			return $this->error_response( "Menu with ID {$menu_id} not found." );
		}

		// Get existing menu item post.
		$existing_item = get_post( $item_id );
		if ( ! $existing_item || 'nav_menu_item' !== $existing_item->post_type ) {
			return $this->error_response( "Menu item with ID {$item_id} not found." );
		}

		// Fetch existing menu item metadata to preserve values not being updated.
		$existing_type      = get_post_meta( $item_id, '_menu_item_type', true );
		$existing_object_id = get_post_meta( $item_id, '_menu_item_object_id', true );
		$existing_object    = get_post_meta( $item_id, '_menu_item_object', true );
		$existing_parent    = get_post_meta( $item_id, '_menu_item_menu_item_parent', true );
		$existing_target    = get_post_meta( $item_id, '_menu_item_target', true );
		$existing_classes   = get_post_meta( $item_id, '_menu_item_classes', true );
		$existing_xfn       = get_post_meta( $item_id, '_menu_item_xfn', true );
		$existing_url       = get_post_meta( $item_id, '_menu_item_url', true );

		// Build update data with existing values as defaults.
		$menu_item_data = array(
			'menu-item-db-id'       => $item_id,
			'menu-item-status'      => $existing_item->post_status ? $existing_item->post_status : 'publish',
			'menu-item-type'        => $existing_type ? $existing_type : 'custom',
			'menu-item-object-id'   => $existing_object_id ? $existing_object_id : 0,
			'menu-item-object'      => $existing_object ? $existing_object : '',
			'menu-item-parent-id'   => $existing_parent ? $existing_parent : 0,
			'menu-item-position'    => $existing_item->menu_order ? $existing_item->menu_order : 0,
			'menu-item-title'       => $existing_item->post_title ? $existing_item->post_title : '',
			'menu-item-target'      => $existing_target ? $existing_target : '',
			'menu-item-classes'     => is_array( $existing_classes ) ? implode( ' ', $existing_classes ) : ( $existing_classes ? $existing_classes : '' ),
			'menu-item-xfn'         => $existing_xfn ? $existing_xfn : '',
			'menu-item-url'         => $existing_url ? $existing_url : '',
			'menu-item-description' => $existing_item->post_content ? $existing_item->post_content : '',
			'menu-item-attr-title'  => $existing_item->post_excerpt ? $existing_item->post_excerpt : '',
		);

		// Override with user-provided values.
		if ( isset( $args['title'] ) ) {
			$menu_item_data['menu-item-title'] = sanitize_text_field( $args['title'] );
		}
		if ( isset( $args['url'] ) ) {
			$menu_item_data['menu-item-url'] = esc_url_raw( $args['url'] );
		}
		if ( isset( $args['parent_id'] ) ) {
			$menu_item_data['menu-item-parent-id'] = intval( $args['parent_id'] );
		}
		if ( isset( $args['position'] ) ) {
			$menu_item_data['menu-item-position'] = intval( $args['position'] );
		}
		if ( isset( $args['target'] ) ) {
			$menu_item_data['menu-item-target'] = sanitize_text_field( $args['target'] );
		}
		if ( isset( $args['classes'] ) ) {
			$menu_item_data['menu-item-classes'] = implode( ' ', array_map( 'sanitize_html_class', $args['classes'] ) );
		}

		$result = wp_update_nav_menu_item( $menu_id, $item_id, $menu_item_data );

		if ( is_wp_error( $result ) ) {
			return $this->error_response( $result->get_error_message() );
		}

		return $this->success_response(
			'Menu item updated successfully',
			array(
				'item_id' => $result,
				'menu_id' => $menu_id,
				'updated' => true,
			)
		);
	}
}
