<?php
/**
 * Update User Tool.
 *
 * Update user information including email, password, display name, role,
 * and profile fields using wp_update_user().
 *
 * @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_User_Tool class.
 */
class Update_User_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Update user information including name, email, and role.';
	}

	/**
	 * 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(
				'id'           => array(
					'type'        => 'integer',
					'description' => 'The user ID to update',
				),
				'email'        => array(
					'type'        => 'string',
					'description' => 'New email address',
					'format'      => 'email',
				),
				'first_name'   => array(
					'type'        => 'string',
					'description' => 'First name',
				),
				'last_name'    => array(
					'type'        => 'string',
					'description' => 'Last name',
				),
				'display_name' => array(
					'type'        => 'string',
					'description' => 'Display name',
				),
				'nickname'     => array(
					'type'        => 'string',
					'description' => 'Nickname',
				),
				'description'  => array(
					'type'        => 'string',
					'description' => 'User biography/description in plain text format',
				),
				'url'          => array(
					'type'        => 'string',
					'description' => 'User website URL in valid URL format',
				),
				'role'         => array(
					'type'        => 'string',
					'description' => 'User role',
				),
			),
			'required'   => array( '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( 'edit_users' );
	}

	/**
	 * 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['id'] ) || empty( $args['id'] ) ) {
			return $this->error_response( 'User ID is required' );
		}

		$user_id = intval( $args['id'] );
		$user    = get_user_by( 'ID', $user_id );

		if ( ! $user ) {
			return $this->error_response( 'User not found' );
		}

		if ( ! WordPress_Utils::can_edit_user( $user_id ) ) {
			return $this->error_response( 'You do not have permission to edit this user' );
		}

		$userdata    = array( 'ID' => $user_id );
		$has_updates = false;

		if ( isset( $args['email'] ) && ! empty( $args['email'] ) ) {
			$email    = sanitize_email( $args['email'] );
			$existing = email_exists( $email );
			if ( $existing && $existing !== $user_id ) {
				return $this->error_response( 'Email already in use by another user' );
			}
			$userdata['user_email'] = $email;
			$has_updates            = true;
		}

		$text_fields = array( 'first_name', 'last_name', 'display_name', 'nickname' );
		foreach ( $text_fields as $field ) {
			if ( isset( $args[ $field ] ) ) {
				$userdata[ $field ] = sanitize_text_field( $args[ $field ] );
				$has_updates        = true;
			}
		}

		if ( isset( $args['description'] ) ) {
			$userdata['description'] = sanitize_textarea_field( $args['description'] );
			$has_updates             = true;
		}

		if ( isset( $args['url'] ) ) {
			$userdata['user_url'] = esc_url_raw( $args['url'] );
			$has_updates          = true;
		}

		if ( ! $has_updates && ! isset( $args['role'] ) ) {
			return $this->error_response( 'No updates provided' );
		}

		if ( $has_updates ) {
			$result = wp_update_user( $userdata );
			if ( is_wp_error( $result ) ) {
				return $this->error_response( 'Failed to update user: ' . $result->get_error_message() );
			}
		}

		if ( isset( $args['role'] ) && ! empty( $args['role'] ) ) {
			$new_role = sanitize_key( $args['role'] );
			if ( ! WordPress_Utils::can_promote_user( $user_id ) ) {
				return $this->error_response( 'You do not have permission to change this user\'s role' );
			}
			if ( ! WordPress_Utils::can_assign_role( $new_role ) ) {
				return $this->error_response( 'You do not have permission to assign the role: ' . $new_role );
			}
			$user->set_role( $new_role );
		}

		$updated_user = get_user_by( 'ID', $user_id );

		return $this->success_response(
			'User updated successfully',
			array(
				'user_id'      => $user_id,
				'username'     => $updated_user->user_login,
				'email'        => $updated_user->user_email,
				'display_name' => $updated_user->display_name,
				'roles'        => $updated_user->roles,
			)
		);
	}
}
