<?php

namespace Easymailing\App\Core\Provider;

use Easymailing\App\Core\Application;
use Easymailing\App\Core\Provider\FluentForms\FluentFormsIntegration;

/**
 * Provider para integrar Easymailing con Fluent Forms, similar a ElementorFormActionProvider
 */
class FluentFormsActionProvider implements ProviderInterface
{
	private $application;
	private $registered = false;

	public function __construct(Application $application)
	{
		$this->application = $application;
	}

	public function register()
	{
		// Verificar si Fluent Forms está activo
		include_once(ABSPATH . 'wp-admin/includes/plugin.php');
		if (!is_plugin_active('fluentform/fluentform.php')) {
			return;
		}

		// Cuando Fluent Forms termine de cargarse
		add_action('fluentform/loaded', function($fluentApp) {
			$this->registerIntegration($fluentApp);
		});

		// Compatibilidad con versiones anteriores de Fluent Forms
		add_action('fluentform_loaded', function($fluentApp) {
			$this->registerIntegration($fluentApp);
		});
	}

	private function registerIntegration($fluentApp = null)
	{
		if ($this->registered) {
			return;
		}
		$this->registered = true;

		try {
			new FluentFormsIntegration($this->application, $fluentApp);
		} catch (\Throwable $e) {
			error_log('Easymailing: Error loading Fluent Forms integration: ' . $e->getMessage());
		}
	}

	public static function shouldRegister(): bool
	{
		return true;
	}
}
