<?php
/**
 * Create User Tool.
 *
 * Create new WordPress users with username, email, password, role, and
 * profile fields using wp_insert_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;
}

/**
 * Create_User_Tool class.
 */
class Create_User_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Create a new user account.';
	}

	/**
	 * 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(
				'username'          => array(
					'type'        => 'string',
					'description' => 'The username (login name)',
				),
				'email'             => array(
					'type'        => 'string',
					'description' => 'The user email address',
					'format'      => 'email',
				),
				'password'          => array(
					'type'        => 'string',
					'description' => 'The user password (if omitted, a random one will be generated)',
				),
				'first_name'        => array(
					'type'        => 'string',
					'description' => 'First name',
				),
				'last_name'         => array(
					'type'        => 'string',
					'description' => 'Last name',
				),
				'display_name'      => array(
					'type'        => 'string',
					'description' => 'Display name',
				),
				'role'              => array(
					'type'        => 'string',
					'description' => 'User role (e.g., subscriber, contributor, author, editor, administrator)',
					'default'     => 'subscriber',
				),
				'send_notification' => array(
					'type'        => 'boolean',
					'description' => 'Whether to send an email notification to the new user',
					'default'     => true,
				),
			),
			'required'   => array( 'username', 'email' ),
		);
	}

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

		if ( ! isset( $args['email'] ) || empty( $args['email'] ) ) {
			return $this->error_response( 'Email is required' );
		}

		$username = sanitize_user( $args['username'] );
		$email    = sanitize_email( $args['email'] );

		if ( username_exists( $username ) ) {
			return $this->error_response( 'Username already exists' );
		}

		if ( email_exists( $email ) ) {
			return $this->error_response( 'Email already exists' );
		}

		$password = $args['password'] ?? wp_generate_password();
		$role     = isset( $args['role'] ) ? sanitize_text_field( $args['role'] ) : 'subscriber';

		// Check if current user can assign this role
		if ( ! WordPress_Utils::can_assign_role( $role ) ) {
			return $this->error_response( 'You do not have permission to assign the role: ' . $role );
		}

		$userdata = array(
			'user_login' => $username,
			'user_email' => $email,
			'user_pass'  => $password,
			'role'       => $role,
		);

		if ( isset( $args['first_name'] ) ) {
			$userdata['first_name'] = sanitize_text_field( $args['first_name'] );
		}
		if ( isset( $args['last_name'] ) ) {
			$userdata['last_name'] = sanitize_text_field( $args['last_name'] );
		}
		if ( isset( $args['display_name'] ) ) {
			$userdata['display_name'] = sanitize_text_field( $args['display_name'] );
		}

		$user_id = wp_insert_user( $userdata );

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

		$send_notification = ! isset( $args['send_notification'] ) || true === $args['send_notification'];
		if ( $send_notification ) {
			wp_new_user_notification( $user_id, null, 'user' );
		}

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

		return $this->success_response(
			'User created successfully',
			array(
				'user_id'           => $user_id,
				'username'          => $user->user_login,
				'email'             => $user->user_email,
				'role'              => $role,
				'notification_sent' => $send_notification,
			)
		);
	}
}
