<?php
/**
 * Auto-display handler module for SiteStaffr widget.
 *
 * @package SiteStaffr
 */

class SiteStaffr_Widget_Auto_Display_Handler {

	/**
	 * Return allowed HTML tags for widget output escaping.
	 *
	 * @since 1.3.4
	 * @return array
	 */
	private static function get_widget_allowed_html() {
		static $cache = null;
		if ( null !== $cache ) {
			return $cache;
		}
		$allowed = wp_kses_allowed_html( 'post' );

		// Widget-specific elements.
		$allowed['button'] = array(
			'type'       => true,
			'class'      => true,
			'aria-label' => true,
			'style'      => true,
		);
		$allowed['audio'] = array(
			'id'    => true,
			'style' => true,
		);

		// SVG tags for widget icons.
		$svg_tags = SiteStaffr_Button_Widget::get_svg_allowed_html();
		foreach ( $svg_tags as $tag => $attrs ) {
			$allowed[ $tag ] = $attrs;
		}

		// Ensure div/span have necessary attributes.
		if ( ! isset( $allowed['div'] ) ) {
			$allowed['div'] = array();
		}
		$allowed['div']['id']    = true;
		$allowed['div']['class'] = true;
		$allowed['div']['style'] = true;
		$allowed['div']['role']  = true;

		$cache = $allowed;
		return $cache;
	}

	/**
	 * Auto-display the fixed widget in the footer if enabled and not already rendered.
	 *
	 * @since 0.14.262
	 * @param callable $is_rendered Callback returning rendered state.
	 * @param callable $render_widget Callback returning rendered widget HTML.
	 * @return void
	 */
	public static function maybe_auto_display( callable $is_rendered, callable $render_widget ) {
		// Skip if already rendered via shortcode on this page
		if ( $is_rendered() ) {
			return;
		}

		// Check the auto-display setting (defaults to ON)
		$widget_settings = SiteStaffr_Widget_Settings_Provider::get_widget_settings();
		$auto_display    = ! isset( $widget_settings['fixed_auto_display'] ) || $widget_settings['fixed_auto_display'];

		if ( ! $auto_display ) {
			return;
		}

		// Render the widget (render_widget returns HTML with all values escaped internally).
		$widget_html = $render_widget();
		echo wp_kses( $widget_html, self::get_widget_allowed_html() );
	}
}
