<?php
/**
 * Elementor Pro Forms source adapter.
 *
 * @package Leadite
 */

namespace Leadite\Capture;

use Leadite\Storage\Lead;

defined( 'ABSPATH' ) || exit;

class ElementorAdapter implements SourceAdapter {

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

	public function label() {
		return 'Elementor Pro';
	}

	public function is_available() {
		// The form widget + new_record action exist only in Elementor Pro.
		return defined( 'ELEMENTOR_PRO_VERSION' );
	}

	public function register() {
		// Priority 10, two args: record + ajax handler.
		add_action( 'elementor_pro/forms/new_record', array( $this, 'capture' ), 10, 2 );
	}

	/**
	 * Capture hook: assemble raw payload from the record, normalize, store.
	 *
	 * @param \ElementorPro\Modules\Forms\Classes\Form_Record  $record  Submission record.
	 * @param \ElementorPro\Modules\Forms\Classes\Ajax_Handler $handler Ajax handler.
	 */
	public function capture( $record, $handler ) {
		if ( ! is_object( $record ) || ! method_exists( $record, 'get' ) ) {
			return;
		}

		$raw_fields = $record->get( 'fields' );
		if ( empty( $raw_fields ) || ! is_array( $raw_fields ) ) {
			return;
		}

		$form_name = '';
		$form_id   = '';
		if ( method_exists( $record, 'get_form_settings' ) ) {
			$form_name = (string) $record->get_form_settings( 'form_name' );
			$form_id   = (string) $record->get_form_settings( 'id' );
		}

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

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

	/**
	 * Pure transformation: raw Elementor record 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 $key => $field ) {
			$label = isset( $field['title'] ) && '' !== $field['title'] ? $field['title'] : $key;
			$value = isset( $field['value'] ) ? $field['value'] : '';
			$type  = isset( $field['type'] ) ? $field['type'] : 'text';
			$lead->add_field( $key, $value, $label, $type );

			// Capture uploaded files from Elementor (already permanently uploaded)
			if ( 'upload' === $type && ! empty( $value ) ) {
				$urls = is_array( $value ) ? $value : explode( ',', $value );
				foreach ( $urls as $url ) {
					$url = trim( $url );
					if ( $url ) {
						$lead->add_attachment( $key, basename( $url ), $url, false );
					}
				}
			}
		}

		return $lead;
	}
}