<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Sifency_Addons_Sub_Header_Render {

	private static $rendered = false;

	public function __construct() {
		if ( is_admin() ) {
			return;
		}

		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_subheader_assets' ), 10 );
		add_action( 'wp_head', array( $this, 'remove_theme_original_subheader' ) );
		add_action( 'admin_bar_menu', array( $this, 'add_admin_bar_link' ), 200 );
		add_action( 'template_redirect', array( $this, 'init_hooks' ) );
	}

	public function remove_theme_original_subheader() {
		$template_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'subheader' );
		if ( ! $template_id ) {
			return;
		}

		$selectors_to_hide = array(
			'.theme-subheader',
			'#qodef-page-outer',
		);

		$theme      = wp_get_theme();
		$theme_slug = $theme->get_template();

		$third_party_themes = array(
			'astra'            => '.ast-breadcrumbs-wrapper, .ast-archive-description',
			'oceanwp'          => '.page-header, .oceanwp-breadcrumb',
			'generatepress'    => '.page-header-content, .entry-header',
			'kadence'          => '.kadence-breadcrumbs, .entry-hero-container',
			'hello-elementor'  => '.page-header',
			'twentytwentyone'  => 'header.entry-header',
			'twentytwentyfour' => 'header.entry-header',
			'blocksy'          => '.hero-section',
		);

		if ( array_key_exists( $theme_slug, $third_party_themes ) ) {
			$selectors_to_hide[] = $third_party_themes[ $theme_slug ];
		}

		if ( ! empty( $selectors_to_hide ) ) {
			$final_css_selector = implode( ', ', $selectors_to_hide );

			echo '<style id="sifency-hide-theme-subheader">';
			echo esc_html( $final_css_selector ) . ' { display: none !important; }';
			echo '</style>';
		}
	}
	public function enqueue_subheader_assets() {

		if ( self::$rendered ) {
			return;
		}

		$template_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'subheader' );

		if ( ! $template_id || ! class_exists( '\Elementor\Plugin' ) ) {
			return;
		}

		/**
		 * Ensure Elementor frontend styles are registered first
		 */
		add_action(
			'elementor/frontend/after_enqueue_styles',
			function () use ( $template_id ) {

				\Elementor\Plugin::instance()->frontend->enqueue_scripts();

				if ( class_exists( '\Elementor\Core\Files\CSS\Post' ) ) {
					$css_file = new \Elementor\Core\Files\CSS\Post( $template_id );
				} elseif ( class_exists( '\Elementor\Post_CSS_File' ) ) {
					$css_file = new \Elementor\Post_CSS_File( $template_id );
				} else {
					$css_file = null;
				}

				if ( $css_file ) {
					$css_file->enqueue();
				}
			}
		);

		/**
		 * Render Elementor subheader content
		 */
		ob_start();
		\Elementor\Plugin::instance()->frontend
			->get_builder_content_for_display( $template_id, true );
		ob_end_clean();
	}

	public function add_admin_bar_link( \WP_Admin_Bar $admin_bar ) {
		if ( ! current_user_can( 'edit_posts' ) || ! is_admin_bar_showing() ) {
			return;
		}

		$template_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'subheader' );

		if ( $template_id && class_exists( '\Elementor\Plugin' ) ) {
			$admin_bar->add_node(
				array(
					'id'     => 'sifency-subheader-edit',
					'parent' => 'elementor_edit_page',
					'title'  => __( 'Edit Subheader', 'sifency-addons' ),
					'href'   => admin_url( 'post.php?post=' . $template_id . '&action=elementor' ),
				)
			);
		}
	}

	public function init_hooks() {
		if ( self::$rendered ) {
			return;
		}

		$template_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'subheader' );
		if ( ! $template_id ) {
			return;
		}

		add_action( 'get_header', array( $this, 'start_buffer' ), 15 );
		add_action( 'wp_footer', array( $this, 'end_buffer' ), 9999 );
	}

	public function start_buffer() {
		ob_start();
	}

	public function end_buffer() {
		if ( ob_get_length() ) {
			$content = ob_get_clean();

			if ( strpos( $content, 'sifency-elementor-below-header' ) !== false ) {
				echo esc_html( $content ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
				return;
			}

			if ( self::$rendered ) {
                 // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Full response buffer with injected Elementor markup.
				echo $content;
				return;
			}

			$template_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'subheader' );

			if ( $template_id ) {
				self::$rendered = true;

				ob_start();
				?>
				<!-- Sifency Elementor Below Header Start -->
				<div class="sifency-elementor-below-header">
					<?php
                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor already escapes content internally.
					echo \Elementor\Plugin::instance()->frontend->get_builder_content_for_display( $template_id, true );
					?>
				</div>
				<!-- Sifency Elementor Below Header End -->
				<?php
				$subheader_html = ob_get_clean();

				$pattern_custom  = '/(<header[^>]*id="sifency-custom-header"[^>]*>.*?)(<\/header>)/is';
				$pattern_general = '/(<\/header>)/i';

				if ( preg_match( $pattern_custom, $content ) ) {
					$content = preg_replace( $pattern_custom, '$1$2' . $subheader_html, $content, 1 );
				} elseif ( preg_match( $pattern_general, $content ) ) {
					$content = preg_replace( $pattern_general, '$1' . $subheader_html, $content, 1 );
				} else {
					$content = $subheader_html . $content;
				}
			}

            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Full response buffer with injected Elementor markup.
			echo $content;
		}
	}
}
