<?php

declare(strict_types=1);

namespace FormConnector\Integration\Forms\Adapters;

/**
 * Abstract Form Adapter Base Class
 * 
 * Provides common functionality for all form plugin adapters.
 */
abstract class AbstractAdapter {

	/**
	 * Plugin identifier key (e.g., 'gravityforms', 'cf7')
	 */
	protected string $plugin_key = '';

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

	/**
	 * Callback for processing submissions
	 * @var callable|null
	 */
	protected $submission_callback = null;

	/**
	 * Check if this form plugin is active
	 *
	 * @return bool
	 */
	abstract public function is_active(): bool;

	/**
	 * Register WordPress hooks for this adapter
	 */
	abstract public function register_hooks(): void;

	/**
	 * Get the plugin key
	 *
	 * @return string
	 */
	public function get_plugin_key(): string {
		return $this->plugin_key;
	}

	/**
	 * Get the plugin display name
	 *
	 * @return string
	 */
	public function get_plugin_name(): string {
		return $this->plugin_name;
	}

	/**
	 * Set the callback for processing submissions
	 *
	 * @param callable $callback
	 */
	public function set_submission_callback(callable $callback): void {
		$this->submission_callback = $callback;
	}

	/**
	 * Process a form submission by delegating to the callback
	 *
	 * @param int|string $form_id Form ID
	 * @param string $form_name Form name
	 * @param array $field_values Extracted field values
	 */
	protected function process_submission($form_id, string $form_name, array $field_values): void {
		if ($this->submission_callback === null) {
			$this->log_debug('No submission callback set');
			return;
		}

		// Get mapping for this form
		$mappings = new \FormConnector\Integration\Forms\Mappings();
		$mapping = $mappings->get_mapping($this->plugin_key, $form_id);

		if (empty($mapping)) {
			$this->log_debug('No mapping found for form', [
				'form_id' => $form_id,
			]);
			return;
		}

		// Call the submission handler
		call_user_func(
			$this->submission_callback,
			$this->plugin_key,
			$form_id,
			$form_name,
			$field_values,
			$mapping
		);
	}

	/**
	 * Log debug message
	 *
	 * @param string $message
	 * @param array $context
	 */
	protected function log_debug(string $message, array $context = []): void {
		if (defined('WP_DEBUG') && WP_DEBUG) {
			error_log(sprintf(
				'[FormConnector %s] %s | %s',
				$this->plugin_name,
				$message,
				wp_json_encode($context)
			));
		}
	}
}
