<?php

/**
 * ACF Fluent Form Field Bootstrap
 *
 * Handles registration and initialization of the ACF Fluent Form field.
 *
 * @package FormEnhancer
 * @subpackage Integrations\AcfFluentFormField
 */

namespace FormEnhancer\Integrations\AcfFluentFormField;

/**
 * Bootstrap class for ACF Fluent Form field integration.
 *
 * This class handles the registration and initialization of the custom ACF field
 * for selecting Fluent Forms.
 */
class Bootstrap
{
	/**
	 * Initialize the ACF integration.
	 *
	 * @return void
	 */
	public function init()
	{
		// Check if ACF is available.
		if (!$this->is_acf_available()) {
			return;
		}

		// Register the field.
		\add_action('acf/include_field_types', [$this, 'register_field']);
	}

	/**
	 * Check if ACF is available.
	 *
	 * @return bool True if ACF is available, false otherwise.
	 */
	private function is_acf_available()
	{
		// Check for ACF Free or Pro.
		return \class_exists('ACF') || \function_exists('acf');
	}

	/**
	 * Register the custom field type with ACF.
	 *
	 * @return void
	 */
	public function register_field()
	{
		new AcfFluentFormField();
	}

	/**
	 * Check if ACF integration is active.
	 *
	 * @return bool True if ACF is active and integration is available.
	 */
	public static function is_active()
	{
		return \class_exists('ACF') || \function_exists('acf');
	}

	/**
	 * Get Custom Fields integration status information.
	 *
	 * @return array Status information array.
	 */
	public static function get_status()
	{
		$status = [
			'active' => self::is_active(),
			'plugin' => 'Not detected',
			'version' => null,
		];

		// Check for Secure Custom Fields (SCF) first.
		if (self::is_scf_active()) {
			$status['plugin'] = 'Secure Custom Fields';
			$status['version'] = \defined('ACF_VERSION') ? \ACF_VERSION : 'Unknown';
		} elseif (\class_exists('ACF') && \defined('ACF_PRO')) {
			// Check for Advanced Custom Fields Pro.
			$status['plugin'] = 'Advanced Custom Fields Pro';
			$status['version'] = \defined('ACF_VERSION') ? \ACF_VERSION : 'Unknown';
		} elseif (\class_exists('ACF')) {
			// Check for Advanced Custom Fields Free.
			$status['plugin'] = 'Advanced Custom Fields';
			$status['version'] = \defined('ACF_VERSION') ? \ACF_VERSION : 'Unknown';
		} elseif (\function_exists('acf')) {
			// Legacy ACF detection.
			$status['plugin'] = 'Advanced Custom Fields (legacy)';
			$status['version'] = \function_exists('acf_get_setting') ? \acf_get_setting('version') : 'Unknown';
		}

		return $status;
	}

	/**
	 * Check if Secure Custom Fields (SCF) is active.
	 *
	 * @return bool True if SCF is active, false otherwise.
	 */
	private static function is_scf_active()
	{
		// Check if SCF plugin is active.
		if (!\function_exists('is_plugin_active')) {
			include_once(\ABSPATH . 'wp-admin/includes/plugin.php');
		}

		return \is_plugin_active('secure-custom-fields/secure-custom-fields.php');
	}
}
