<?php

namespace Easymailing\App\Core\Provider\FluentForms;

use Easymailing\App\Core\Application;
use Easymailing\App\Model\Config;
use Easymailing\App\Utils\MemberPayload;
use FluentForm\App\Services\Integrations\IntegrationManager;
use FluentForm\Framework\Foundation\Application as FluentApp;
use FluentForm\Framework\Support\Arr;

class FluentFormsIntegration extends IntegrationManager
{
	private $application;

	public $hasGlobalMenu = false;

	public $disableGlobalSettings = 'yes';

	public function __construct(Application $application, $fluentApp = null)
	{
		if (!$fluentApp) {
			$fluentApp = FluentApp::getInstance();
		}

		parent::__construct(
			$fluentApp,
			'Easymailing',
			'easymailing',
			'_fluentform_easymailing_settings',
			'easymailing_feeds',
			10
		);

		$this->application = $application;
		$this->description = __('Enviar envíos de Fluent Forms a una audiencia de Easymailing.', 'easymailing');
		$this->logo = $this->application->getConfigurations()['plugin_url'].'assets/build/plugin/img/logo.svg'; // Ajusta la ruta según corresponda

		$this->registerAdminHooks();
	}

	public function getGlobalFields($fields): array
	{
		return [
			'logo'             => $this->logo,
			'menu_title'       => __('Ajustes de Easymailing', 'easymailing'),
			'menu_description' => $this->isConfigured()
				? __('El plugin de Easymailing ya está configurado.', 'easymailing')
				: __('El plugin de Easymailing no está configurado. Ve a la configuración principal.', 'easymailing'),
			'valid_message'    => __('Tu API Key de Easymailing es válida.', 'easymailing'),
			'invalid_message'  => __('Tu API Key de Easymailing no es válida.', 'easymailing'),
			'save_button_text' => '',
			'fields'           => [],
			'hide_on_valid'    => true,
			'discard_settings' => [
				'section_description' => $this->isConfigured()
					? __('El plugin de Easymailing ya está configurado.', 'easymailing')
					: '',
				'button_text'         => __('Comprobar', 'easymailing'),
				'data'                => [],
				'show_verify'         => false,
			],
		];
	}

	public function saveGlobalSettings($settings): void
	{
		wp_send_json_success([
			'message' => __('Easymailing se gestiona en el plugin principal.', 'easymailing'),
			'status'  => $this->isConfigured(),
		], 200);
	}

	public function getGlobalSettings($settings): array
	{
		return [
			'apiKey' => '',
			'status' => $this->isConfigured()
		];
	}

	public function pushIntegration($integrations, $formId): array
	{
		$integrations[$this->integrationKey] = [
			'title'                 => __('Integración de Easymailing', 'easymailing'),
			'logo'                  => $this->logo,
			'is_active'             => $this->isConfigured(),
			'configure_title'       => __('¡Configuración requerida!', 'easymailing'),
			'global_configure_url'  => admin_url('admin.php?page=fluent_forms_settings#general-easymailing-settings'),
			'configure_message'     => __('Easymailing no está configurado. Por favor, configura la API en el plugin principal.', 'easymailing'),
			'configure_button_text' => __('Configurar Easymailing', 'easymailing'),
		];
		return $integrations;
	}

	public function isConfigured(): bool
	{
		$repository = $this->application->getContainer()->get('config_repository');
		$config = $repository->getConfig();

		if($config instanceof Config){
			if($config->getApiKey()){
				return true;
			}
		}

		return false;
	}

	public function getIntegrationDefaults($settings, $formId): array
	{
		$listId = $this->app->request->get('serviceId');
		$defaults = [

			'name'              => '',
			'list_id'          => $listId,
			'merge_fields'      => (object)[],
			'other_fields' => [
				[
					'label' => '',
					'item_value' => ''
				]
			],
			'groups'            => [],
			'disable_double_opt_in' => false,
			'disable_sms_double_opt_in' => false,
			'enabled'           => true,
		];

		return wp_parse_args($settings, $defaults);
	}


