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

if ( ! class_exists( 'Sifency_Addons_Frontend_Scrollup' ) ) {

	class Sifency_Addons_Frontend_Scrollup {

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

			add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scrollup_assets' ) );
			add_action( 'wp_footer', array( $this, 'render_scrollup' ), 9999 );
			add_action( 'admin_bar_menu', array( $this, 'add_admin_bar_link' ), 200 );
		}

		public function enqueue_scrollup_assets() {

			$scrollup_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'scrollup' );

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

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

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

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

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

			/**
			 * Render Elementor scroll-up content
			 */
			ob_start();
			\Elementor\Plugin::instance()->frontend
				->get_builder_content_for_display( $scrollup_id, true );
			ob_end_clean();

			/**
			 * Scroll-up custom assets
			 */
			wp_enqueue_style(
				'sifency-scrollup-css',
				SIFENCY_TB_URL . 'assets/css/stt.css',
				array(),
				SIFENCY_TB_VERSION,
				'all'
			);

			wp_enqueue_script(
				'sifency-scrollup-js',
				SIFENCY_TB_URL . 'assets/js/stt.js',
				array( 'jquery' ),
				SIFENCY_TB_VERSION,
				true
			);
		}

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

			$scrollup_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'scrollup' );

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

		public function render_scrollup() {
			$scrollup_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'scrollup' );
			if ( ! $scrollup_id ) {
				return;
			}

			echo '<!-- Sifency Custom Scroll-Up Start -->';
			echo '<div id="sifency-scrollup-wrapper" class="sifency-scrollup-wrapper">';
				Sifency_Addons_Frontend_Helper::render_elementor_content( $scrollup_id, true );
			echo '</div>';
			echo '<!-- Sifency Custom Scroll-Up End -->';
		}
	}


}
