<?php

declare(strict_types=1);

namespace FormConnector\Integration\Forms\Adapters;

/**
 * Gravity Forms Adapter
 * 
 * Handles form submissions from Gravity Forms.
 */
class GravityFormsAdapter extends AbstractAdapter {

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

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

	/**
	 * Check if Gravity Forms is active
	 */
	public function is_active(): bool {
		return class_exists('GFAPI');
	}

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

		add_action('gform_after_submission', [$this, 'handle_submission'], 10, 2);
	}

	/**
	 * Handle Gravity Forms submission
	 *
	 * @param array $entry The entry data
	 * @param array $form The form data
	 */
	public function handle_submission(array $entry, array $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,
		]);

		// Extract field values
		$field_values = $this->extract_field_values($entry, $form);

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

	/**
	 * Extract field values from Gravity Forms entry
	 *
	 * @param array $entry Entry data
	 * @param array $form Form configuration
	 * @return array Field values keyed by field ID
	 */
	private function extract_field_values(array $entry, array $form): array {
		$values = [];

		foreach ($form['fields'] as $field) {
			$field_id = $field->id;
			$field_type = $field->type ?? '';

			// Handle name fields (has sub-fields like .3, .6)
			if ($field_type === 'name') {
				// First name is typically .3, Last name is .6
				$first = trim($entry["{$field_id}.3"] ?? '');
				$last = trim($entry["{$field_id}.6"] ?? '');
				$prefix = trim($entry["{$field_id}.2"] ?? '');
				$middle = trim($entry["{$field_id}.4"] ?? '');
				$suffix = trim($entry["{$field_id}.8"] ?? '');

				$values["field_{$field_id}.3"] = $first;
				$values["field_{$field_id}.6"] = $last;
				$values["field_{$field_id}.2"] = $prefix;
				$values["field_{$field_id}.4"] = $middle;
				$values["field_{$field_id}.8"] = $suffix;
				
				// Also store combined for full_name_split
				$values["field_{$field_id}"] = trim("{$first} {$last}");
				
				// Add 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;
				}
				continue;
			}

			// Handle address fields
			if ($field_type === 'address') {
				$values["field_{$field_id}.1"] = trim($entry["{$field_id}.1"] ?? ''); // Street
				$values["field_{$field_id}.2"] = trim($entry["{$field_id}.2"] ?? ''); // Street 2
				$values["field_{$field_id}.3"] = trim($entry["{$field_id}.3"] ?? ''); // City
				$values["field_{$field_id}.4"] = trim($entry["{$field_id}.4"] ?? ''); // State
				$values["field_{$field_id}.5"] = trim($entry["{$field_id}.5"] ?? ''); // ZIP
				$values["field_{$field_id}.6"] = trim($entry["{$field_id}.6"] ?? ''); // Country
				continue;
			}

			// Handle checkbox fields (multi-value)
			if ($field_type === 'checkbox' && !empty($field->inputs)) {
				$checkbox_values = [];
				foreach ($field->inputs as $input) {
					$input_id = $input['id'];
					if (!empty($entry[$input_id])) {
						$checkbox_values[] = $entry[$input_id];
					}
				}
				$values["field_{$field_id}"] = implode(', ', $checkbox_values);
				continue;
			}

			// Regular single-value fields
			$value = $entry[$field_id] ?? '';
			if (is_array($value)) {
				$value = implode(', ', $value);
			}
			$values["field_{$field_id}"] = trim((string) $value);
		}

		return $values;
	}
}
