<?php
/**
 * Agile CRM Transformer
 *
 * Custom transformer for Agile CRM integration
 * Handles complex property structure required by Agile CRM API
 *
 * @package SureForms
 * @since 1.13.0
 */

namespace SRFM_Pro\Inc\Pro\Native_Integrations\Transformers;

use SRFM\Inc\Helper;
use SRFM_Pro\Inc\Pro\Native_Integrations\Interfaces\Payload_Transformer;
use SRFM_Pro\Inc\Pro\Native_Integrations\Services\Workflow_Processor;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Agile CRM Transformer class.
 *
 * @since 1.13.0
 */
class Agile_CRM_Transformer implements Payload_Transformer {
	/**
	 * Integration name
	 *
	 * @var string
	 */
	private $integration_name = 'agile-crm';

	/**
	 * Get integration name this transformer handles
	 *
	 * @return string Integration name.
	 * @since 1.13.0
	 */
	public function get_integration_name() {
		return $this->integration_name;
	}

	/**
	 * Transform payload for Agile CRM integration
	 *
	 * @param array $form_data Original form data.
	 * @param array $field_mappings Field mappings configuration.
	 * @param array $context Additional context data.
	 * @return array Transformed payload for Agile CRM API.
	 * @since 1.13.0
	 */
	public function transform( $form_data, $field_mappings = [], $context = [] ) {
		unset( $field_mappings ); // Unused.
		$action_name = $context['action_name'] ?? '';

		switch ( $action_name ) {
			case 'Create Contact':
				return $this->transform_create_contact( $form_data );
			case 'Create Company':
				return $this->transform_create_company( $form_data );
			default:
				return $form_data;
		}
	}

	/**
	 * Prepare test payload with sample data
	 *
	 * @param array $workflow_fields Fields from the workflow configuration.
	 * @param array $field_definitions Field definitions from the action configuration.
	 * @return array Test payload.
	 * @since 1.13.0
	 */
	public function prepare_test_payload( $workflow_fields, $field_definitions ) {
		$payload = [];

		// Generate test payload based on field definitions.
		foreach ( $field_definitions as $field_def ) {
			$field_key = $field_def['key'] ?? '';

			if ( empty( $field_key ) ) {
				continue;
			}

			// Skip fields that are excluded from payload.
			$exclude_from_payload = $field_def['exclude_from_payload'] ?? false;
			if ( $exclude_from_payload ) {
				continue;
			}

			// Get field value or generate test data.
			if ( isset( $workflow_fields[ $field_key ] ) && ! empty( $workflow_fields[ $field_key ] ) ) {
				$payload[ $field_key ] = $workflow_fields[ $field_key ];
			} else {
				$payload[ $field_key ] = Workflow_Processor::generate_test_value( $field_def );
			}
		}

		// Apply the same transformation logic as the main transform method.
		// We need to determine the action name from the context.
		$action_name = $this->get_action_name_from_field_definitions( $field_definitions );

		// Use the same transformation logic as the main method.
		$context = [ 'action_name' => $action_name ];
		return $this->transform( $payload, [], $context );
	}

	/**
	 * Transform data for Create Contact action
	 *
	 * @param array $form_data Form data.
	 * @return array Transformed payload.
	 * @since 1.13.0
	 */
	private function transform_create_contact( $form_data ) {
		$payload = [
			'type'       => 'PERSON',
			'properties' => [],
		];

		// Add tags if provided.
		if ( ! empty( $form_data['tags'] ) ) {
			$tags = $this->convert_tags_to_array( $form_data['tags'] );
			if ( ! empty( $tags ) ) {
				$payload['tags'] = $tags;
			}
		}

		// Add system properties.
		$properties = [];

		// First name (required by Agile CRM).
		if ( ! empty( $form_data['first_name'] ) ) {
			$properties[] = [
				'type'  => 'SYSTEM',
				'name'  => 'first_name',
				'value' => Helper::get_string_value( $form_data['first_name'] ),
			];
		}

		// Last name.
		if ( ! empty( $form_data['last_name'] ) ) {
			$properties[] = [
				'type'  => 'SYSTEM',
				'name'  => 'last_name',
				'value' => Helper::get_string_value( $form_data['last_name'] ),
			];
		}

		// Email.
		if ( ! empty( $form_data['email'] ) ) {
			$properties[] = [
				'type'    => 'SYSTEM',
				'name'    => 'email',
				'subtype' => 'work',
				'value'   => Helper::get_string_value( $form_data['email'] ),
			];
		}

		// Phone.
		if ( ! empty( $form_data['phone'] ) ) {
			$properties[] = [
				'name'    => 'phone',
				'value'   => Helper::get_string_value( $form_data['phone'] ),
				'subtype' => 'work',
			];
		}

		// Company.
		if ( ! empty( $form_data['company'] ) ) {
			$properties[] = [
				'name'  => 'Company',
				'type'  => 'SYSTEM',
				'value' => Helper::get_string_value( $form_data['company'] ),
			];
		}

		// Website.
		if ( ! empty( $form_data['website'] ) ) {
			$properties[] = [
				'name'    => 'website',
				'value'   => Helper::get_string_value( $form_data['website'] ),
				'subtype' => 'URL',
			];
		}

		// Address (JSON-encoded string).
		$address_fields = [ 'address', 'city', 'state', 'zip_code', 'country' ];
		$address_data   = [];
		foreach ( $address_fields as $field ) {
			if ( ! empty( $form_data[ $field ] ) ) {
				$address_key                  = 'zip_code' === $field ? 'zip' : $field;
				$address_data[ $address_key ] = Helper::get_string_value( $form_data[ $field ] );
			}
		}

		if ( ! empty( $address_data ) ) {
			$properties[] = [
				'type'  => 'SYSTEM',
				'name'  => 'address',
				'value' => wp_json_encode( $address_data ),
			];
		}

		$payload['properties'] = $properties;

		return $payload;
	}

