<?php

class HappyForms_Integration_Sendinblue {

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

	private $service;

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

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

		return self::$instance;
	}

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

	public function hook() {
		if ( self::$hooked ) {
			return;
		}

		self::$hooked = true;

		foreach ( $this->field_parts as $part_slug ) {
			add_filter( "happyforms_part_customize_fields_{$part_slug}", array( $this, 'add_part_fields' ) );
			add_action( "happyforms_part_customize_{$part_slug}_before_advanced_options", array( $this, "add_part_controls" ) );
		}

		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, 'add_logic_to_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_sendinblue'] = array(
			'default' => 0,
			'sanitize' => 'happyforms_sanitize_checkbox'
		);

		$fields['sendinblue_double_opt_in'] = array(
			'default' => 0,
			'sanitize' => 'happyforms_sanitize_checkbox'
		);

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

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

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

		return $fields;
	}

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

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

		$controls[152] = array(
			'type' => 'checkbox',
			'field' => 'sendinblue_double_opt_in',
			'label' => __( 'Send email to confirm subscription', 'happyforms' )
		);

		$controls[153] = array(
			'type' => 'group_start',
			'trigger' => 'sendinblue_double_opt_in',
		);

		$templates = $this->service->get_templates();
		$template_options = wp_list_pluck( $templates, 'name', 'id' );

		$controls[154] = array(
			'type' => 'select',
			'field' => 'sendinblue_double_opt_in_template',
			'placeholder' => __( '— Select —', 'happyforms' ),
			'label' => __( 'Double opt-in email template', 'happyforms' ),
			'options' => $template_options,
		);

		$controls[155] = array(
			'type' => 'url',
			'label' => __( 'Double opt-in redirect address', 'happyforms' ),
			'placeholder' => __( 'Paste web address or type to search', 'happyforms' ),
			'field' => 'sendinblue_double_opt_in_redirect_url',
		);

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

		$lists = $this->service->get_lists();
		$lists_options = array();

		foreach ( $lists as $folder_key => $folder_lists ) {
			$folder_lists = array_map( function( $list ) {
				$list = array(
					'label' => $list['name'],
					'value' => $list['id'],
				);

				return $list;
			}, $folder_lists );

			$lists_options[$folder_key] = $folder_lists;
		}

		$controls[157] = array(
			'type' => 'select',
			'field' => "{$this->service->id}_list",
			'placeholder' => __( '— Select —', 'happyforms' ),
			'label' => __( 'List to add user\'s email to', 'happyforms' ),
			'options' => $lists_options,
			'allow_empty' => true,
		);

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

		return $controls;
	}

	public function add_logic_to_controls( $controls ) {
		$lists = array();
		$lists = $this->service->get_lists();
		$lists_options = array();

		if ( empty( $lists ) ) {
			return $controls;
		}

		foreach ( $lists as $folder_key => $folder_lists ) {
			$folder_lists = array_map( function( $list ) {
				$list = array(
					'label' => $list['name'],
					'value' => $list['id'],
				);

				return $list;
			}, $folder_lists );

			$lists_options[$folder_key] = array(
				'title'   => $folder_key,
				'options' => $folder_lists,
			);
		}

		$controls["{$this->service->id}_list"] = array(
			'type' => 'select',
			'options' => $lists_options,
			'then_text' => __( 'Then add to…', 'happyforms' )
		);

		return $controls;
	}

	public function add_part_fields( $fields ) {
		$fields["{$this->service->id}_field"] = array(
			'default'  => '',
			'sanitize' => 'sanitize_text_field'
		);

		return $fields;
	}

	public function add_part_controls() {
		?>
		<% if ( 1 == happyForms.form.get( 'enable_sendinblue' ) ) { %>
		<p>
			<label for="<%= instance.id %>_sendinblue_field"><?php _e( 'Map field to Sendinblue field', 'happyforms' ); ?></label>
			<select class="widefat happyforms-client-updated" data-bind="sendinblue_field" data-var="_happyFormsSendinblueData" data-var-prop="fields">
				<option value="" selected>– <?php _e( 'Select', 'happyforms' ); ?> –</option>
			</select>
		</p>
		<% } %>
		<?php
	}

	public function handle_submit( $submission, $form, $message ) {
		$form_controller = happyforms_get_form_controller();
		$email_integration_part = $form_controller->get_first_part_by_type( $form, 'email_integration' );

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

		$form_controller = happyforms_get_form_controller();
		$form = happyforms_get_conditional_controller()->get( $form, $_REQUEST );
		$list_id = happyforms_get_form_property( $form, 'sendinblue_list' );

		$fields = array();

		foreach ( $form['parts'] as $part ) {
			if ( empty( $part['sendinblue_field'] ) ) {
				continue;
			}

			$fields[$part['sendinblue_field']] = $submission[$part['id']];
		}

		$data = array(
			'list_id' => $list_id,
			'fields' => $fields,
		);

		$use_double_opt_in = false;
		$use_double_opt_in = happyforms_get_form_property( $form, 'sendinblue_double_opt_in' );
		$double_opt_in_template = happyforms_get_form_property( $form, 'sendinblue_double_opt_in_template' );
		$double_opt_in_redirect_url = happyforms_get_form_property( $form, 'sendinblue_double_opt_in_redirect_url' );

		if ( happyforms_is_truthy( $use_double_opt_in ) ) {
			$data['double_opt_in_template'] = $double_opt_in_template;
			$data['double_opt_in_redirect_url'] = $double_opt_in_redirect_url;
			$use_double_opt_in = true;
		}

		$this->service->add_subscriber( $data, $use_double_opt_in );
	}

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

		$data = array(
			'fields' => $fields,
		);

		wp_localize_script(
			'happyforms-customize',
			'_happyFormsSendinblueData',
			$data
		);
	}

}

if ( ! function_exists( 'happyforms_get_integration_sendinblue' ) ):

function happyforms_get_integration_sendinblue() {
	$instance = HappyForms_Integration_Sendinblue::instance();
	$instance->hook();

	return $instance;
}

endif;

happyforms_get_integration_sendinblue();