	public function getSettingsFields($settings, $formId): array
	{
		$listId = $this->app->request->get('serviceId', Arr::get($settings, 'list_id'));


		$fieldSettings = [
			'button_require_list' => false,
			'integration_title'   => $this->title,
			'fields' => [
				[
					'key'         => 'name',
					'label'       => __('Nombre', 'easymailing'),
					'required'    => true,
					'placeholder' => __('Nombre de tu feed', 'easymailing'),
					'component'   => 'text',
				],
				[
					'key'         => 'list_id',
					'label'       => __('Audiencia de Easymailing', 'easymailing'),
					'placeholder' => __('Selecciona la audiencia', 'easymailing'),
					'required'    => true,
					'tips'        => __('Selecciona la audiencia de Easymailing donde deseas agregar contactos.', 'easymailing'),
					'component'   => 'refresh',
					'options'     => $this->getAudienceOptions(),
				],
				[
					'key'          => 'disable_double_opt_in',
					'label'        => __('Doble opt-in email', 'easymailing'),
					'checkbox_label'        => __('Desactivar', 'easymailing'),
					'tips'        => __('Selecciona esta opción si quieres desactivar el doble opt-in para los contactos que rellenan el formulario y se registren directamente cuando tengas activado el doble opt-in en tu audiencia', 'easymailing'),
					'component'    => 'checkbox-single',
				],
				[
					'key'          => 'disable_sms_double_opt_in',
					'label'        => __('Doble opt-in SMS', 'easymailing'),
					'checkbox_label'        => __('Desactivar', 'easymailing'),
					'tips'        => __('Selecciona esta opción solo si el formulario ya recoge consentimiento SMS válido y quieres evitar el SMS de confirmación.', 'easymailing'),
					'component'    => 'checkbox-single',
				]

			],

		];


		if ($listId) {
			$groupsField = [
				'key'         => 'groups',
				'label'       => __('Grupos', 'easymailing'),
				'is_multiple' => true,
				'require_list'   => false,
				'component'   => 'select',
				'placeholder' => __('Selecciona los grupos', 'easymailing'),
				'tips'        => __('Selecciona los grupos a los que quieres vincular los suscriptores que rellenen el formulario', 'easymailing'),
				'options'     => $this->getGroupsOptions($listId),
			];
			$fieldSettings['fields'][] = $groupsField;


			$mergeFields = [
				'key'         => 'merge_fields',
				'require_list'=> false,
				'label'       => __('Mapear campos', 'easymailing'),
				'tips'        => __('Asocia tus campos de easymailing con el formulario', 'easymailing'),
				'component'   => 'map_fields',
				'field_label_remote' => __('Campo Easymailing', 'easymailing'),
				'field_label_local'  => __('Campo del formulario', 'easymailing'),
				'primary_fileds'     => [
					[
						'key'           => 'fieldEmailAddress',
						'label'         => __('Email', 'easymailing'),
						'required'      => false,
						'input_options' => 'emails',
					],
					[
						'key'           => 'fieldPhone',
						'label'         => __('Teléfono', 'easymailing'),
						'required'      => false,
						'input_options' => 'phone',
					],
					[
						'key'           => 'fieldFirstName',
						'label'         => __('Nombre', 'easymailing'),
						'required'      => false,
					],
					[
						'key'           => 'fieldLastName',
						'label'         => __('Apellidos', 'easymailing'),
						'required'      => false,
					],
				],
			];

			$fieldSettings['fields'][] = $mergeFields;

			$otherFields = [
				'key'                => 'other_fields',
				'require_list'       => false,
				'require'       => false,
				'label'              => __('Campos personalizados', 'easymailing'),
				'tips'               => __('Mapea lso campos personalizados de Easymailing con los campos del formulario', 'easymailing'),
				'component'          => 'dropdown_many_fields',
				'field_label_remote' => __('Campo de Easymailing', 'easymailing'),
				'field_label_local'  => __('Campo del formulario', 'easymailing'),
				'options'            => $this->getCustomFields($listId)
			];

			$fieldSettings['fields'][] = $otherFields;

			$stateField  = [
				'require_list'   => false,
				'key'            => 'enabled',
				'label'          => __('Estado', 'easymailing'),
				'component'      => 'checkbox-single',
				'checkbox_label' => __('Activar este feed', 'easymailing'),
			];

			$fieldSettings['fields'][] = $stateField;

		}

		return $fieldSettings;
	}


	private function getAudienceOptions(): array
	{
		$options = [];
		try {
			$client = $this->application->getContainer()->get('api_client');
			$audiences = $client->getAudiences();
			foreach ($audiences as $audience) {
				$options[$audience->id] = $audience->title;
			}
		} catch (\Exception $e) {
			// En caso de error, devolver array vacío
		}
		return $options;
	}


	private function getGroupsOptions($listId): array
	{
		$options = [];
		try {
			$client = $this->application->getContainer()->get('api_client');
			$audiences = $client->getAudiences();
			foreach ($audiences as $audience) {
				if ($listId !== $audience->id) {
					continue;
				}
				foreach ($audience->groups as $group) {
					$options[$group->id] = $group->title;
				}
			}
		} catch (\Exception $e) {
			// En caso de error, devolver array vacío
		}
		return $options;
	}


