<?php
/**
 * ACF BuddyPress Profile Fields Selector
 *
 * @package Nisje
 */

/**
 * Field Class.
 */
class ACF_Field_BP_Profile_Fields extends acf_field {

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->name     = 'bp_profile_fields';
		$this->label    = esc_html__( 'BuddyPress Profile Fields', 'nisje' );
		$this->category = 'relational';

		$this->defaults = [
			'return_format' => 'array',
			'multiple'      => 1,
			'allow_null'    => 0,
			'ui'            => 0,
			'placeholder'   => '',
		];

		$this->l10n = [
			'matches_1'            => _x( 'One result is available, press enter to select it.', 'Select2 JS matches_1', 'nisje' ),
			// translators: %d Select2 JS matches_n.
			'matches_n'            => _x( '%d results are available, use up and down arrow keys to navigate.', 'Select2 JS matches_n', 'nisje' ),
			'matches_0'            => _x( 'No matches found', 'Select2 JS matches_0', 'nisje' ),
			'input_too_short_1'    => _x( 'Please enter 1 or more characters', 'Select2 JS input_too_short_1', 'nisje' ),
			// translators: %d Select2 JS input_too_short_n.
			'input_too_short_n'    => _x( 'Please enter %d or more characters', 'Select2 JS input_too_short_n', 'nisje' ),
			'input_too_long_1'     => _x( 'Please delete 1 character', 'Select2 JS input_too_long_1', 'nisje' ),
			// translators: %d Select2 JS input_too_long_n.
			'input_too_long_n'     => _x( 'Please delete %d characters', 'Select2 JS input_too_long_n', 'nisje' ),
			'selection_too_long_1' => _x( 'You can only select 1 item', 'Select2 JS selection_too_long_1', 'nisje' ),
			// translators: %d Select2 JS selection_too_long_n.
			'selection_too_long_n' => _x( 'You can only select %d items', 'Select2 JS selection_too_long_n', 'nisje' ),
			'load_more'            => _x( 'Loading more results&hellip;', 'Select2 JS load_more', 'nisje' ),
			'searching'            => _x( 'Searching&hellip;', 'Select2 JS searching', 'nisje' ),
			'load_fail'            => _x( 'Loading failed', 'Select2 JS load_fail', 'nisje' ),
		];

		parent::__construct();
	}

	/**
	 * Admin Enqueue Scripts.
	 */
	public function input_admin_enqueue_scripts() {
		global $wp_scripts, $wp_styles;

		$version = '3.5.2';
		$min     = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';

		wp_enqueue_script( 'select2', acf_get_url( "assets/inc/select2/select2{$min}.js" ), [ 'jquery' ], $version, true );
		wp_enqueue_style( 'select2', acf_get_url( 'assets/inc/select2/select2.css' ), '', $version );
	}

	/**
	 * Register field settings
	 *
	 * @param string $field Current field.
	 */
	public function render_field_settings( $field ) {
		acf_render_field_setting(
			$field, [
				'label'        => esc_html__( 'Return Format', 'nisje' ),
				'instructions' => '',
				'type'         => 'radio',
				'name'         => 'return_format',
				'choices'      => [
					'id' => esc_html__( 'Id', 'nisje' ),
				],
				'layout'       => 'horizontal',
			]
		);

		// multiple.
		acf_render_field_setting(
			$field, [
				'label'        => esc_html__( 'Select multiple values?', 'nisje' ),
				'instructions' => '',
				'type'         => 'radio',
				'name'         => 'multiple',
				'choices'      => [
					1 => esc_html__( 'Yes', 'nisje' ),
					0 => esc_html__( 'No', 'nisje' ),
				],
				'layout'       => 'horizontal',
			]
		);

		// ui.
		acf_render_field_setting(
			$field, [
				'label'        => esc_html__( 'Stylised UI', 'nisje' ),
				'instructions' => '',
				'type'         => 'radio',
				'name'         => 'ui',
				'choices'      => [
					1 => esc_html__( 'Yes', 'nisje' ),
					0 => esc_html__( 'No', 'nisje' ),
				],
				'layout'       => 'horizontal',
			]
		);
	}

	/**
	 * Render field
	 *
	 * @param string $field Current field.
	 */
	public function render_field( $field ) {

		$field = array_merge( $this->defaults, $field );

		// Change Field into a select.
		$field['type']    = 'select';
		$field['choices'] = [];
		$field['ajax']    = 0;

		$query_args = [
			'hide_empty_groups'      => true,
			'hide_empty_fields'      => false,
			'fetch_fields'           => true,
			'fetch_visibility_level' => true,
		];

		$field_groups = bp_xprofile_get_groups( $query_args );

		foreach ( $field_groups as $field_group ) {
			$name = esc_attr( $field_group->name );

			foreach ( $field_group->fields as $xfield ) {
				if ( 'public' === $xfield->visibility_level ) {
					$id                               = (int) $xfield->id;
					$field['choices'][ $name ][ $id ] = esc_html( $xfield->name );
				}
			}
		}

		// phpcs:disable WordPress.NamingConventions.ValidHookName.UseUnderscores
		do_action( 'acf/render_field/type=select', $field );
		// phpcs:enable
	}

	/**
	 * Format value
	 *
	 * @param mixed  $value   Current value.
	 * @param string $post_id Post ID.
	 * @param string $field   Current field.
	 *
	 * @return mixed Optimized value.
	 */
	public function format_value( $value, $post_id, $field ) {

		// bail early if no value.
		if ( empty( $value ) ) {
			return $value;
		}

		// force value to array.
		$value = acf_get_array( $value );

		return $value;
	}
}

new ACF_Field_BP_Profile_Fields();
