<?php

// If the GF_Field class isn't available, bail.
if ( ! class_exists( 'GFForms' ) ) {
	die();
}

/**
 * Class GF_Field_MultiSelect
 *
 * Allows the creation of multiselect fields.
 *
 * @since Unknown
 *
 * @uses GF_Field
 */
class GF_Field_MultiSelect extends GF_Field {

	public $type = 'multiselect';

	/**
	 * Indicates if this field supports state validation.
	 *
	 * @since 3.0
	 *
	 * @var bool
	 */
	protected $_supports_state_validation = true;

	/**
	 * Returns the field title.
	 *
	 * @since  Unknown
	 * @access public
	 *
	 * @return string The field title. Escaped.
	 */
	public function get_form_editor_field_title() {
		return esc_attr__( 'Multi Select', 'gravityforms' );
	}

	/**
	 * Returns the field's form editor description.
	 *
	 * @since 2.5
	 *
	 * @return string
	 */
	public function get_form_editor_field_description() {
		return esc_attr__( 'Allows users to select multiple options available in the multi select box.', 'gravityforms' );
	}

	/**
	 * Returns the field's form editor icon.
	 *
	 * This could be an icon url or a gform-icon class.
	 *
	 * @since 2.5
	 *
	 * @return string
	 */
	public function get_form_editor_field_icon() {
		return 'gform-icon--multi-select';
	}

	/**
	 * Returns the class names of the settings which should be available on the field in the form editor.
	 *
	 * @since  Unknown
	 * @access public
	 *
	 * @return array Settings available within the field editor.
	 */
	function get_form_editor_field_settings() {
		return array(
			'conditional_logic_field_setting',
			'prepopulate_field_setting',
			'error_message_setting',
			'enable_enhanced_ui_setting',
			'label_setting',
			'label_placement_setting',
			'admin_label_setting',
			'size_setting',
			'choices_setting',
			'rules_setting',
			'visibility_setting',
			'description_setting',
			'css_class_setting',
		);
	}

	/**
	 * Indicates this field type can be used when configuring conditional logic rules.
	 *
	 * @return bool
	 */
	public function is_conditional_logic_supported() {
		return true;
	}

	/**
	 * Whether this field expects an array during submission.
	 *
	 * @since 2.4
	 *
	 * @return bool
	 */
	public function is_value_submission_array() {
		return true;
	}

	/**
	 * Returns the field inner markup.
	 *
	 * @since  Unknown
	 * @access public
	 *
	 * @uses GF_Field_MultiSelect::is_entry_detail()
	 * @uses GF_Field_MultiSelect::is_form_editor()
	 * @uses GF_Field_MultiSelect::get_conditional_logic_event()
	 * @uses GF_Field_MultiSelect::get_tabindex()
	 *
	 * @param array        $form  The Form Object currently being processed.
	 * @param string|array $value The field value. From default/dynamic population, $_POST, or a resumed incomplete submission.
	 * @param null|array   $entry Null or the Entry Object currently being edited.
	 *
	 * @return string The field input HTML markup.
	 */
	public function get_field_input( $form, $value = '', $entry = null ) {
		$form_id         = absint( $form['id'] );
		$is_entry_detail = $this->is_entry_detail();
		$is_form_editor  = $this->is_form_editor();

		$id       = $this->id;
		$field_id = $is_entry_detail || $is_form_editor || $form_id == 0 ? "input_$id" : 'input_' . $form_id . "_$id";

		$size          = $this->size;
		$class_suffix  = $is_entry_detail ? '_admin' : '';
		$class         = $size . $class_suffix;
		$class         = esc_attr( $class );
		$css_class     = trim( $class . ' gfield_select' );
		$tabindex      = $this->get_tabindex();
		$disabled_text = $is_form_editor ? 'disabled="disabled"' : '';
		$required_attribute = $this->isRequired ? 'aria-required="true"' : '';
		$invalid_attribute  = $this->failed_validation ? 'aria-invalid="true"' : 'aria-invalid="false"';
		$describedby_attribute = $this->get_aria_describedby();


		/**
		 * Allow the placeholder used by the enhanced ui to be overridden
		 *
		 * @since 1.9.14 Third parameter containing the field ID was added.
		 * @since Unknown
		 *
		 * @param string  $placeholder The placeholder text.
		 * @param integer $form_id     The ID of the current form.
		 */
		$placeholder = gf_apply_filters( array(
			'gform_multiselect_placeholder',
			$form_id,
			$this->id
		), __( 'Click to select...', 'gravityforms' ), $form_id, $this );
		$placeholder = $this->enableEnhancedUI ? "data-placeholder='" . esc_attr( $placeholder ) . "'" : '';

		$size = $this->multiSelectSize;
		if ( empty( $size ) ) {
			$size = 7;
		}
		$size = esc_attr( $size );

		return sprintf( "<div class='ginput_container ginput_container_multiselect'><select multiple='multiple' {$placeholder} size='{$size}' name='input_%d[]' id='%s' class='%s' $tabindex %s %s %s %s>%s</select></div>", $id, esc_attr( $field_id ), $css_class, $disabled_text, $invalid_attribute, $required_attribute, $describedby_attribute, $this->get_choices( $value ) );
	}

