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

namespace Leadite\Capture;

use Leadite\Storage\Lead;

defined( 'ABSPATH' ) || exit;

class GravityFormsAdapter implements SourceAdapter {

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

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

	public function is_available() {
		return class_exists( 'GFAPI' ) || class_exists( 'GFCommon' );
	}

	public function register() {
		// Runs after form entry submission is saved
		add_action( 'gform_after_submission', array( $this, 'capture' ), 10, 2 );
	}

	/**
	 * Capture hook: assemble raw payload, normalize, store.
	 *
	 * @param array $entry Entry data.
	 * @param array $form  Form settings.
	 */
	public function capture( $entry, $form ) {
		$form_id    = isset( $form['id'] ) ? (string) $form['id'] : '';
		$form_title = isset( $form['title'] ) ? (string) $form['title'] : '';

		$fields = array();
		if ( ! empty( $form['fields'] ) && is_array( $form['fields'] ) ) {
			foreach ( $form['fields'] as $field ) {
				$value = '';
				if ( method_exists( $field, 'is_value_submission_array' ) && $field->is_value_submission_array( $form['id'] ) ) {
					if ( method_exists( $field, 'get_value_export' ) ) {
						$value = $field->get_value_export( $entry );
					}
				} else {
					$value = isset( $entry[ $field->id ] ) ? $entry[ $field->id ] : '';
				}

				$fields[] = array(
					'id'    => (string) $field->id,
					'label' => $field->label,
					'type'  => $field->type,
					'value' => $value,
				);
			}
		}

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

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

	/**
	 * Pure transformation: raw Gravity Forms 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'] : '';
			$label = isset( $f['label'] ) && '' !== $f['label'] ? $f['label'] : $id;
			$value = isset( $f['value'] ) ? $f['value'] : '';
			$type  = isset( $f['type'] ) ? $f['type'] : 'text';

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

			// Capture uploaded files from Gravity Forms (stored permanently in uploads/gravity_forms/)
			if ( 'fileupload' === $type && ! empty( $value ) ) {
				$urls = array();
				if ( false !== strpos( $value, '[' ) && false !== strpos( $value, ']' ) ) {
					$decoded = json_decode( $value, true );
					if ( is_array( $decoded ) ) {
						$urls = $decoded;
					}
				}
				if ( empty( $urls ) ) {
					$urls = explode( ',', $value );
				}

				foreach ( $urls as $url ) {
					$url = trim( $url );
					if ( $url ) {
						$lead->add_attachment( $id, basename( $url ), $url, false );
					}
				}
			}
		}

		return $lead;
	}
}