<?php

declare(strict_types=1);

namespace FormConnector\Integration\Forms\Adapters;

/**
 * Fluent Forms Adapter
 * 
 * Handles form submissions from Fluent Forms.
 */
class FluentFormsAdapter extends AbstractAdapter {

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

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

	/**
	 * Check if Fluent Forms is active
	 */
	public function is_active(): bool {
		return defined('FLUENTFORM');
	}

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

		add_action('fluentform/submission_inserted', [$this, 'handle_submission'], 10, 3);
	}

	/**
	 * Handle Fluent Forms submission
	 *
	 * @param int $entry_id Entry ID
	 * @param array $form_data Form data
	 * @param object $form Form object
	 */
	public function handle_submission(int $entry_id, array $form_data, $form): void {
		$form_id = (int) ($form->id ?? 0);
		$form_name = $form->title ?? "Form #{$form_id}";

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

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

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

	/**
	 * Extract field values from Fluent Forms data
	 *
	 * @param array $form_data Submitted form data
	 * @return array Field values keyed by field name
	 */
	private function extract_field_values(array $form_data): array {
		$values = [];

		$this->log_debug('Raw Fluent Forms data', [
			'keys' => array_keys($form_data),
			'data' => $form_data,
		]);

		foreach ($form_data as $key => $value) {
			// Skip internal fields
			if (strpos($key, '__') === 0 || $key === '_wp_http_referer' || $key === '_fluentform_') {
				continue;
			}

			// Handle name fields (array with first_name, last_name)
			if (is_array($value) && isset($value['first_name'])) {
				$first = trim($value['first_name'] ?? '');
				$last = trim($value['last_name'] ?? '');
				$middle = trim($value['middle_name'] ?? '');
				
				// Store with dot separator to match FormIntegrationManager field IDs
				// e.g., names.first_name, names.last_name
				$values[$key . '.first_name'] = $first;
				$values[$key . '.last_name'] = $last;
				$values[$key . '.middle_name'] = $middle;
				
				// Also store plain first_name/last_name for easier mapping
				if (empty($values['first_name']) && !empty($first)) {
					$values['first_name'] = $first;
				}
				if (empty($values['last_name']) && !empty($last)) {
					$values['last_name'] = $last;
				}
				
				$full_name = trim(implode(' ', array_filter([$first, $last])));
				$values[$key] = $full_name;
				
				$this->log_debug('Extracted name field', [
					'key' => $key,
					'first' => $first,
					'last' => $last,
					'stored_keys' => [$key . '.first_name', $key . '.last_name', 'first_name', 'last_name'],
				]);
				continue;
			}

			// Handle address fields (array with address_line_1, city, etc.)
			if (is_array($value) && isset($value['address_line_1'])) {
				// Use dot separator to match FormIntegrationManager
				$values[$key . '.address_line_1'] = trim($value['address_line_1'] ?? '');
				$values[$key . '.address_line_2'] = trim($value['address_line_2'] ?? '');
				$values[$key . '.city'] = trim($value['city'] ?? '');
				$values[$key . '.state'] = trim($value['state'] ?? '');
				$values[$key . '.zip'] = trim($value['zip'] ?? '');
				$values[$key . '.country'] = trim($value['country'] ?? '');
				
				$address_parts = array_filter([
					$value['address_line_1'] ?? '',
					$value['city'] ?? '',
					$value['state'] ?? '',
					$value['zip'] ?? '',
				]);
				$values[$key] = implode(', ', $address_parts);
				continue;
			}

			// Handle arrays (checkboxes, multi-select)
			if (is_array($value)) {
				$values[$key] = implode(', ', array_filter(array_map('trim', $value)));
			} else {
				$values[$key] = trim((string) $value);
			}
		}

		$this->log_debug('Extracted field values', [
			'keys' => array_keys($values),
			'values' => $values,
		]);

		return $values;
	}
}