	/**
	 * Helper for retrieving the markup for the choices.
	 *
	 * @since  Unknown
	 * @access public
	 *
	 * @uses GFCommon::get_select_choices()
	 *
	 * @param string|array $value The field value. From default/dynamic population, $_POST, or a resumed incomplete submission.
	 *
	 * @return string Returns the choices available within the multi-select field.
	 */
	public function get_choices( $value ) {

		$value = $this->to_array( $value );

		return GFCommon::get_select_choices( $this, $value, false );

	}

	/**
	 * Format the entry value for display on the entries list page.
	 *
	 * @since  Unknown
	 * @access public
	 *
	 * @param string|array $value    The field value.
	 * @param array        $entry    The Entry Object currently being processed.
	 * @param string       $field_id The field or input ID currently being processed.
	 * @param array        $columns  The properties for the columns being displayed on the entry list page.
	 * @param array        $form     The Form Object currently being processed.
	 *
	 * @return string $value The value of the field. Escaped.
	 */
	public function get_value_entry_list( $value, $entry, $field_id, $columns, $form ) {
		// Add space after comma-delimited values.
		$value = implode( ', ', $this->to_array( $value ) );
		return esc_html( $value );
	}

	/**
	 * Format the entry value for display on the entry detail page and for the {all_fields} merge tag.
	 *
	 * @since  Unknown
	 * @since  2.9.29 Changed the second parameter $currency (string) to $entry (array).
	 *
	 * @param string|array $value    The field value.
	 * @param array        $entry    The entry.
	 * @param bool|false   $use_text When processing choice based fields should the choice text be returned instead of the value.
	 * @param string       $format   The format requested for the location the merge is being used. Possible values: html, text or url.
	 * @param string       $media    The location where the value will be displayed. Possible values: screen or email.
	 *
	 * @return string The list items, stored within an unordered list.
	 */
	public function get_value_entry_detail( $value, $entry = array(), $use_text = false, $format = 'html', $media = 'screen' ) {

		if ( $this->type === 'post_category' ) {
			$value = GFCommon::prepare_post_category_value( $value, $this, 'entry_detail' );
		}

		if ( empty( $value ) || ( $format == 'text' && $this->storageType !== 'json' ) ) {
			return $value;
		}

		$items    = $this->to_array( $value );
		$currency = rgar( $entry, 'currency' );

		foreach ( $items as &$item ) {
			$item = esc_html( GFCommon::selection_display( $item, $this, $currency, $use_text ) );
		}

		if ( $format === 'text' ) {
			return GFCommon::implode_non_blank( ', ', $items );
		}

		return "<ul class='bulleted'><li>" . GFCommon::implode_non_blank( '</li><li>', $items ) . '</li></ul>';
	}

