<?php

/**
 * ACF Fluent Form Field
 *
 * Custom ACF field type for selecting Fluent Forms.
 *
 * @source: https://github.com/AdvancedCustomFields/acf-example-field-type/tree/main
 * @source: https://github.com/statenweb/Fluent-Forms-ACF-Field/blob/main/fluent_forms-v5.php
 *
 * @package FormEnhancer
 * @subpackage Integrations\AcfFluentFormField
 */

namespace FormEnhancer\Integrations\AcfFluentFormField;

use acf_field;
use Exception;

/**
 * ACF Fluent Form Field class.
 *
 * Extends ACF field to provide a dropdown for selecting Fluent Forms.
 */
class AcfFluentFormField extends acf_field
{
	/**
	 * Controls field type visibility in REST requests.
	 *
	 * @var bool
	 */
	public $show_in_rest = true;

	/**
	 * Environment values relating to the theme or plugin.
	 *
	 * @var array $env Plugin or theme context such as 'url' and 'version'.
	 */
	private $env;

	/**
	 * Constructor.
	 */
	public function __construct()
	{
		/**
		 * Field type reference used in PHP and JS code.
		 *
		 * No spaces. Underscores allowed.
		 */
		$this->name = 'fluent_form';

		/**
		 * Field type label.
		 *
		 * For public-facing UI. May contain spaces.
		 */
		$this->label = \__('Fluent Form', 'formenhancer');

		/**
		 * The category the field appears within in the field type picker.
		 */
		$this->category = 'relational';

		/**
		 * Field type Description.
		 *
		 * For field descriptions. May contain spaces.
		 */
		$this->description = \__('Adds a dropdown with all forms from Fluent Forms and returns the form ID.', 'formenhancer');

		/**
		 * Defaults for your custom user-facing settings for this field type.
		 */
		$this->defaults = [
			'form_id' => '',
		];

		$this->env = [
			'url'     => \site_url(\str_replace(\ABSPATH, '', __DIR__)), // URL to the directory.
			'version' => \FORMENHANCER_VERSION, // Plugin version.
		];

		parent::__construct();
	}

	/**
	 * Settings to display when users configure a field of this type.
	 *
	 * These settings appear on the ACF "Edit Field Group" admin page when
	 * setting up the field.
	 *
	 * @param array $field The field configuration array.
	 * @return void
	 */
	public function render_field_settings($field)
	{
		\acf_render_field_setting($field, [
			'label'   => \__('Allow Null?', 'formenhancer'),
			'type'    => 'radio',
			'name'    => 'allow_null',
			'choices' => [
				1 => \__('Yes', 'formenhancer'),
				0 => \__('No', 'formenhancer'),
			],
			'layout'  => 'horizontal'
		]);

		\acf_render_field_setting($field, [
			'label'        => \__('Return Value', 'formenhancer'),
			'instructions' => \__('Specify the returned value on front end', 'formenhancer'),
			'type'         => 'radio',
			'name'         => 'return_format',
			'layout'       => 'horizontal',
			'choices'      => [
				'form_object' => \__('Form Object', 'formenhancer'),
				'id'          => \__('Form ID', 'formenhancer')
			],
		]);
	}

	/**
	 * HTML content to show when a publisher edits the field on the edit screen.
	 *
	 * @param array $field The field settings and values.
	 * @return void
	 */
	public function render_field($field)
	{
		$field['choices'] = $this->get_forms();
		$field['type'] = 'select';

		?>
		<select id="<?php echo \esc_attr(\str_replace(['[', ']'], ['-', ''], $field['name'])); ?>" name="<?php echo \esc_attr($field['name']); ?>">
			<?php
			if ($field['allow_null']) {
				echo '<option value="">' . \esc_html__('-- Select --', 'formenhancer') . '</option>';
			}

			foreach ($field['choices'] as $key => $value) {
				$selected = '';
				if ((\is_array($field['value']) && \in_array($key, $field['value'], true)) || $field['value'] == $key) {
					$selected = ' selected="selected"';
				}
				?>
				<option value="<?php echo \esc_attr($key); ?>"<?php echo \esc_attr($selected); ?>><?php echo \esc_html($value); ?></option>
				<?php
			}
			?>
		</select>
		<?php
	}

	/**
	 * Get all forms from Fluent Forms.
	 *
	 * @return array Array of form ID => form title pairs.
	 */
	private function get_forms()
	{
		$forms = [];

		// Check if Fluent Forms API is available.
		if (!\function_exists('fluentFormApi')) {
			return $forms;
		}

		try {
			// Use FluentForm's official API to get forms.
			$fluentFormApi = \fluentFormApi('forms');
			$ff_forms_response = $fluentFormApi->forms([
				'sort_by'    => 'id',
				'sort_order' => 'DESC',
				'per_page'   => 1000, // Get all forms.
			]);

			if (!empty($ff_forms_response['data']) && \is_array($ff_forms_response['data'])) {
				foreach ($ff_forms_response['data'] as $form) {
					if (isset($form->id, $form->title)) {
						$forms[$form->id] = $form->title;
					}
				}
			}
		} catch (Exception $e) {
			// Silently handle any API errors - form list will be empty.
			// In development, you could log this: error_log('FormEnhancer ACF Field: Error fetching forms - ' . $e->getMessage()).
		}

		return $forms;
	}

	/**
	 * Format the field value for frontend display.
	 *
	 * @param mixed $value The field value.
	 * @param int   $post_id The post ID.
	 * @param array $field The field configuration array.
	 * @return mixed The formatted value.
	 */
	public function format_value($value, $post_id, $field)
	{
		if (!\is_array($field)) {
			$field = [];
		}

		if (empty($field['return_format'])) {
			$field['return_format'] = 'form_object';
		}

		// Return ID if requested or if fluentFormApi is not available.
		if ($field['return_format'] === 'id' || !\function_exists('fluentFormApi')) {
			return \intval($value);
		}

		// Return form object.
		if ($field['return_format'] === 'form_object') {
			try {
				$form = \fluentFormApi('forms')->form($value);

				// Return the form object if it's not an error object.
				if (!\is_wp_error($form)) {
					return $form;
				}
			} catch (Exception $e) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
				// Silently fail - return false below.
			}
		}

		return false;
	}
}