<?php

/**
 * Base class for fields that extend existing Fluent Forms fields.
 *
 * @package FormEnhancer\FluentForm\Fields\Abstracts
 */

namespace FormEnhancer\FluentForm\Fields\Abstracts;

use FluentForm\App\Services\FormBuilder\BaseFieldManager;
use FormEnhancer\FluentForm\Fields\Helpers\DefaultElementSettingsPlacement;
use FormEnhancer\FluentForm\Fields\Helpers\DefaultElements;

/**
 * Abstract class for creating fields based on existing Fluent Forms fields.
 *
 * Provides base functionality for extending and customizing existing field types.
 */
abstract class BasedOnExistingField extends BaseFieldManager
{
	/**
	 * The field to extend.
	 *
	 * @var string
	 */
	protected $fieldToExtendKey;

	/**
	 * The field tab.
	 *
	 * @var string
	 */
	protected $fieldToExtendTab;

	/**
	 * Constructor.
	 *
	 * @param string $key The unique field key.
	 * @param string $title The field title.
	 * @param array  $keywords Keywords for field search.
	 * @param string $section The field section.
	 * @param string $extendKey The key of field to extend.
	 * @param string $extendTab The tab of field to extend.
	 */
	public function __construct($key, $title, $keywords, $section, $extendKey = null, $extendTab = null)
	{
		parent::__construct(
			$key,
			$title,
			$keywords,
			$section
		);

		$this->fieldToExtendKey = $extendKey;
		$this->fieldToExtendTab = $extendTab;

		\add_filter('fluentform/reportable_inputs', [$this, 'pushFieldId']);
		\add_filter('fluentform/conversational_accepted_field_elements', [$this, 'pushFieldId']);
		\add_filter('fluentform/conversational_field_types', [$this, 'pushFlowField']);
	}

	/**
	 * Get the field component.
	 *
	 * @return array
	 */
	public function getComponent()
	{
		if (empty($this->fieldToExtendKey) || empty($this->fieldToExtendTab)) {
			return [];
		}

		// Load default input_radio field settings.
		$element = DefaultElements::getInstance()->getElement($this->fieldToExtendTab, $this->fieldToExtendKey);

		if ($element === false) {
			$element = [];
		}

		// Modify default input_radio field settings to match the new field.
		$element['element'] = $this->key;
		$element['attributes']['name'] = $this->key;
		$element['editor_options']['title'] = $this->title;

		return $element;
	}

	/**
	 * Get general editor elements.
	 *
	 * @return array
	 */
	public function getGeneralEditorElements()
	{
		if (empty($this->fieldToExtendKey)) {
			$elements = parent::getGeneralEditorElements();
		} else {
			$elements = DefaultElementSettingsPlacement::getInstance()->getSettingPlacement($this->fieldToExtendKey, 'general');
		}

		return $elements;
	}

	/**
	 * Get advanced editor elements.
	 *
	 * @return array
	 */
	public function getAdvancedEditorElements()
	{
		if (empty($this->fieldToExtendKey)) {
			return parent::getAdvancedEditorElements();
		}
		return DefaultElementSettingsPlacement::getInstance()->getSettingPlacement($this->fieldToExtendKey, 'advanced');
	}

	/**
	 * Add this field to the list.
	 *
	 * @param array $inputs The list of fields.
	 * @return array
	 */
	public function pushFieldId($inputs)
	{
		$inputs[] = $this->key;
		return $inputs;
	}

	/**
	 * Add this field to the list for conversational form.
	 *
	 * @param array $fields The list of fields.
	 * @return array
	 */
	public function pushFlowField($fields)
	{

		// Source: fluentform/app/Services/FluentConversational/Classes/Converter/Converter.php 678.
		$flowFieldsMapping = [
			'input_url'                      => 'FlowFormUrlType',
			'input_date'                     => 'FlowFormDateType',
			'input_text'                     => 'FlowFormTextType',
			'input_email'                    => 'FlowFormEmailType',
			'input_hidden'                   => 'FlowFormHiddenType',
			'input_number'                   => 'FlowFormNumberType',
			'select'                         => 'FlowFormDropdownType',
			'select_country'                 => 'FlowFormDropdownType',
			'textarea'                       => 'FlowFormLongTextType',
			'input_password'                 => 'FlowFormPasswordType',
			'custom_html'                    => 'FlowFormSectionBreakType',
			'section_break'                  => 'FlowFormSectionBreakType',
			'welcome_screen'                 => 'FlowFormWelcomeScreenType',
			'input_checkbox'                 => 'FlowFormMultipleChoiceType',
			'input_radio'                    => 'FlowFormMultipleChoiceType',
			'terms_and_condition'            => 'FlowFormTermsAndConditionType',
			'gdpr_agreement'                 => 'FlowFormTermsAndConditionType',
			'MultiplePictureChoice'          => 'FlowFormMultiplePictureChoiceType',
			'recaptcha'                      => 'FlowFormReCaptchaType',
			'hcaptcha'                       => 'FlowFormHCaptchaType',
			'turnstile'                      => 'FlowFormTurnstileType',
			'address'                        => 'FlowFormAddressType',
			'input_name'                     => 'FlowFormNameType',
			'ffc_custom'                     => 'FlowFormCustomType',
			'payment_method'                 => 'FlowFormPaymentMethodType',
			'multi_payment_component'        => 'FlowFormPaymentType',
			'custom_payment_component'       => 'FlowFormPaymentType',
			'item_quantity_component'        => 'FlowFormPaymentType',
			'payment_summary_component'      => 'FlowFormPaymentSummaryType',
			'subscription_payment_component' => 'FlowFormSubscriptionType',
			'phone'                          => 'FlowFormPhoneType',
			'input_image'                    => 'FlowFormFileType',
			'input_file'                     => 'FlowFormFileType',
			'ratings'                        => 'FlowFormRateType',
			'tabular_grid'                   => 'FlowFormMatrixType',
			'payment_coupon'                 => 'FlowFormCouponType',
			'quiz_score'                     => 'FlowFormHiddenType',
			'rangeslider'                    => 'FlowFormRangesliderType',
			'save_progress_button'           => 'FlowFormSaveAndResumeType',
			'dynamic_field'                  => 'FlowFormDynamicFieldType',
		];

		if (isset($flowFieldsMapping[$this->fieldToExtendKey])) {
			$fields[$this->key] = $flowFieldsMapping[$this->fieldToExtendKey];
		}

		return $fields;
	}
}
