<?php
/**
 * Search customers field.
 *
 * @package YITH\Dynamic\PricingAndDiscounts\CustomFields
 * @since   4.0.0
 * @version 1.0.0
 * @author  YITH <plugins@yithemes.com>
 *
 * @var array $field
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
yith_plugin_fw_enqueue_enhanced_select();
list ( $field_id, $name, $placeholder, $multiple, $allow_clear, $value, $class, $data ) = yith_plugin_fw_extract( $field, 'id', 'name', 'placeholder', 'multiple', 'allow_clear', 'value', 'class', 'data' );

$multiple    = '' === $multiple ? false : $multiple;
$allow_clear = '' === $allow_clear ? false : $allow_clear;
$placeholder = empty( $placeholder ) ? __( 'Search for users...', 'ywdpd' ) : $placeholder;

$value       = ! is_array( $value ) ? explode( ',', $value ) : $value;
$user_string = array();
if ( ! empty( $value ) ) {
	foreach ( $value as $key => $customer_id ) {
		$user = get_user_by( 'id', $customer_id );
		if ( $user ) {
			$user_string[ $customer_id ] = esc_html( $user->display_name ) . ' (#' . absint( $user->ID ) . ' &ndash; ' . esc_html( $user->user_email );
		} else {
			unset( $value[ $key ] );
		}
	}
}

?>
<div class="ywdpd-search-customers-wrapper" <?php yith_plugin_fw_html_data_to_string( $data, true ); ?> >
	<div class="yith-plugin-fw-select2-wrapper">
		<?php
		$args = array(
			'class'            => 'wc-customer-search',
			'id'               => $field_id,
			'name'             => $name,
			'data-placeholder' => $placeholder,
			'data-allow_clear' => $allow_clear,
			'data-selected'    => $user_string,
			'data-multiple'    => $multiple,
			'value'            => implode( ',', $value ),
			'style'            => 'width:500px',
		);

		yit_add_select2_fields( $args );
		?>
	</div>
</div>
