<?php

class HappyForms_Part_MultiLineTextExtended extends HappyForms_Part_MultiLineText {

	public function __construct() {
		parent::__construct();

		add_action( 'happyforms_print_scripts', array( $this, 'footer_templates' ) );
		add_filter( 'happyforms_style_dependencies', array( $this, 'style_dependencies' ), 10, 2 );
	}

	/**
	 * Sanitize submitted value before storing it.
	 *
	 * @param array $part_data Form part data.
	 *
	 * @return string
	 */
	public function sanitize_value( $part_data = array(), $form_data = array(), $request = array() ) {
		$sanitized_value = $this->get_default_value( $part_data );
		$part_name = happyforms_get_part_name( $part_data, $form_data );

		if ( isset( $request[$part_name] ) ) {
			if ( 1 == $part_data['rich_text'] ) {
				$allowed_html = $this->get_allowed_html();
				$sanitized_value = wp_kses( $request[$part_name], $allowed_html );
			} else {
				$sanitized_value = sanitize_textarea_field( $request[$part_name] );
			}
		}

		return $sanitized_value;
	}

	/**
	 * Get all part meta fields defaults.
	 *
	 * @since 1.0.0.
	 *
	 * @return array
	 */
	public function get_customize_fields() {
		$fields = parent::get_customize_fields();

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

		return happyforms_get_part_customize_fields( $fields, $this->type );
	}

	/**
	 * Get front end part template with parsed data.
	 *
	 * @since 1.0.0.
	 *
	 * @param array	$part_data 	Form part data.
	 * @param array	$form_data	Form (post) data.
	 *
	 * @return string	Markup for the form part.
	 */
	public function frontend_template( $part_data = array(), $form_data = array() ) {
		$part = wp_parse_args( $part_data, $this->get_customize_defaults() );
		$form = $form_data;

		$template_path = happyforms_get_include_folder() . '/templates/parts/frontend-multi-line-text-extended.php';

		if ( 1 == $part['rich_text'] && happyforms_is_block_context() ) {
			$template_path = happyforms_get_include_folder() . '/templates/parts/block-rich-text.php';
		}

		include( $template_path );
	}

	/**
	 * Enqueue scripts in customizer area.
	 *
	 * @since 1.0.0.
	 *
	 * @param array	List of dependencies.
	 *
	 * @return void
	 */
	public function customize_enqueue_scripts( $deps = array() ) {
		parent::customize_enqueue_scripts( $deps );

		wp_enqueue_script(
			'part-multi-line-text-extended',
			happyforms_get_plugin_url() . 'inc/assets/js/parts/part-multi-line-text-extended.js',
			$deps, HAPPYFORMS_VERSION, true
		);
	}

	public function html_part_class( $class, $part, $form ) {
		if ( $this->type === $part['type'] ) {
			if ( happyforms_get_part_value( $part, $form ) ) {
				$class[] = 'happyforms-part--filled';
			}

			if ( 'focus-reveal' === $part['description_mode'] ) {
				$class[] = 'happyforms-part--focus-reveal-description';
			}

			if ( 1 == $part['rich_text'] ) {
				$class[] = 'happyforms-part--rich_text';
			}
		}

		return $class;
	}

	private function get_limit_mode( $part ) {
		$mode = 'character';

		if ( 0 === strpos( $part['character_limit_mode'], 'word' ) ) {
			$mode = 'word';
		}

		return $mode;
	}

	private function get_limit_label( $part, $form ) {
		$min_or_max = '';
		$type = '';

		switch( $part['character_limit_mode'] ) {
			case 'character_min':
				$type = $form['characters_label_min'];
				break;
			case 'character_max':
				$type = $form['characters_label_max'];
				break;
			case 'word_min':
				$type = $form['words_label_min'];
				break;
			case 'word_max':
				$type = $form['words_label_max'];
				break;
		}

		$label = sprintf(
			'<span class="counter-label">%s</span>',
			$type,
			$min_or_max
		);

		return $label;
	}

	public function html_part_attributes( $attrs, $part ) {
		if ( $this->type !== $part['type'] ) {
			return $attrs;
		}

		$limit_input = intval( $part['limit_input'] );
		$character_limit = intval( $part['character_limit'] );
		$character_limit = $limit_input ? $character_limit : 0;

		if ( $character_limit || happyforms_is_preview() ) {
			$mode = $this->get_limit_mode( $part );
			$attrs[] = "data-length=\"{$character_limit}\"";
			$attrs[] = "data-length-mode=\"{$mode}\"";
		}

		return $attrs;
	}

