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

class Sifency_Addons_Header_Loader {

	/**
	 * Initializes the class.
	 *
	 * Hooks the following actions:
	 * - 'wp_enqueue_scripts' with a priority of 10 to enqueue Elementor styles & scripts for header template
	 * - 'wp_head' to replace the theme's original header with the Elementor header template
	 * - 'template_redirect' to replace the theme's original header with the Elementor header template
	 * - 'admin_bar_menu' with a priority of 200 to add an admin bar link to edit the header template
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_header_assets' ), 10 );
		add_action( 'wp_head', array( $this, 'replace_theme_original_header' ) );
		add_action( 'template_redirect', array( $this, 'sifency_addons_replace_header' ) );
		add_action( 'admin_bar_menu', array( $this, 'add_admin_bar_link' ), 200 );
	}

	/**
	 * Enqueue Elementor styles & scripts for header template
	 *
	 * This function is hooked to 'wp_enqueue_scripts' action with a priority of 10.
	 * It uses the 'elementor/frontend/after_enqueue_styles' action to enqueue scripts
	 * and Elementor CSS file (if exists) for the header template.
	 *
	 * @since 1.0.0
	 */
	public function enqueue_header_assets() {

		$header_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'header' );

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

		add_action(
			'elementor/frontend/after_enqueue_styles',
			function () use ( $header_id ) {

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

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

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

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

	public function replace_theme_original_header() {
		$header_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'header' );
		if ( ! $header_id ) {
			return;
		}

		$selectors_to_hide = array(
			'.theme-header',
			'header#qodef-page-mobile-header',
		);
		$theme             = wp_get_theme();
		$theme_slug        = $theme->get_template();

		$third_party_themes = array(
			'twentytwentyfive'  => 'header.wp-block-template-part',
			'twentytwentyfour'  => 'header.wp-block-template-part',
			'twentytwentythree' => 'header.wp-block-template-part',
			'astra'             => '#masthead',
			'oceanwp'           => '#site-header',
			'generatepress'     => '.site-header',
			'kadence'           => '#site-header',
			'hello-elementor'   => '#site-header',
			'twentytwentyone'   => '#site-header',
			'twentytwenty'      => '#site-header',
			'blocksy'           => 'header.site-header',
			'neve'              => 'header.header',
		);

		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-header">';
			echo esc_html( $final_css_selector ) . ' { display: none !important; }';
			echo '</style>';
		}
	}

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

		$header_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'header' );

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

	public function sifency_addons_replace_header() {
		$header_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'header' );
		if ( ! $header_id ) {
			return;
		}

		if ( function_exists( 'is_woocommerce' ) && is_woocommerce() ) {
			add_action( 'woocommerce_before_main_content', array( $this, 'render_woocommerce_header' ), 1 );
			return;
		}

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

	public function render_woocommerce_header() {
		static $rendered = false;
		if ( $rendered ) {
			return;
		}

		$header_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'header' );
		if ( ! $header_id || ! class_exists( '\Elementor\Plugin' ) ) {
			return;
		}

		$rendered = true;
		?>
		<header id="sifency-custom-header" class="sifency-header sifency-woocommerce-header" itemscope itemtype="https://schema.org/WPHeader">
			<?php
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor already escapes content internally.
				echo \Elementor\Plugin::instance()->frontend
				->get_builder_content_for_display( $header_id, true );
			?>
		</header>
		<?php
	}
	public function start_buffer() {
		ob_start();
	}

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

			$header_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'header' );

			if ( $header_id && class_exists( '\Elementor\Plugin' ) ) {
				ob_start();
				?>
			<header id="sifency-custom-header" class="sifency-header" itemscope itemtype="https://schema.org/WPHeader">
				<?php
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
				echo \Elementor\Plugin::instance()->frontend->get_builder_content_for_display( $header_id, true );
				?>
			</header>
				<?php
				$custom_header_html = ob_get_clean();

				$pattern = '/<header[^>]*>.*?<\/header>/is';
				if ( preg_match( $pattern, $content ) ) {
					$content = preg_replace( $pattern, $custom_header_html, $content, 1 );
				} else {
					$content = preg_replace( '/<body([^>]*)>/i', '<body$1>' . $custom_header_html, $content, 1 );
				}
			}

			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			echo $content;
		}
	}
}

new Sifency_Addons_Header_Loader();
