<?php
/**
 * ACF BuddyPress Groups Selector
 *
 * @package Nisje
 */

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

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->name     = 'bp_groups';
		$this->label    = esc_html__( 'BuddyPress Groups', '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' ),
				],
				'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;

		$user_groups = groups_get_groups(
			[
				'type'        => 'alphabetical',
				'per_page'    => 999,
				'show_hidden' => true,
			]
		);

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

		if ( isset( $user_groups['groups'] ) ) {
			foreach ( $user_groups['groups'] as $group ) {
				$id                      = sanitize_key( $group->id );
				$field['choices'][ $id ] = esc_html( $group->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 ( 'id' === $field['return_format'] ) {
			if ( 'none' !== $value[0] ) {
				return absint( $value[0] );
			} else {
				return $value[0];
			}
		}

		return $value;
	}
}

new ACF_Field_BP_Groups();
