<?php
/**
 * WPForms source adapter.
 *
 * @package Leadite
 */

namespace Leadite\Capture;

use Leadite\Storage\Lead;

defined( 'ABSPATH' ) || exit;

class WpformsAdapter implements SourceAdapter {

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

	public function label() {
		return 'WPForms';
	}

	public function is_available() {
		return function_exists( 'wpforms' ) || class_exists( 'WPForms' );
	}

	public function register() {
		// Runs after form processing is complete
		add_action( 'wpforms_process_complete', array( $this, 'capture' ), 10, 4 );
	}

	/**
	 * Capture hook: assemble raw payload, normalize, store.
	 *
	 * @param array $fields    Form fields data.
	 * @param array $entry     Entry values.
	 * @param array $form_data Form settings/configurations.
	 * @param int   $entry_id  Entry ID.
	 */
	public function capture( $fields, $entry, $form_data, $entry_id ) {
		$form_id   = isset( $form_data['id'] ) ? (string) $form_data['id'] : '';
		$form_name = isset( $form_data['settings']['form_title'] ) ? (string) $form_data['settings']['form_title'] : '';

		$raw = array(
			'form_id'   => $form_id,
			'form_name' => $form_name,
			'fields'    => $fields,
		);

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

	/**
	 * Pure transformation: raw WPForms fields -> normalized Lead.
	 *
	 * @param array $raw Keys: form_id, form_name, fields.
	 * @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 $f ) {
			if ( ! is_array( $f ) ) {
				continue;
			}
			$id    = isset( $f['id'] ) ? (string) $f['id'] : '';
			$name  = isset( $f['name'] ) && '' !== $f['name'] ? $f['name'] : $id;
			$value = isset( $f['value'] ) ? $f['value'] : '';
			$type  = isset( $f['type'] ) ? $f['type'] : 'text';

			$lead->add_field( $id, $value, $name, $type );

			// Capture uploaded files from WPForms (already permanently uploaded on the server)
			if ( 'file-upload' === $type && ! empty( $value ) ) {
				$urls = is_array( $value ) ? $value : ( ( false !== strpos( $value, "\n" ) ) ? explode( "\n", $value ) : explode( ',', $value ) );
				foreach ( $urls as $url ) {
					$url = trim( $url );
					if ( $url ) {
						$lead->add_attachment( $id, basename( $url ), $url, false );
					}
				}
			}
		}

		return $lead;
	}
}