<?php
/**
 * REST endpoint controller for WordPress users.
 *
 * @since 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class ZINV_REST_Users {

	private string $namespace;
	private string $rest_base;

	public function __construct( string $namespace ) {
		$this->namespace = $namespace;
		$this->rest_base = 'users';
	}

	public function register(): void {
		register_rest_route( $this->namespace, '/' . $this->rest_base, [
			[
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => [ $this, 'get_items' ],
				'permission_callback' => [ $this, 'check_permission' ],
				'args'                => [
					'search' => [
						'default'           => '',
						'sanitize_callback' => 'sanitize_text_field',
					],
				],
			],
		] );
	}

	public function check_permission(): bool {
		return current_user_can( 'zinv_manage_clients' );
	}

	public function get_items( WP_REST_Request $request ): WP_REST_Response {
		$search = sanitize_text_field( $request->get_param( 'search' ) ?? '' );
		$args   = [
			'number' => 100, // Reasonable cap to keep dropdowns fast
			'fields' => [ 'ID', 'display_name', 'user_email' ],
		];

		if ( ! empty( $search ) ) {
			$args['search']         = '*' . $search . '*';
			$args['search_columns'] = [ 'user_login', 'user_nicename', 'user_email', 'display_name' ];
		}

		$users = get_users( $args );

		$data = [];
		foreach ( $users as $user ) {
			$data[] = [
				'id'           => (int) $user->ID,
				'display_name' => $user->display_name,
				'email'        => $user->user_email,
			];
		}

		return new WP_REST_Response( $data, 200 );
	}
}
