<?php

namespace DIFL\Feature;

use DIFL\Customizer\Frontend\Frontend;

class CF_Attachment extends \ET_Builder_Module_Contact_Form_Item {
	public function __construct() {
		parent::__construct();
		add_filter( 'et_pb_contact_field_shortcode_output', [ $this, 'handle_render' ], 999, 3 );
		add_action( 'wp_footer', [ $this, 'enqueue_inline_script' ] );
		$this->advanced_fields = $this->get_advanced_fields_config();
	}

	public function render_as_builder_data( $atts, $content, $render_slug, $parent_address = '', $global_parent = '', $global_parent_type = '', $parent_type = '', $theme_builder_area = '' ) {
		$object          = parent::render_as_builder_data( $atts, $content, $render_slug, $parent_address = '', $global_parent = '', $global_parent_type = '', $parent_type = '', $theme_builder_area = '' );
		$object['attrs'] = array_merge( $atts, $object['attrs'] );

		return $object;
	}

	protected function _render_module_wrapper( $output = '', $render_slug = '' ) {
		return $output;
	}

	public function handle_render( $output, $render_slug, $object ) {
		if ( $object->props['field_type'] !== 'file_upload' || \DIFL\Customizer\Frontend\Frontend::is_vb_or_tb() ) {
			return $output;
		}
		$module_class     = $this->module_classname( $render_slug );
		$button_alignemnt = empty( $this->props['file_upload_button_alignment'] ) ? '' : $this->props['file_upload_button_alignment'];
		$order_class      = self::get_module_order_class( $render_slug );
		$label            = $object->props['field_title'];
		$button_label     = empty( $object->props['difl_cf_button_label'] ) ? esc_html__( 'Choose File', 'divi_flash' ) : esc_html( $object->props['difl_cf_button_label'] );
		$output           = sprintf(
			'
            <p class="difl-cf-upload et_pb_contact_field %2$s %6$s" data-id="file_upload" data-type="file_upload">
                <label for="et_pb_contact_file_upload_0" class="et_pb_contact_form_label"> %1$s </label>
                <input style="display: none" type="file" name="%2$s" id="%3$s" data-label="%4$s"/>
                <button type="button" style="position: relative" class="difl_contact_form_file_upload et_pb_button">%5$s</button>
                <span class="file-name" data-isfile="false">No File Chosen</span>
                <span class="delete dashicons dashicons-trash" style="display:none"></span>
            </p>',
			esc_html( $label ),
			esc_attr( $order_class ),
			esc_attr( $order_class ),
			esc_attr( $label ),
			esc_html( $button_label ),
			esc_attr( $button_alignemnt )
		);

		return $output;
	}

	public function get_fields() {
		$fields                          = parent::get_fields();
		$fields['field_type']['options'] = array_merge( $fields['field_type']['options'], [
			'file_upload' => __( 'File Upload', 'divi_flash' ),
		] );

		$fields['difl_cf_button_label'] = [
			'label'            => esc_html__( 'Button Label', 'divi_flash' ),
			'type'             => 'text',
			'default_on_front' => esc_html__( 'Choose File', 'divi_flash' ),
			'default'          => esc_html__( 'Choose File', 'divi_flash' ),
			'description'      => esc_html__( 'Here you can enter label for button text.', 'divi_flash' ),
			'tab_slug'         => 'general',
			'toggle_slug'      => 'main_content',
			'show_if'          => [
				'field_type' => 'file_upload',
			],
		];

		return $fields;
	}

	public function resolve_conditional_defaults( $values, $render_slug = '' ) {
		$existing = $values;
		$resolved = parent::resolve_conditional_defaults( $values, $render_slug ); // TODO: Change the autogenerated stub

		return array_merge( $resolved, $existing );
	}

	public function get_advanced_fields_config() {
		$advanced_fields = [];
		$config          = parent::get_advanced_fields_config();

		$advanced_fields['button']['file_upload_button'] = [
			'label'          => esc_html__( 'File Upload Button', 'divi_flash' ),
			'css'            => [
				'main'         => '%%order_class%% .difl_contact_form_file_upload',
				'limited_main' => '%%order_class%% .difl_contact_form_file_upload',
				'important'    => true,
			],
			'no_rel_attr'    => true,
			'box_shadow'     => [
				'css' => [
					'main'      => '%%order_class%% .difl_contact_form_file_upload',
					'important' => true,
				],
			],
			'use_alignment'  => true,
			'margin_padding' => [
				'css' => [
					'main'      => '%%order_class%% .difl_contact_form_file_upload',
					'important' => 'all',
				],
			],
			'show_if'        => [ 'item_type' => 'file_upload' ],
		];

		return array_merge( $config, $advanced_fields );
	}

