<?php

declare(strict_types=1);

namespace FormConnector\Integration\Forms\Adapters;

/**
 * Contact Form 7 Adapter
 * 
 * Handles form submissions from Contact Form 7.
 */
class ContactForm7Adapter extends AbstractAdapter {

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

	/**
	 * Plugin display name
	 */
	protected string $plugin_name = 'Contact Form 7';

	/**
	 * Check if Contact Form 7 is active
	 */
	public function is_active(): bool {
		return class_exists('WPCF7');
	}

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

		add_action('wpcf7_mail_sent', [$this, 'handle_submission'], 10, 1);
	}

	/**
	 * Handle Contact Form 7 submission
	 *
	 * @param \WPCF7_ContactForm $contact_form The form object
	 */
	public function handle_submission($contact_form): void {
		$form_id = $contact_form->id();
		$form_name = $contact_form->title();

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

		// Get submission data
		$submission = \WPCF7_Submission::get_instance();
		if (!$submission) {
			$this->log_debug('No submission instance found');
			return;
		}

		$posted_data = $submission->get_posted_data();

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

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

	/**
	 * Extract field values from CF7 posted data
	 *
	 * @param array $posted_data Posted form data
	 * @return array Field values keyed by field name
	 */
	private function extract_field_values(array $posted_data): array {
		$values = [];

		// Fields to skip (CF7 system fields)
		$skip_fields = ['_wpcf7', '_wpcf7_version', '_wpcf7_locale', '_wpcf7_unit_tag', '_wpcf7_container_post', '_wpcf7_posted_data_hash'];

		foreach ($posted_data as $key => $value) {
			// Skip system fields
			if (in_array($key, $skip_fields) || strpos($key, '_wpcf7') === 0) {
				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);
			}
		}

		return $values;
	}
}
