<?php

class HappyForms_Form_Setup_Upgrade {

	private static $instance;

	public $action_abandon = 'happyforms-form-abandon';

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

		self::$instance->hook();

		return self::$instance;
	}

	public function hook() {
		// Common form extensions
		add_filter( 'happyforms_get_steps', array( $this, 'steps_add_preview' ), 10, 2 );
		add_filter( 'happyforms_meta_fields', array( $this, 'meta_fields' ) );
		add_filter( 'happyforms_frontend_settings', array( $this, 'frontend_settings' ), 10, 1 );
		add_action( 'wp_ajax_' . $this->action_abandon, array( $this, 'form_abandoned' ) );
		add_action( 'wp_ajax_nopriv_' . $this->action_abandon, array( $this, 'form_abandoned' ) );

		// Reviewable form display
		add_filter( 'happyforms_get_submit_template_path', array( $this, 'submit_preview_template' ), 10, 2 );
		add_filter( 'happyforms_get_submit_template_path', array( $this, 'confirm_preview_partial' ), 20, 2 );
		add_filter( 'happyforms_form_class', array( $this, 'form_html_class_preview' ), 10, 2 );
		add_filter( 'happyforms_form_class', array( $this, 'form_html_class' ), 10, 2 );
		add_action( 'happyforms_parts_before', array( $this, 'form_open_preview' ) );
		add_filter( 'happyforms_part_attributes', array( $this, 'part_attributes_preview' ), 10, 4 );
		add_action( 'happyforms_part_before', array( $this, 'part_before_preview' ), 10, 2 );
		add_action( 'happyforms_part_after', array( $this, 'part_after_preview' ), 10, 2 );

		add_filter( 'happyforms_setup_controls', array( $this, 'setup_controls' ) );
		add_filter( 'happyforms_email_controls', array( $this, 'email_controls' ) );
		add_action( 'happyforms_messages_controls', array( $this, 'messages_controls' ) );
		add_filter( 'happyforms_messages_fields', array( $this, 'get_messages_fields' ) );

		add_action( 'happyforms_do_setup_control', array( $this, 'do_control' ), 10, 3 );
		add_action( 'happyforms_do_email_control', array( $this, 'do_control' ), 10, 3 );
		add_action( 'happyforms_do_setup_control', array( $this, 'do_deprecated_control' ), 10, 3 );

		add_action( 'happyforms_customize_enqueue_scripts', array( $this, 'customize_enqueue_styles' ) );
		add_filter( 'happyforms_part_customize_template_path_select', array( $this, 'part_select_set_customize_template_path' ) );
		add_filter( 'happyforms_part_customize_template_path_checkbox', array( $this, 'part_checkbox_set_customize_template_path' ) );
		add_filter( 'happyforms_part_customize_template_path_radio', array( $this, 'part_radio_set_customize_template_path' ) );
		add_filter( 'happyforms_part_customize_template_path_table', array( $this, 'part_table_set_customize_template_path' ) );
		add_filter( 'happyforms_part_customize_template_path_multi_line_text', array( $this, 'part_multilinetext_set_customize_template_path' ) );
		add_action( 'happyforms_response_created', array( $this, 'increment_unique_id' ), 10, 2 );

		add_filter( 'happyforms_get_form_data', array( $this, 'handle_features_transition' ) );

	}

	public function get_fields() {
		$fields = array(
			'alert_email_attachment_links' => array(
				'default' => 0,
				'sanitize' => 'happyforms_sanitize_checkbox',
			),
			'alert_email_hide_placeholder_parts' => array(
				'default' => 0,
				'sanitize' => 'happyforms_sanitize_checkbox',
			),
			'alert_email_include_referral_url' => array(
				'default' => 0,
				'sanitize' => 'happyforms_sanitize_checkbox',
			),
			'alert_email_include_user_data' => array(
				'default' => 1,
				'sanitize' => 'happyforms_sanitize_checkbox',
			),
			'unique_id' => array(
				'default' => 0,
				'sanitize' => 'happyforms_sanitize_checkbox',
			),
			'unique_id_start_from' => array(
				'default' => 1,
				'sanitize' => 'intval',
			),
			'unique_id_prefix' => array(
				'default' => '',
				'sanitize' => 'sanitize_text_field',
			),
			'unique_id_suffix' => array(
				'default' => '',
				'sanitize' => 'sanitize_text_field',
			),
			'confirmation_email_respondent_address' => array(
				'default' => '',
				'sanitize' => 'sanitize_text_field',
			),
			'hide_prev_button' => array(
				'default' => 0,
				'sanitize' => 'happyforms_sanitize_checkbox'
			)
		);

		return $fields;
	}

	public function get_messages_fields( $fields ) {
		$messages_fields = array(
			'review_step_message' => array(
				'default' => __( 'Please double-check for mistake.', 'happyforms' ),
				'sanitize' => 'esc_html',
			),
			'next_button_label' => array(
				'default' => __( 'Next', 'happyforms' ),
				'sanitize' => 'sanitize_text_field',
			),
			'previous_button_label' => array(
				'default' => __( 'Previous', 'happyforms' ),
				'sanitize' => 'sanitize_text_field',
			),
			'review_button_label' => array(
				'default' => __( 'Review reply', 'happyforms' ),
				'sanitize' => 'sanitize_text_field',
			),
			'edit_button_label' => array(
				'default' => __( 'Edit', 'happyforms' ),
				'sanitize' => 'sanitize_text_field',
			),
		);

		$fields = array_merge( $fields, $messages_fields );

		return $fields;
	}


	public function meta_fields( $fields ) {
		$fields = array_merge( $fields, $this->get_fields() );

		return $fields;
	}

	public function setup_controls( $controls ) {
		// unset upsell for "Redirect to web address"
		unset( $controls[11] );

		$controls[50] = array(
			'type' => 'url',
			'label' => __( 'Web address', 'happyforms' ),
			'placeholder' => __( 'Paste web address or type to search', 'happyforms' ),
			'field' => 'redirect_url',
		);

		$controls[51] = array(
			'type' => 'checkbox',
			'label' => __( 'Open web address in new tab', 'happyforms' ),
			'field' => 'redirect_blank',
		);

		$controls[1700] = array(
			'type' => 'identifier-checkbox',
			'label' => __( 'Add submission identifier', 'happyforms' ),
			// 'tooltip' => __( 'Tag responses with a unique, incremental identifier.', 'happyforms' ),
			'field' => 'unique_id',
		);

		$controls[1701] = array(
			'type' => 'group_start',
			'trigger' => 'unique_id'
		);

		$controls[1702] = array(
			'type' => 'identifier-number',
			'label' => __( 'Start counter from', 'happyforms' ),
			'field' => 'unique_id_start_from',
			'min' => 0
		);

		$controls[1703] = array(
			'type' => 'identifier-text',
			'label' => __( 'Prefix', 'happyforms' ),
			'field' => 'unique_id_prefix',
			'autocomplete' => 'off',
		);

		$controls[1704] = array(
			'type' => 'identifier-text',
			'label' => __( 'Suffix', 'happyforms' ),
			'field' => 'unique_id_suffix',
			'autocomplete' => 'off',
		);

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

		$controls[1800] = array(
			'type' => 'checkbox',
			'label' => __( 'Require respondents to review a submission before submitting', 'happyforms' ),
			'field' => 'preview_before_submit',
		);

		$controls[1900] = array(
			'type' => 'checkbox',
			'label' => __( 'Disable buttons until required fields are answered', 'happyforms' ),
			'field' => 'disable_submit_until_valid',
			// 'tooltip' => __( 'Reduce the opacity of buttons until all required form parts are valid.', 'happyforms' ),
		);

		$controls[4001] = array(
			'type' => 'checkbox',
			'label' => __( 'Hide previous button', 'happyforms' ),
			'field' => 'hide_prev_button',
		);

		return $controls;
	}

	public function email_controls( $controls ) {
		$controls[450] = array(
			'type' => 'checkbox',
			'label' => __( 'Include reply link', 'happyforms' ),
			// 'tooltip' => __( 'Reply to your users and mark their submission as read in one click.', 'happyforms' ),
			'field' => 'email_mark_and_reply',
		);

		$controls[460] = array(
			'type' => 'checkbox',
			'label' => __( 'Link to attachments in email', 'happyforms' ),
			// 'tooltip' => __( 'Show attachments as links instead of a simple counter.', 'happyforms' ),
			'field' => 'alert_email_attachment_links',
		);

		$controls[470] = array(
			'type' => 'checkbox',
			'label' => __( 'Hide Text fields in email', 'happyforms' ),
			'field' => 'alert_email_hide_placeholder_parts',
		);

		$controls[480] = array(
			'type' => 'checkbox',
			'label' => __( 'Include user\'s meta data', 'happyforms' ),
			// 'tooltip' => __( 'Include user meta data like IP address ,local time, and platform in email.', 'happyforms' ),
			'field' => 'alert_email_include_user_data',
		);

		$controls[481] = array(
			'type' => 'checkbox',
			'label' => __( 'Include referral web address', 'happyforms' ),
			// 'tooltip' => __( 'Include the page URL your form was submitted from.', 'happyforms' ),
			'field' => 'alert_email_include_referral_url',
		);

		$controls[595] = array(
			'type' => 'email-parts-list',
			'label' => __( 'To email address', 'happyforms' ),
			// 'tooltip' => __( 'The Email field used to send this confirmation.', 'happyforms' ),
			'field' => 'confirmation_email_respondent_address',
		);

		return $controls;
	}

	public function messages_controls( $controls ){
		$controls[140] = array(
			'type' => 'text',
			'label' => __( 'Respondent is viewing review page', 'happyforms' ),
			'field' => 'review_step_message',
		);
		$controls[2100] = array(
			'type' => 'text',
			'label' => __( 'Go to next page', 'happyforms' ),
			'field' => 'next_button_label',
		);
		$controls[2120] = array(
			'type' => 'text',
			'label' => __( 'Go to previous page', 'happyforms' ),
			'field' => 'previous_button_label',
		);
		$controls[2200] = array(
			'type' => 'text',
			'label' => __( 'Review reply', 'happyforms' ),
			'field' => 'review_button_label',
			'autocomplete' => 'off',
		);
		$controls[2040] = array(
			'type' => 'text',
			'label' => __( 'Edit reply', 'happyforms' ),
			'field' => 'edit_button_label',
			'autocomplete' => 'off',
		);

		return $controls;
	}

	public function do_control( $control, $field, $index ) {
		$type = $control['type'];

		switch( $type ) {
			case 'parts-list':
				require( happyforms_get_include_folder() . '/templates/customize-controls/parts-list.php' );
				break;
			case 'email-parts-list':
				require( happyforms_get_include_folder() . '/templates/customize-controls/email-parts-list.php' );
				break;
			case 'url':
				require( happyforms_get_include_folder() . '/templates/customize-controls/url.php' );
				break;
			break;
		}
	}

	public function do_deprecated_control( $control, $field, $index ) {
		$type = $control['type'];

		switch( $type ) {
			case 'identifier-checkbox':
			case 'identifier-number':
			case 'identifier-text':
				$form = happyforms_customize_get_current_form();

				if ( $form[ 'unique_id' ] == 1 ) {
					$path = happyforms_get_core_folder() . '/templates/customize-controls/setup';
					$type = str_replace( 'identifier-', '', $type );

					require( "{$path}/{$type}.php" );
				}

				break;
		}
	}

	public function increment_unique_id( $response_id, $form ) {
		if ( intval( $form['unique_id'] ) ) {
			$increment = intval( $form['unique_id_start_from'] );
			happyforms_update_meta( $form['ID'], 'unique_id_start_from', $increment + 1 );
		}
	}

	public function requires_confirmation( $form ) {
		return ( 1 === intval( $form['preview_before_submit'] ) );
	}

	public function part_select_set_customize_template_path( $template_path ) {
		$template_path = happyforms_get_include_folder() . '/templates/parts/customize-select.php';

		return $template_path;
	}

	public function part_checkbox_set_customize_template_path( $template_path ) {
		$template_path = happyforms_get_include_folder() . '/templates/parts/customize-checkbox.php';

		return $template_path;
	}

	public function part_radio_set_customize_template_path( $template_path ) {
		$template_path = happyforms_get_include_folder() . '/templates/parts/customize-radio.php';

		return $template_path;
	}

	public function part_table_set_customize_template_path( $template_path ) {
		$template_path = happyforms_get_include_folder() . '/templates/parts/customize-table.php';

		return $template_path;
	}

	public function part_multilinetext_set_customize_template_path( $template_path ) {
		$template_path = happyforms_get_include_folder() . '/templates/parts/customize-multi-line-text-extended.php';

		return $template_path;
	}

	public function part_before_preview( $part, $form ) {
		if ( happyforms_get_form_property( $form, 'preview_before_submit' )
			&& ( 'review' === happyforms_get_current_step( $form ) ) ) {
			require( happyforms_get_include_folder() . '/templates/partials/part-preview.php' );
		}
	}

	public function part_after_preview( $part, $form ) {
		if ( happyforms_get_form_property( $form, 'preview_before_submit' )
			&& ( 'review' === happyforms_get_current_step( $form ) ) ) {
			?>
			</div></div>
			<?php
		}
	}

	public function part_attributes_preview( $attributes, $part, $form, $component ) {
		if ( happyforms_get_form_property( $form, 'preview_before_submit' )
			&& ( 'review' === happyforms_get_current_step( $form ) ) ) {
			$attributes[] = 'readonly';
		}

		return $attributes;
	}

	public function form_open_preview( $form ) {
		if ( happyforms_get_form_property( $form, 'preview_before_submit' )
			&& ( 'review' === happyforms_get_current_step( $form ) ) ) {
			?>
			<div>
				<?php echo wpautop( html_entity_decode( happyforms_get_form_property( $form, 'review_step_message' ) ) ); ?>
			</div>
			<?php
		}
	}

	public function form_html_class_preview( $classes, $form ) {
		if ( happyforms_get_form_property( $form, 'preview_before_submit' )
			&& ( 'review' === happyforms_get_current_step( $form ) ) ) {
			$classes[] = 'happyforms-form-preview';
		}

		return $classes;
	}

	public function confirm_preview_partial( $path, $form ) {
		if ( happyforms_get_form_property( $form, 'preview_before_submit' )
			&& ( 'review' === happyforms_get_current_step( $form ) ) ) {
			$path = happyforms_get_include_folder() . '/templates/partials/form-confirm-preview.php';
		}

		return $path;
	}

	public function submit_preview_template( $path, $form ) {
		if ( happyforms_get_form_property( $form, 'preview_before_submit' )
			&& ( 'preview' === happyforms_get_current_step( $form ) ) ) {
			$path = happyforms_get_include_folder() . '/templates/partials/form-submit-preview.php';
		}

		return $path;
	}

	public function steps_add_preview( $steps, $form ) {
		if ( $this->requires_confirmation( $form ) ) {
			$steps[100] = 'preview';
			$steps[200] = 'review';
		}

		return $steps;
	}

	public function form_html_class( $class, $form ) {
		if ( 1 === intval( happyforms_get_form_property( $form, 'disable_submit_until_valid' ) ) ) {
			$class[] = 'happyforms-form--disable-until-valid';
		}

		return $class;
	}

	public function customize_enqueue_styles() {
		wp_enqueue_style(
			'happyforms-customize-upgrade',
			happyforms_get_plugin_url() . 'inc/assets/css/customize.css',
			array(), HAPPYFORMS_UPGRADE_VERSION
		);
	}

	public function handle_features_transition( $form_data ) {
		if ( ! metadata_exists( 'post', $form_data['ID'], '_happyforms_confirm_submission' ) ) {
			if ( 1 == happyforms_get_meta( $form_data['ID'], 'redirect_on_complete', true ) ) {
				$form_data['confirm_submission'] = 'redirect';
			}
		}

		return $form_data;
	}

	public function frontend_settings( $data ) {
		$data['actionAbandon'] = $this->action_abandon;

		return $data;
	}

	public function form_abandoned() {
		do_action( 'happyforms_form_abandoned' );
	}

}

if ( ! function_exists( 'happyforms_get_form_setup_upgrade' ) ):
/**
 * Get the HappyForms_Form_Controller class instance.
 */
function happyforms_get_form_setup_upgrade() {
	return HappyForms_Form_Setup_Upgrade::instance();
}

endif;

/**
 * Initialize the HappyForms_Form_Controller class immediately.
 */
happyforms_get_form_setup_upgrade();
