<?php

namespace HulkPlugins\ElementorPro\Forms\AdvancedFields\Fields\RichText;

use ElementorPro\Modules\Forms\Classes\Form_Record;
use HulkPlugins\ElementorPro\Forms\AdvancedFields\Fields\FieldBase;
use const HulkPlugins\ElementorPro\Forms\AdvancedFields\PREFIX;

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

class Field extends FieldBase {

	public $depended_styles = [ PREFIX . 'RichText' ];
	public $depended_scripts = [ PREFIX . 'RichText' ];

	protected bool $showStyleTab = false;

	/**
	 * Get field type.
	 * @return string
	 */
	public function get_type(): string {
		return PREFIX . 'rich_text';
	}

	/**
	 * Get field name.
	 * @return string
	 */
	public function get_name(): string {
		return esc_attr__( 'Rich Text', 'advanced-fields-for-elementor-forms' );
	}

	public function add_assets_depends( $form ): void {
		wp_enqueue_editor();
		parent::add_assets_depends( $form );
	}

	public function add_preview_depends(): void {
		wp_enqueue_editor();
		parent::add_preview_depends();
	}

	/**
	 * Enqueue script and style if elementor cache is enabled
	 * @return void
	 */
	public function get_builder_content(): void {
		wp_enqueue_editor();
		parent::get_builder_content();
	}

	/**
	 * Filters the record before it sent to actions after submit.
	 *
	 * @param Form_Record $record
	 *
	 * @return Form_Record
	 */
	public function forms_record_actions_before( Form_Record $record ): Form_Record {
		$fields = $record->get( 'fields' );
		if ( is_array( $fields ) ) {
			foreach ( $fields as $field ) {
				if ( $field['type'] === 'hulk_affef_rich_text' ) {
					$record->update_field(
						$field['id'],
						'value',
						wp_kses_post( wpautop( $field['raw_value'] ) )
					);
				}
			}
		}
		return $record;
	}

	public function __construct( array $meta ) {
		parent::__construct( $meta );
		if ( $meta['isEnabled'] === true ) {
			add_filter( 'elementor_pro/forms/record/actions_before', [ $this, 'forms_record_actions_before' ] );
		}
	}
}
