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

class Sifency_Addons_Footer_Loader {

	public function __construct() {
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_footer_assets' ), 10 );
		add_action( 'wp_head', array( $this, 'replace_theme_original_footer' ) );
		add_action( 'admin_bar_menu', array( $this, 'add_admin_bar_link' ), 200 );
		add_action( 'get_footer', array( $this, 'start_buffer' ), 1 );
		add_action( 'wp_footer', array( $this, 'end_buffer' ), 9999 );
	}

	public function enqueue_footer_assets() {

		$footer_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'footer' );

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

		/**
		 * Ensure Elementor frontend styles are registered first
		 * (prevents elementor-frontend dependency notice)
		 */
		add_action(
			'elementor/frontend/after_enqueue_styles',
			function () use ( $footer_id ) {

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

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

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

		/**
		 * Render Elementor footer content
		 */
		ob_start();
		\Elementor\Plugin::instance()->frontend
			->get_builder_content_for_display( $footer_id, true );
		ob_end_clean();
	}
	/**
	 * Hides the theme's original footer via CSS.
	 * Includes a global class '.theme-footer' and support for popular themes.
	 */
	public function replace_theme_original_footer() {

		$footer_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'footer' );
		if ( ! $footer_id ) {
			return;
		}

		$selectors_to_hide = array(
			'.theme-footer',
		);

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

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

		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-footer">';
			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;
		}

		$footer_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'footer' );

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

	public function start_buffer() {
		ob_start();
	}

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

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

			// ← ADD THIS GUARD
			if ( $template_id && class_exists( '\Elementor\Plugin' ) ) {
				ob_start();
				?>
			<!-- Sifency Custom Footer Start -->
			<footer id="sifency-custom-footer" class="sifency-footer" itemscope itemtype="https://schema.org/WPFooter">
				<?php
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
				echo \Elementor\Plugin::instance()->frontend->get_builder_content_for_display( $template_id, true );
				?>
			</footer>
			<!-- Sifency Custom Footer End -->
				<?php
				$custom_html = ob_get_clean();

				$pattern = '/<footer\b[^>]*>.*?<\/footer>/is';

				if ( preg_match( $pattern, $footer_content ) ) {
					$footer_content = preg_replace( $pattern, $custom_html, $footer_content, 1 );
				} else {
					$footer_content = $custom_html . $footer_content;
				}
			}

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