<?php
/**
 * PHP file to use when rendering the block type on the server to show on the front end.
 *
 * The following variables are exposed to the file:
 *     $attributes (array): The block attributes.
 *     $content (string): The block default content.
 *     $block (WP_Block): The block instance.
 *
 * @see https://github.com/WordPress/gutenberg/blob/trunk/docs/reference-guides/block-api/block-metadata.md#render
 */

// Generate unique id for aria-controls.
$unique_id = wp_unique_id( 'p-' );

if ( ! empty( $attributes['overlayColor'] ) ) {

	$popper_styles = array(
		array(
			'selector'     => 'dialog[data-id="' . $attributes['uuid'] . '"]::backdrop',
			'declarations' => array( 'background' => $attributes['overlayColor'] ),
		),
	);

	$popper_stylesheet = wp_style_engine_get_stylesheet_from_css_rules(
		$popper_styles,
		array(
			'context' => 'popper-styles-' . $unique_id,
		)
	);

	$stylesheet = wp_style_engine_get_stylesheet_from_context( 'popper-styles-' . $unique_id );

}

$rules = get_post_meta( $attributes['uuid'], 'popper_rules', true );

$p = new WP_HTML_Tag_Processor( $content );

$context = array(
	'triggers' => $attributes['triggers'],
	'settings' => $attributes['settings'],
	'devices' => $rules['device'] ?? array(),
);

wp_interactivity_config(
	'popper',
	array(
		'ajax_url' => admin_url( 'admin-ajax.php' ),
		'debug'    => ! empty( $attributes['debug'] ) && current_user_can( 'manage_options' ) ?? false,
		'nonce'    => wp_create_nonce( 'popper' ),
		'mediaUrl' => empty( $attributes['sound'] ) ? '' : plugins_url() . '/popper/assets/audio/' . $attributes['sound'] . '.mp3',
	)
);

if ( $p->next_tag( 'dialog' ) ) {
	$p->set_attribute( 'data-wp-interactive', 'popper' );
	$p->set_attribute( 'data-wp-context', wp_json_encode( $context ) );
	$p->set_attribute( 'data-wp-init', 'callbacks.init' );
	$p->set_attribute( 'data-wp-on-async-document--scroll', 'callbacks.scroll' );
	$p->set_attribute( 'data-wp-on-async-document--mouseout', 'callbacks.exit' );
	$p->set_attribute( 'data-wp-on-async-document--mousemove', 'callbacks.hover' );
	// Needs preventDefault, so I cannot use async.
	$p->set_attribute( 'data-wp-on-document--click', 'callbacks.click' );
	$p->set_attribute( 'data-wp-on--click', 'callbacks.closeOnOverlayClick' );
}

if (
	$p->next_tag(
		array(
			'tag_name' => 'div',
			'class_name' => 'wp-block-popper__close',
		)
	)
) {
	$p->set_attribute( 'aria-label', __( 'Close modal', 'popper' ) );
}

echo $p->get_updated_html();
