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

		private static $rendered = false;

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

			add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_after_subheader_assets' ), 10 );
			add_action( 'admin_bar_menu', array( $this, 'add_admin_bar_link' ), 201 );
			add_action( 'template_redirect', array( $this, 'init_hooks' ) );
		}

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

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

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

			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();
					}
				}
			);

			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( 'after-subheader' );

			if ( $template_id && class_exists( '\Elementor\Plugin' ) ) {
				$admin_bar->add_node(
					array(
						'id'     => 'sifency-after-subheader-edit',
						'parent' => 'elementor_edit_page',
						'title'  => __( 'Edit After 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( 'after-subheader' );
			if ( ! $template_id ) {
				return;
			}

			// Start buffer just before subheader (priority 14) and end it after subheader (priority 10000)
			add_action( 'get_header', array( $this, 'start_buffer' ), 14 );
			add_action( 'wp_footer', array( $this, 'end_buffer' ), 10000 );
		}

		public function start_buffer() {
			ob_start();
		}

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

				if ( strpos( $content, 'sifency-elementor-after-subheader' ) !== false ) {
					echo esc_html( $content );
					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( 'after-subheader' );

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

					ob_start();
					?>
				<!-- Sifency Elementor After Subheader Start -->
				<div class="sifency-elementor-after-subheader">
					<?php
                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor escapes content internally.
					echo \Elementor\Plugin::instance()->frontend->get_builder_content_for_display( $template_id, true );
					?>
				</div>
				<!-- Sifency Elementor After Subheader End -->
					<?php
					$after_subheader_html = ob_get_clean();

					$pattern_subheader = '/(<!-- Sifency Elementor Below Header End -->)/is';
					$pattern_custom    = '/(<header[^>]*id="sifency-custom-header"[^>]*>.*?)(<\/header>)/is';
					$pattern_general   = '/(<\/header>)/i';

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

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