	/**
	 * Sanitize and format the value before it is saved to the Entry Object.
	 *
	 * @since 3.0.0
	 * @since 3.0.3 Updated to use $this->prepare_post_category_value_save_input().
	 *
	 * @param string $value          The value to be saved.
	 * @param array  $form           The Form object currently being processed.
	 * @param string $input_name     The input name used when accessing the $_POST.
	 * @param int    $entry_id        The ID of the entry currently being processed.
	 * @param array  $entry           The entry currently being processed.
	 * @param string $repeater_index The repeater index if the field is inside a repeater.
	 *
	 * @return array|string The sanitized and formatted input value to be saved.
	 */
	public function get_value_save_input( $value, $form, $input_name, $entry_id, $entry, $repeater_index = '' ) {
		if ( $this->type === 'post_category' ) {
			$value = $this->prepare_post_category_value_save_input( $this->to_array( $value ) );
		} else {
			if ( is_array( $value ) ) {
				foreach ( $value as &$v ) {
					$v = $this->sanitize_entry_value( $v, $form['id'] );
				}
			} else {
				$value = $this->sanitize_entry_value( $value, $form['id'] );
			}
		}

		return empty( $value ) ? '' : $this->to_string( $value );
	}

	/**
	 * Format the entry value for when the field/input merge tag is processed.
	 *
	 * @since  Unknown
	 * @access public
	 *
	 * @uses GFCommon::format_post_category()
	 * @uses GFCommon::format_variable_value()
	 * @uses GFCommon::selection_display()
	 * @uses GFCommon::implode_non_blank()
	 *
	 * @param string|array $value      The field value. Depending on the location the merge tag is being used the following functions may have already been applied to the value: esc_html, nl2br, and urlencode.
	 * @param string       $input_id   The field or input ID from the merge tag currently being processed.
	 * @param array        $entry      The Entry Object currently being processed.
	 * @param array        $form       The Form Object currently being processed.
	 * @param string       $modifier   The merge tag modifier. e.g. value
	 * @param string|array $raw_value  The raw field value from before any formatting was applied to $value.
	 * @param bool         $url_encode Indicates if the urlencode function may have been applied to the $value.
	 * @param bool         $esc_html   Indicates if the esc_html function may have been applied to the $value.
	 * @param string       $format     The format requested for the location the merge is being used. Possible values: html, text or url.
	 * @param bool         $nl2br      Indicates if the nl2br function may have been applied to the $value.
	 *
	 * @return string $return The merge tag value.
	 */
	public function get_value_merge_tag( $value, $input_id, $entry, $form, $modifier, $raw_value, $url_encode, $esc_html, $format, $nl2br ) {
		$items = $this->to_array( $raw_value );

		$modifiers = $this->get_modifiers();

		if ( $this->type == 'post_category' ) {
			if ( is_array( $items ) ) {
				$use_id = in_array( 'id', $modifiers );

				foreach ( $items as &$item ) {
					$cat  = GFCommon::format_post_category( $item, $use_id );
					$item = GFCommon::format_variable_value( $cat, $url_encode, $esc_html, $format );
				}
			}
		} elseif ( ! in_array( 'value', $modifiers ) ) {

			foreach ( $items as &$item ) {
				$item = GFCommon::selection_display( $item, $this, rgar( $entry, 'currency' ), true );
				$item = GFCommon::format_variable_value( $item, $url_encode, $esc_html, $format );
			}
		}

		$return = GFCommon::implode_non_blank( ', ', $items );

		if ( $format == 'html' || $esc_html ) {
			$return = esc_html( $return );
		}

		return $return;
	}

