<?php
/**
 * ACF BuddyPress Member Types Selector
 *
 * @package Nisje
 */

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

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

		$this->defaults = [
			'return_format' => 'id',
			'multiple'      => 0,
			'allow_null'    => 0,
		];

		$this->l10n = [];

		parent::__construct();
	}

	/**
	 * 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' ),
				'object' => esc_html__( 'Object', '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['ui']      = 0;
		$field['ajax']    = 0;

		$member_types = bp_get_member_types( [], 'object' );

		$field['choices']['none'] = esc_html__( 'Not connected to a member type', 'nisje' );

		if ( $member_types ) {
			foreach ( $member_types as $member_type ) {
				$name = sanitize_key( $member_type->name );

				$field['choices'][ $name ] = esc_html( $member_type->labels['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 );

		if ( 'object' === $field['return_format'] ) {
			$value = bp_get_member_type_object( $value );
		}

		return $value;
	}
}

new ACF_Field_BP_Member_Types();
