<?php
/**
 * Fluent Forms source adapter.
 *
 * Captures real-time form submissions via the `fluentform/submission_inserted`
 * action hook (Fluent Forms v5+). Historical submissions can be imported via
 * the existing SubmissionImporter::migrate_fluentforms() batch importer.
 *
 * @package Leadite
 */

namespace Leadite\Capture;

use Leadite\Storage\Lead;

defined( 'ABSPATH' ) || exit;

class FluentFormsAdapter implements SourceAdapter {

	public function slug() {
		return 'fluentforms';
	}

	public function label() {
		return 'Fluent Forms';
	}

	public function is_available() {
		// Works with both free and Pro; the class exists in both.
		return defined( 'FLUENTFORM' ) || class_exists( 'FluentForm\App\Models\Form' );
	}

	public function register() {
		// Fires after a submission is fully saved.
		// Signature: int $entryId, array $formData, object $form
		add_action( 'fluentform/submission_inserted', array( $this, 'capture' ), 10, 3 );
	}

	/**
	 * Capture hook: assemble raw payload, normalise, store.
	 *
	 * @param int    $entry_id  Submission (entry) ID saved by Fluent Forms.
	 * @param array  $form_data Raw field data posted by the visitor.
	 * @param object $form      Fluent Forms form object (has ->id, ->title).
	 */
	public function capture( $entry_id, $form_data, $form ) {
		$form_id   = isset( $form->id ) ? (string) $form->id : '';
		$form_name = isset( $form->title ) ? (string) $form->title : '';

		$raw = array(
			'form_id'   => $form_id,
			'form_name' => $form_name,
			'fields'    => is_array( $form_data ) ? $form_data : array(),
		);

		AdapterRegistry::store( $this->normalize( $raw ) );
	}

	/**
	 * Pure transformation: raw Fluent Forms payload → normalised Lead.
	 *
	 * Fluent Forms passes the posted field array keyed by field name.
	 * Internal keys that start with '__' (e.g. '__fluent_form_embded_post_id')
	 * are skipped, matching the behaviour of the batch importer.
	 *
	 * @param array $raw Keys: form_id, form_name, fields (assoc key => value).
	 * @return Lead
	 */
	public function normalize( array $raw ) {
		$lead            = new Lead();
		$lead->source    = $this->slug();
		$lead->form_id   = isset( $raw['form_id'] ) ? (string) $raw['form_id'] : '';
		$lead->form_name = isset( $raw['form_name'] ) ? (string) $raw['form_name'] : '';

		$fields = isset( $raw['fields'] ) && is_array( $raw['fields'] ) ? $raw['fields'] : array();

		foreach ( $fields as $key => $value ) {
			// Skip internal Fluent Forms meta fields.
			if ( strpos( (string) $key, '__' ) === 0 ) {
				continue;
			}

			if ( is_array( $value ) ) {
				$value = implode( ', ', $value );
			}

			$label = ucwords( str_replace( array( '-', '_' ), ' ', (string) $key ) );
			$type  = ( false !== strpos( strtolower( (string) $key ), 'email' ) ) ? 'email' : 'text';

			$lead->add_field( (string) $key, (string) $value, $label, $type );
		}

		return $lead;
	}
}