<?php
/**
 * List Users Tool.
 *
 * Retrieve lists of site users with filtering by role, search, and pagination
 * using WP_User_Query.
 *
 * @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;
}

/**
 * List_Users_Tool class.
 */
class List_Users_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'List site users with optional filtering.';
	}

	/**
	 * 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(
				'role'    => array(
					'type'        => 'string',
					'description' => 'Filter by role (e.g., administrator, editor, author, contributor, subscriber)',
				),
				'search'  => array(
					'type'        => 'string',
					'description' => 'Search term to find in username, email, or display name',
				),
				'limit'   => array(
					'type'        => 'integer',
					'description' => 'Maximum number of users to return',
					'default'     => 20,
				),
				'offset'  => array(
					'type'        => 'integer',
					'description' => 'Number of users to skip',
					'default'     => 0,
				),
				'orderby' => array(
					'type'        => 'string',
					'description' => 'Field to order by',
					'enum'        => array( 'ID', 'login', 'nicename', 'email', 'registered', 'display_name' ),
					'default'     => 'display_name',
				),
				'order'   => array(
					'type'        => 'string',
					'description' => 'Order direction',
					'enum'        => array( 'ASC', 'DESC' ),
					'default'     => 'ASC',
				),
			),
			'required'   => array(),
		);
	}

	/**
	 * 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( 'list_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 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 ) {
		$query_args = array(
			'number'  => isset( $args['limit'] ) ? intval( $args['limit'] ) : 20,
			'offset'  => isset( $args['offset'] ) ? intval( $args['offset'] ) : 0,
			'orderby' => $args['orderby'] ?? 'display_name',
			'order'   => $args['order'] ?? 'ASC',
		);

		if ( isset( $args['role'] ) && ! empty( $args['role'] ) ) {
			$query_args['role'] = sanitize_text_field( $args['role'] );
		}

		if ( isset( $args['search'] ) && ! empty( $args['search'] ) ) {
			$query_args['search']         = '*' . sanitize_text_field( $args['search'] ) . '*';
			$query_args['search_columns'] = array( 'user_login', 'user_email', 'display_name' );
		}

		$user_query = new \WP_User_Query( $query_args );
		$users      = $user_query->get_results();

		if ( empty( $users ) ) {
			return $this->success_response(
				'No users found',
				array(
					'users'    => array(),
					'count'    => 0,
					'total'    => 0,
					'limit'    => intval( $query_args['number'] ),
					'offset'   => intval( $query_args['offset'] ),
					'has_more' => false,
				)
			);
		}

		$user_list = array();
		foreach ( $users as $user ) {
			$user_list[] = array(
				'id'           => $user->ID,
				'username'     => $user->user_login,
				'email'        => $user->user_email,
				'display_name' => $user->display_name,
				'roles'        => $user->roles,
				'registered'   => $user->user_registered,
			);
		}

		$limit  = intval( $query_args['number'] );
		$offset = intval( $query_args['offset'] );

		return $this->success_response(
			'Users retrieved successfully',
			array(
				'users'    => $user_list,
				'count'    => count( $user_list ),
				'total'    => $user_query->get_total(),
				'limit'    => $limit,
				'offset'   => $offset,
				'has_more' => ( $offset + count( $user_list ) ) < $user_query->get_total(),
			)
		);
	}
}