	/**
	 * Transform data for Create Company action
	 *
	 * @param array $form_data Form data.
	 * @return array Transformed payload.
	 * @since 1.13.0
	 */
	private function transform_create_company( $form_data ) {
		$payload = [
			'type'       => 'COMPANY',
			'properties' => [],
		];

		// Add tags if provided.
		if ( ! empty( $form_data['tags'] ) ) {
			$tags = $this->convert_tags_to_array( $form_data['tags'] );
			if ( ! empty( $tags ) ) {
				$payload['tags'] = $tags;
			}
		}

		$properties = [];

		// Company name (required).
		if ( ! empty( $form_data['company_name'] ) ) {
			$properties[] = [
				'type'  => 'SYSTEM',
				'name'  => 'name',
				'value' => Helper::get_string_value( $form_data['company_name'] ),
			];
		}

		// Phone.
		if ( ! empty( $form_data['phone'] ) ) {
			$properties[] = [
				'name'    => 'phone',
				'value'   => Helper::get_string_value( $form_data['phone'] ),
				'subtype' => '',
			];
		}

		// Website URL.
		if ( ! empty( $form_data['website_url'] ) ) {
			$properties[] = [
				'type'  => 'SYSTEM',
				'name'  => 'url',
				'value' => Helper::get_string_value( $form_data['website_url'] ),
			];
		}

		// LinkedIn URL.
		if ( ! empty( $form_data['linkedin_url'] ) ) {
			$properties[] = [
				'name'    => 'website',
				'value'   => Helper::get_string_value( $form_data['linkedin_url'] ),
				'subtype' => 'LINKEDIN',
			];
		}

		// Address.
		$address_fields = [ 'address', 'city', 'state', 'zip_code', 'country' ];
		$address_data   = [];
		foreach ( $address_fields as $field ) {
			if ( ! empty( $form_data[ $field ] ) ) {
				$address_key                  = 'zip_code' === $field ? 'zip' : $field;
				$address_data[ $address_key ] = Helper::get_string_value( $form_data[ $field ] );
			}
		}

		if ( ! empty( $address_data ) ) {
			$properties[] = [
				'name'    => 'address',
				'value'   => wp_json_encode( $address_data ),
				'subtype' => 'office',
			];
		}

		$payload['properties'] = $properties;

		return $payload;
	}

	/**
	 * Determine action name from field definitions
	 *
	 * @param array $field_definitions Field definitions array.
	 * @return string Action name.
	 * @since 1.13.0
	 */
	private function get_action_name_from_field_definitions( $field_definitions ) {
		// Look for specific field patterns to determine action type.
		$field_keys = array_column( $field_definitions, 'key' );

		if ( in_array( 'company_name', $field_keys, true ) ) {
			return 'Create Company';
		}

		// Default to Create Contact.
		return 'Create Contact';
	}

	/**
	 * Convert comma-separated tags to array
	 *
	 * @param string $tags_string Comma-separated tags.
	 * @return array Array of tag strings.
	 * @since 1.13.0
	 */
	private function convert_tags_to_array( $tags_string ) {
		if ( empty( $tags_string ) ) {
			return [];
		}

		$tags = array_map( 'trim', explode( ',', $tags_string ) );

		// Remove quotes from tags if present.
		$tags = array_map(
			static function( $tag ) {
				return trim( $tag, '"' );
			},
			$tags
		);

		return array_filter( $tags );
	}

}