	/**
	 * Format the entry value before it is used in entry exports and by framework add-ons using GFAddOn::get_field_value().
	 *
	 * @since  Unknown
	 * @access public
	 *
	 * @uses GFCommon::selection_display()
	 * @uses GFCommon::implode_non_blank()
	 *
	 * @param array      $entry    The entry currently being processed.
	 * @param string     $input_id The field or input ID.
	 * @param bool|false $use_text When processing choice based fields should the choice text be returned instead of the value.
	 * @param bool|false $is_csv   Is the value going to be used in the .csv entries export?
	 *
	 * @return string $value The value of a field from an export file.
	 */
	public function get_value_export( $entry, $input_id = '', $use_text = false, $is_csv = false ) {
		if ( empty( $input_id ) ) {
			$input_id = $this->id;
		}

		$value = rgar( $entry, $input_id );

		if ( ! empty( $value ) && ! $is_csv ) {
			$items = $this->to_array( $value );

			foreach ( $items as &$item ) {
				$item = GFCommon::selection_display( $item, $this, rgar( $entry, 'currency' ), $use_text );
			}
			$value = GFCommon::implode_non_blank( ', ', $items );

		} elseif ( $this->storageType === 'json' ) {

			$items = json_decode( $value );
			$value = GFCommon::implode_non_blank( ', ', $items );
		}

		return $value;
	}

	/**
	 * Converts an array to a string.
	 *
	 * @since 2.2.3.7 Changed access to public.
	 * @since 2.2
	 * @access public
	 *
	 * @uses \GF_Field_MultiSelect::$storageType
	 *
	 * @param array $value The array to convert to a string.
	 *
	 * @return string The converted string.
	 */
	public function to_string( $value ) {
		if ( $this->storageType === 'json' ) {
			return json_encode( $value );
		} else {
			return is_array( $value ) ? implode( ',', $value ) : $value;
		}
	}

	/**
	 * Converts a string to an array.
	 *
	 * @since 2.2.3.7 Changed access to public.
	 * @since 2.2
	 * @access public
	 *
	 * @uses \GF_Field_MultiSelect::$storageType
	 *
	 * @param string $value A comma-separated or JSON string to convert.
	 *
	 * @return array The converted array.
	 */
	public function to_array( $value ) {
		if ( empty( $value ) ) {
			return array();
		} elseif ( is_array( $value ) ) {
			return $value;
		} elseif ( $this->storageType !== 'json' || $value[0] !== '[' ) {
			return array_map( 'trim', explode( ',', $value ) );
		} else {
			$json = json_decode( $value, true );

			return $json == null ? array() : $json;
		}
	}

	/**
	 * Forces settings into expected values while saving the form object.
	 *
	 * No escaping should be done at this stage to prevent double escaping on output.
	 *
	 * Currently called only for forms created after version 1.9.6.10.
	 *
	 * @since  Unknown
	 * @access public
	 *
	 * @return void
	 *
	 */
	public function sanitize_settings() {
		parent::sanitize_settings();
		$this->enableEnhancedUI = (bool) $this->enableEnhancedUI;

		$this->storageType = empty( $this->storageType ) || $this->storageType === 'json' ? $this->storageType : 'json';

		if ( $this->type === 'post_category' ) {
			$this->displayAllCategories = (bool) $this->displayAllCategories;
		}
	}

	// # FIELD FILTER UI HELPERS ---------------------------------------------------------------------------------------

	/**
	 * Returns the filter operators for the current field.
	 *
	 * @since 2.4
	 *
	 * @return array
	 */
	public function get_filter_operators() {
		return array( 'contains' );
	}

	/**
	 * Indicates if state validation should be skipped if the submitted value is blank.
	 *
	 * @since 3.0
	 *
	 * @param string|int $key The field or input ID.
	 *
	 * @return bool
	 */
	public function skip_state_validation_if_blank( $key ) {
		return true;
	}

	/**
	 * Prepares the value that will be hashed on form display as part of the state.
	 *
	 * @since 3.0
	 *
	 * @param string|array $value The default value.
	 *
	 * @return null|array
	 */
	public function get_values_for_state_hash( $value ) {
		return array( $this->id => $this->get_choices_for_state_hash() );
	}

	/**
	 * Returns the value to use when the state is validated.
	 *
	 * @since 3.0
	 *
	 * @param string|array $value The submitted value.
	 *
	 * @return array
	 */
	public function get_value_for_state_validation( $value ) {
		return array( $this->id => $value );
	}

}

// Register the new field type.
GF_Fields::register( new GF_Field_MultiSelect() );