	public function script_dependencies( $deps, $forms ) {
		$contains_long_text = false;
		$contains_editor    = false;

		$form_controller = happyforms_get_form_controller();

		foreach ( $forms as $form ) {
			$parts = $form_controller->get_parts_by_type( $form, $this->type );

			if ( ! empty( $parts ) ) {
				$contains_long_text = true;
			}

			$editors = array_filter( $parts, function( $part ) {
				return 1 == $part['rich_text'];
			} );

			if ( ! empty( $editors ) ) {
				$contains_editor = true;
				break;
			}
		}

		if ( ! happyforms_is_preview() && ! $contains_long_text ) {
			return $deps;
		}

		$editor_settings = array();

		if ( $contains_editor ) {
			$content_css = array( happyforms_get_plugin_url() . 'inc/assets/css/rich-text-editor.css' );
			/**
			 * Filters the list of CSS files to load
			 * in the editor document.
			 *
			 * @param array $content_css Current list of files.
			 *
			 * @return array
			 */
			$content_css = apply_filters( 'happyforms_text_editor_content_css', $content_css );
			$css_vars = array_values( happyforms_get_styles()->form_css_vars() );
			$allowed_elements = $this->get_editor_valid_elements();
			$editor_settings = array(
				'contentCSS' => $content_css,
				'cssVars' => $css_vars,
				'allowedElements' => $allowed_elements,
			);
		}

		wp_register_script(
			'happyforms-part-long-text-extended',
			happyforms_get_plugin_url() . 'inc/assets/js/frontend/long-text.js',
			( $contains_editor ? array( 'wp-tinymce' ) : array() ), HAPPYFORMS_VERSION, true
		);

		wp_localize_script(
			'happyforms-part-long-text-extended',
			'_happyFormsRichTextSettings',
			$editor_settings
		);

		$deps[] = 'happyforms-part-long-text-extended';

		return $deps;
	}

	public function style_dependencies( $deps, $forms ) {
		$contains_long_text = false;
		$contains_editor    = false;

		$form_controller = happyforms_get_form_controller();

		foreach ( $forms as $form ) {
			$parts = $form_controller->get_parts_by_type( $form, $this->type );

			if ( ! empty( $parts ) ) {
				$contains_long_text = true;
			}

			$editors = array_filter( $parts, function( $part ) {
				return 1 == $part['rich_text'];
			} );

			if ( ! empty( $editors ) ) {
				$contains_editor = true;
				break;
			}
		}

		if ( ! happyforms_is_preview() && ! $contains_long_text ) {
			return $deps;
		}

		if ( $contains_editor ) {
			$deps[] = 'editor-buttons';
		}

		return $deps;
	}

	private function get_allowed_html() {
		$allowed = array(
			'br' => array(),
			'b' => array(),
			'strong' => array(),
			'i' => array(),
			'em' => array(),
			'ul' => array(),
			'ol' => array(),
			'li' => array(),
			'p' => array(),
			'a' => array( 'href' => array() ),
			'pre' => array(),
			'hr' => array(),
			'u' => array(),
			'strike' => array(),
			'del' => array(),
			'blockquote' => array(),
		);

		return $allowed;
	}

	private function get_editor_valid_elements() {
		$tags = $this->get_allowed_html();
		$elements = array();

		foreach( $tags as $tag => $attributes ) {
			$element = $tag;
			$element_attributes = implode( '|', array_keys( $attributes ) );

			if ( ! empty( $element_attributes ) ) {
				$element = "{$element}[{$element_attributes}]";
			}

			$elements[] = $element;
		}

		$elements = implode( ',', $elements );

		return $elements;
	}

	public function part_input_after( $part, $form ) {
		return;
	}

	public function footer_templates( $forms ) {
		$contains_editor = false;
		$form_controller = happyforms_get_form_controller();

		foreach ( $forms as $form ) {
			$parts = $form_controller->get_parts_by_type( $form, $this->type );

			$editors = array_filter( $parts, function( $part ) {
				return 1 == $part['rich_text'];
			} );

			if ( ! empty( $editors ) ) {
				$contains_editor = true;
				break;
			}
		}

		if ( ! $contains_editor ) {
			return;
		}

		require_once( happyforms_get_include_folder() . '/templates/partials/frontend-rich-text-toolbar-icons.php' );
	}

}
