<?php

declare(strict_types=1);

namespace FormConnector\Integration\Forms\Adapters;

/**
 * Forminator Adapter
 * 
 * Handles form submissions from Forminator.
 */
class ForminatorAdapter extends AbstractAdapter {

	/**
	 * Plugin identifier
	 */
	protected string $plugin_key = 'forminator';

	/**
	 * Plugin display name
	 */
	protected string $plugin_name = 'Forminator';

	/**
	 * Check if Forminator is active
	 */
	public function is_active(): bool {
		return class_exists('Forminator_API');
	}

	/**
	 * Register WordPress hooks
	 */
	public function register_hooks(): void {
		if (!$this->is_active()) {
			return;
		}

		add_action('forminator_custom_form_submit_before_set_fields', [$this, 'handle_submission'], 10, 3);
	}

	/**
	 * Handle Forminator submission
	 *
	 * @param object $entry Entry object
	 * @param int $form_id Form ID
	 * @param array $field_data_array Field data array
	 */
	public function handle_submission($entry, int $form_id, array $field_data_array): void {
		$form_name = $this->get_form_name($form_id);

		$this->log_debug('Submission received', [
			'form_id' => $form_id,
			'form_name' => $form_name,
		]);

		// Extract field values
		$field_values = $this->extract_field_values($field_data_array);

		// Process the submission
		$this->process_submission($form_id, $form_name, $field_values);
	}

	/**
	 * Get form name from Forminator API
	 *
	 * @param int $form_id Form ID
	 * @return string Form name
	 */
	private function get_form_name(int $form_id): string {
		if (!class_exists('Forminator_API')) {
			return "Form #{$form_id}";
		}

		try {
			$form = \Forminator_API::get_form($form_id);
			if ($form && isset($form->settings['formName'])) {
				return $form->settings['formName'];
			}
		} catch (\Exception $e) {
			$this->log_debug('Error getting form name', ['error' => $e->getMessage()]);
		}

		return "Form #{$form_id}";
	}

	/**
	 * Extract field values from Forminator field data
	 *
	 * @param array $field_data_array Field data array
	 * @return array Field values keyed by field ID
	 */
	private function extract_field_values(array $field_data_array): array {
		$values = [];

		// Debug: Log raw field data to see what Forminator sends
		$this->log_debug('Raw Forminator field_data_array', [
			'count' => count($field_data_array),
			'raw_data' => array_map(function($f) {
				return [
					'name' => $f['name'] ?? 'NO_NAME',
					'value' => $f['value'] ?? 'NO_VALUE',
					'value_type' => is_array($f['value'] ?? null) ? 'array' : gettype($f['value'] ?? null),
				];
			}, $field_data_array),
		]);

		foreach ($field_data_array as $field_data) {
			$field_name = $field_data['name'] ?? '';
			$field_value = $field_data['value'] ?? '';

			if (empty($field_name)) {
				continue;
			}

			// Handle name fields (name-X format with first/last components)
			// FormIntegrationManager uses format: name-1-first-name, name-1-last-name
			if (strpos($field_name, 'name-') === 0) {
				if (is_array($field_value)) {
					// Multi-part name field: array with first-name, last-name keys
					$values[$field_name . '-first-name'] = trim($field_value['first-name'] ?? '');
					$values[$field_name . '-last-name'] = trim($field_value['last-name'] ?? '');
					$values[$field_name . '-prefix'] = trim($field_value['prefix'] ?? '');
					$values[$field_name . '-middle-name'] = trim($field_value['middle-name'] ?? '');
					
					// Also store combined for full_name_split support
					$full_name = trim(implode(' ', array_filter([
						$field_value['first-name'] ?? '',
						$field_value['last-name'] ?? '',
					])));
					$values[$field_name] = $full_name;
					
					// Add plain first_name/last_name for easier mapping
					$first = trim($field_value['first-name'] ?? '');
					$last = trim($field_value['last-name'] ?? '');
					if (empty($values['first_name']) && !empty($first)) {
						$values['first_name'] = $first;
					}
					if (empty($values['last_name']) && !empty($last)) {
						$values['last_name'] = $last;
					}
				} else {
					// Single-input name field: split by space into first/last
					$name_string = trim((string) $field_value);
					$values[$field_name] = $name_string;
					
					// Split into first and last name
					$name_parts = preg_split('/\s+/', $name_string, 2);
					$first_name = $name_parts[0] ?? '';
					$last_name = $name_parts[1] ?? '';
					
					$values[$field_name . '-first-name'] = $first_name;
					$values[$field_name . '-last-name'] = $last_name;
					
					// Add plain first_name/last_name for easier mapping
					if (empty($values['first_name']) && !empty($first_name)) {
						$values['first_name'] = $first_name;
					}
					if (empty($values['last_name']) && !empty($last_name)) {
						$values['last_name'] = $last_name;
					}
					
					$this->log_debug("Split single name field into parts", [
						'field' => $field_name,
						'original' => $name_string,
						'first_name' => $first_name,
						'last_name' => $last_name,
					]);
				}
				continue;
			}

			// Handle address fields
			// FormIntegrationManager uses format: address-1-street_address, address-1-city, etc.
			if (strpos($field_name, 'address-') === 0) {
				if (is_array($field_value)) {
					// Use hyphen format to match FormIntegrationManager
					$values[$field_name . '-street_address'] = trim($field_value['street_address'] ?? '');
					$values[$field_name . '-address_line'] = trim($field_value['address_line'] ?? '');
					$values[$field_name . '-city'] = trim($field_value['city'] ?? '');
					$values[$field_name . '-state'] = trim($field_value['state'] ?? '');
					$values[$field_name . '-zip'] = trim($field_value['zip'] ?? '');
					$values[$field_name . '-country'] = trim($field_value['country'] ?? '');
					
					// Also store combined
					$address_parts = array_filter([
						$field_value['street_address'] ?? '',
						$field_value['city'] ?? '',
						$field_value['state'] ?? '',
						$field_value['zip'] ?? '',
					]);
					$values[$field_name] = implode(', ', $address_parts);
				} else {
					$values[$field_name] = trim((string) $field_value);
				}
				continue;
			}

			// Handle phone fields
			if (strpos($field_name, 'phone-') === 0) {
				$values[$field_name] = trim((string) $field_value);
				continue;
			}

			// Handle email fields
			if (strpos($field_name, 'email-') === 0) {
				$values[$field_name] = trim((string) $field_value);
				continue;
			}

			// Regular fields
			if (is_array($field_value)) {
				// For multi-select, checkboxes
				$values[$field_name] = implode(', ', array_filter(array_map('trim', $field_value)));
			} else {
				$values[$field_name] = trim((string) $field_value);
			}
		}

		// Debug: Log extracted values
		$this->log_debug('Extracted field values from Forminator', [
			'keys' => array_keys($values),
			'values' => $values,
		]);

		return $values;
	}
}