	public function getCustomFields($audienceId): array
	{
		try {
			$client = $this->application->getContainer()->get('api_client');
			$audience = $client->getAudienceById($audienceId);
			$suscription = $client->getMySuscription();
			$locale = $suscription->locale;
		} catch (\Exception $e) {
			return [];
		}

		$fields = [];
		// Procesar los listFields
		foreach ($audience->listFields as $field) {
			$translationLabel = '';
			foreach ($field->translations as $translation) {
				if ($translation->locale === $locale) {
					$translationLabel = $translation->label;
					break;
				}
			}

			$fields[$field->id] = $translationLabel;

		}
		// Procesar treatmentPurposes
		foreach ($audience->listGdpr->treatmentPurposes as $purpose) {
			$translationLabel = '';
			foreach ($purpose->translations as $translation) {
				if ($translation->locale === $locale) {
					$translationLabel = $translation->title;
					break;
				}
			}

			$fields[$purpose->id] = $translationLabel;
		}
		return $fields;
	}

	private function normalizeType($type)
	{
		static $types = [
			'list.field.type.text'       => 'text',
			'list.field.type.select'     => 'select',
			'list.field.type.multiselect'=> 'select',
			'list.field.type.date'       => 'date',
			'list.field.type.datetime'   => 'date',
			'list.field.type.birthday'   => 'date',
			'list.field.type.textarea'   => 'textarea',
			'list.field.type.phone'      => 'tel',
			'list.field.type.url'        => 'url',
			'list.field.type.integer'    => 'number',
			'list.field.type.decimal'    => 'number',
			'list.field.type.money'      => 'number',
			'list.field.type.language'   => 'text',
			'list.field.type.boolean'    => 'acceptance',
		];
		return $types[$type] ?? 'text';
	}


	public function getMergeFields($list, $listId, $formId): array
	{
		return [];
	}


	public function notify($feed, $formData, $entry, $form): void
	{
		if (empty($feed['settings']['enabled'])) {
			return;
		}

		$dobleOptIn = $feed['processedValues']['disable_double_opt_in'] ?? false;
		$smsDobleOptIn = $feed['processedValues']['disable_sms_double_opt_in'] ?? false;
		$audience = $feed['processedValues']['list_id'] ?? '';
		$groups = $feed['processedValues']['groups'] ?? [];
		$emailField = $feed['processedValues']['fieldEmailAddress'] ?? '';
		$phoneField = $feed['processedValues']['fieldPhone'] ?? '';
		$firstNameField = $feed['processedValues']['fieldFirstName'] ?? '';
		$lastNameField = $feed['processedValues']['fieldLastName'] ?? '';
		$emailValue = $formData[$emailField] ?? '';
		$phoneValue = $formData[$phoneField] ?? '';
		$firstNameValue = $formData[$firstNameField] ?? '';
		$lastNameValue = $formData[$lastNameField] ?? '';


		$body = array_merge(MemberPayload::identityFields([
			'email' => $emailValue,
			'phone' => $phoneValue,
			'first_name' => $firstNameValue,
			'last_name' => $lastNameValue,
		]), [
			'groups'        => $groups,
			'client_ip'     => $_SERVER['REMOTE_ADDR'] ?? null,
			'custom_fields' => []
		]);

		if (!MemberPayload::hasIdentity($body)) {
			return;
		}

		$treatmentPurposes = [];

		foreach ($feed['processedValues']['other_fields'] as $localField) {

			$label = $localField['label'];
			$itemValue = $localField['item_value'];

			if (strpos($label, 'list_fields') !== false) {
				$body['custom_fields'][] = [
					'list_field' => $label,
					'value'      => $itemValue,
				];
			}
			if (strpos($label, 'treatment_purposes') !== false) {
				$treatmentPurposes[] = $label;
			}
		}

		$body['member_consent'] = [
			'ip' => $_SERVER['REMOTE_ADDR'] ?? null,
			'consent_at' => (new \DateTime("now", new \DateTimeZone("UTC")))->format('Y-m-d\TH:i:s\Z'),
		];

		if(count($treatmentPurposes) > 0){
			$body['member_consent']['treatment_purposes'] = $treatmentPurposes;
		}

		try {
			$this->application->getContainer()->get('api_client')->createMember($audience, $body, $dobleOptIn, $smsDobleOptIn);
		} catch (\Exception $e) {
			error_log('Error al crear el contacto: ' . $e->getMessage());
		}
	}
}
