<?php

class HappyForms_Integration_ActiveCampaign {

	private static $instance;
	private static $hooked = false;
	private $service;

	public static function instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}

		self::$instance->hook();

		return self::$instance;
	}

	public function __construct() {
		$this->service = happyforms_get_integrations()->get_service( 'active-campaign' );
	}

	public function hook() {
		add_filter( 'happyforms_meta_fields', array( $this, 'meta_fields' ) );
		add_filter( 'happyforms_email_controls', array( $this, 'setup_controls' ) );
		add_filter( 'happyforms_conditional_enabled_setup_controls', array( $this, 'conditional_enabled_setup_controls' ) );

		$supported_parts = $this->get_supported_parts();

		foreach ( $supported_parts as $part ) {
			add_filter( "happyforms_part_customize_fields_{$part}", array( $this, 'add_part_fields' ) );
			add_action( "happyforms_part_customize_{$part}_before_advanced_options", array( $this, 'add_part_controls' ) );
		}

		add_action( 'happyforms_customize_enqueue_scripts', array( $this, 'customize_enqueue_scripts' ) );
		add_action( 'happyforms_submission_success', array( $this, 'handle_submit' ), 10, 3 );
	}

	public function meta_fields( $fields ) {
		$fields['enable_active_campaign'] = array(
			'default' => 0,
			'sanitize' => 'happyforms_sanitize_checkbox'
		);

		$fields['active_campaign_list'] = array(
			'default' => 0,
			'sanitize' => 'sanitize_text_field'
		);

		$fields['active_campaign_tags'] = array(
			'default' => '',
			'sanitize' => 'sanitize_text_field'
		);

		return $fields;
	}

	public function setup_controls( $controls ) {
		$controls[150] = array(
			'type' => 'checkbox',
			'field' => 'enable_active_campaign',
			'label' => __( 'Use ActiveCampaign', 'happyforms' ),
			// 'tooltip' => __( 'Send mapped fields to ActiveCampaign.', 'happyforms' )
		);

		$controls[151] = array(
			'type' => 'group_start',
			'trigger' => 'enable_active_campaign'
		);

		$lists = $this->service->get_lists();
		$lists = wp_list_pluck( $lists, 'name', 'id' );

		$controls[152] = array(
			'type' => 'select',
			'field' => 'active_campaign_list',
			'placeholder' => __( '— Select —', 'happyforms' ),
			'label' => __( 'List to add user\'s email to', 'happyforms' ),
			'options' => $lists
		);

		$controls[153] = array(
			'type' => 'text',
			'field' => 'active_campaign_tags',
			'label' => __( 'Add these tags to submissions', 'happyforms' ),
			'placeholder' => __( 'e.g. Influencer, Prospect, Uses coupons', 'happyforms' )
		);

		$controls[154] = array(
			'type' => 'group_end'
		);

		return $controls;
	}

	public function conditional_enabled_setup_controls( $controls ) {
		$lists = $this->service->get_lists();
		$lists = wp_list_pluck( $lists, 'name', 'id' );

		$controls['active_campaign_list'] = array(
			'type' => 'select',
			'options' => $lists,
			'then_text' => __( 'Then add to…', 'happyforms' )
		);

		$controls['active_campaign_tags'] = array(
			'type' => 'set',
			'then_text' => __( 'Then add tags…', 'happyforms' )
		);

		return $controls;
	}

	public function get_supported_parts() {
		$parts = array(
			'single_line_text',
			'multi_line_text',
			'email',
			'website_url',
			'radio',
			'checkbox',
			'select',
			'number',
			'poll',
			'phone',
			'date',
			'scale',
			'rich_text',
			'title',
			'legal',
			'rating'
		);

		return $parts;
	}

	public function get_field_part_mappings() {
		$parts = array(
			'single_line_text' => array( 'textarea', 'text', 'hidden' ),
			'multi_line_text' => array( 'textarea', 'text', 'hidden' ),
			'email' => array( 'textarea', 'text', 'hidden' ),
			'website_url' => array( 'textarea', 'text', 'hidden' ),
			'radio' => array( 'dropdown', 'radio' ),
			'checkbox' => array( 'listbox', 'checkbox' ),
			'select' => array( 'dropdown', 'radio' ),
			'number' => array( 'textarea', 'text', 'hidden' ),
			'poll' => array( 'textarea', 'text', 'hidden' ),
			'phone' => array( 'textarea', 'text', 'hidden' ),
			'date' => array( 'textarea', 'text', 'hidden', 'date' ),
			'scale' => array( 'textarea', 'text', 'hidden' ),
			'rich_text' => array( 'textarea' ),
			'title' => array( 'textarea', 'text', 'hidden' ),
			'legal' => array( 'textarea', 'text', 'hidden' ),
			'rating' => array( 'textarea', 'text', 'hidden' ),
		);

		return $parts;
	}

	public function add_part_fields( $fields ) {
		$fields['active_campaign_field'] = array(
			'default' => '',
			'sanitize' => 'sanitize_text_field'
		);

		return $fields;
	}

	public function add_part_controls() {
		require( happyforms_get_integrations_folder() . '/services/active-campaign/templates/partial-part-controls.php' );
	}

	public function customize_enqueue_scripts() {
		$fields = $this->service->get_fields();
		$mappings = $this->get_field_part_mappings();

		$active_campaign_data = array(
			'fields' => $fields,
			'mappings' => $mappings,
		);

		wp_localize_script(
			'happyforms-customize',
			'_happyFormsActiveCampaignSettings',
			$active_campaign_data
		);
	}

	public function get_field_submission_value( $field, $part, $form, $submission ) {
		$value = '';
		$part_type = $part['type'];
		$part_id = $part['id'];

		switch( $part_type ) {
			case 'checkbox':
				$part_class = happyforms_get_part_library()->get_part( $part_type );
				$value = $part_class->sanitize_value( $part, $form, $_REQUEST );
				$value = array_map( function( $option ) use( $part ) {
					return $part['options'][$option]['label'];
				}, $value );
				break;
			default:
				$value = $submission[$part_id];
				break;
		}

		return $value;
	}

	public function handle_submit( $submission, $form, $message ) {
		$form_controller = happyforms_get_form_controller();
		$form = happyforms_get_conditional_controller()->get( $form, $_REQUEST );
		$list_id = happyforms_get_form_property( $form, 'active_campaign_list' );

		$email_integration_part = $form_controller->get_first_part_by_type( $form, 'email_integration' );

		if ( $email_integration_part && 'yes' !== $submission[$email_integration_part['id']] ) {
			return;
		}

		if ( '' === $list_id ) {
			return;
		}

		$parts = array_filter( $form['parts'], function( $part ) {
			return ! empty( $part['active_campaign_field'] );
		} );

		$fields = wp_list_pluck( $parts, 'id', 'active_campaign_field' );

		if ( ! isset( $fields['email'] ) ) {
			return;
		}

		unset( $fields[''] );

		$part_ids = wp_list_pluck( $parts, 'id' );
		$parts = array_combine( $part_ids, $parts );

		foreach( $fields as $field => $part_id ) {
			$part = $parts[$part_id];
			$fields[$field] = $this->get_field_submission_value( $field, $part, $form, $submission );
		}

		$tags = happyforms_get_form_property( $form, 'active_campaign_tags' );

		$this->service->create_contact( $list_id, $fields, $tags );
	}

}

if ( ! function_exists( 'happyforms_get_integration_active_campaign' ) ):

function happyforms_get_integration_active_campaign() {
	$instance = HappyForms_Integration_ActiveCampaign::instance();
	$instance->hook();

	return $instance;
}

endif;

happyforms_get_integration_active_campaign();