	public function enqueue_inline_script() {
		if ( Frontend::is_vb_or_tb() ) {
			return;
		}
		?>
        <script>
			(() => {
				const removeFile = ( input, index ) => {
					input.files = [ ...input.files ]
						.reduce( ( dt, f, i ) => {
							if ( i !== index ) {
								dt.items.add( f );
							}
							return dt;
						}, new DataTransfer() )
						.files;
				}
				const handleFileUpload = () => {
					const forms = document.querySelectorAll( 'form[class*="et_pb_contact_form"]' );
					const uids = document.querySelector( 'div[data-form_unique_id]' ).dataset;
					const form_number = uids.form_unique_num;
					const form_uid = uids.form_unique_id;
					const nonce = document.querySelector( 'input[id^="_wpnonce-et-pb-contact-form-submitted"]' ).value;
					if ( ! forms ) {
						return;
					}

					[ ...forms ].forEach( form => {
						const fields = [ ...form.querySelectorAll( '.difl-cf-upload' ) ];
						if ( ! fields ) {
							return;
						}

						fields.forEach( field => {
							const button = field.querySelector( 'button.difl_contact_form_file_upload' );
							const font_size = getComputedStyle( button ).fontSize;
							const input = button.previousElementSibling;
							const file_name = button.nextElementSibling;
							const trash = button.nextElementSibling.nextElementSibling;
							file_name.style.fontSize = font_size
							trash.style.fontSize = font_size
							button.addEventListener( 'click', e => {
								input.addEventListener( 'change', e => {
									file_name.innerText = e.target.files[0].name;
									trash.style.display = 'unset'
								} )
								input.click();

								trash.addEventListener( 'click', () => {
									removeFile( input, 0 );
									trash.style.display = 'none';
									file_name.innerText = 'No File Chosen';
								} );
							} );
						} );

						form.addEventListener( 'submit', () => {
							const files = form.querySelectorAll( 'input[type="file"][name*="et_pb_contact_field_"]' );
							const data = new FormData;
							if ( ! files ) {
								return;
							}

							[ ...files ].forEach( file => {
								const label = file.dataset.label;
								data.append( label, file.files[0] );
								data.append( label, label );
							} );

							data.append( 'action', 'difl_cf_form_handler' );
							data.append( 'form_number', form_number );
							data.append( 'form_uid', form_uid );
							data.append( 'nonce', nonce );
							setTimeout( () => {
								try {
									fetch( "<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>", {
										method: 'post',
										body: data,
									} );
								} catch ( e ) {
									console.log( e );
								}
							}, 1000 )
						} )
					} )
				}
				const originalOpen = XMLHttpRequest.prototype.open;

				XMLHttpRequest.prototype.open = function ( method, url ) {
					const form = document.querySelector( 'form.et_pb_contact_form' );
					if ( url.includes( form.action ) ) {
						this.addEventListener( 'load', function () {
							setTimeout( () => {
								handleFileUpload();
							}, 1000 )
						} );
					}
					originalOpen.apply( this, arguments );
				};
				window.addEventListener( 'load', handleFileUpload );
			})()
        </script>
        <style>
            .difl-cf-upload.center {
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .difl-cf-upload.right {
                display: flex;
                align-items: center;
                justify-content: flex-end;
            }

            .difl-cf-upload p.et_pb_contact_field {
                display: flex;
                align-items: center;
            }

            .difl-cf-upload button:hover, .difl-cf-upload span.delete {
                cursor: pointer;
            }

            .difl-cf-upload span {
                font-size: inherit;
                height: 100%;
            }

            .difl-cf-upload span.file-name {
                margin-inline-start: .5rem;
            }

            .difl-cf-upload span.delete {
                vertical-align: middle;
                margin-left: .25rem;
            }
        </style>
		<?php
	}
}
