<?php
defined( 'ABSPATH' ) || exit;

/**
 * Frontend asset registration and enqueue.
 */
class AWP_Assets {

	/**
	 * Whether assets were enqueued.
	 *
	 * @var bool
	 */
	private static $enqueued = false;

	/**
	 * Register handles early.
	 */
	public static function register() {
		wp_register_style(
			'swiper',
			AWP_SLIDER_PLUGIN_URL . 'assets/vendor/swiper/swiper-bundle.min.css',
			array(),
			'11.0.0'
		);

		wp_register_style(
			'awp-slider',
			AWP_SLIDER_PLUGIN_URL . 'assets/css/awp-slider.css',
			array( 'swiper' ),
			AWP_PLUGIN_VERSION
		);

		wp_register_script(
			'swiper',
			AWP_SLIDER_PLUGIN_URL . 'assets/vendor/swiper/swiper-bundle.min.js',
			array(),
			'11.0.0',
			true
		);

		wp_register_script(
			'awp-slider',
			AWP_SLIDER_PLUGIN_URL . 'assets/js/awp-slider.js',
			array( 'swiper' ),
			AWP_PLUGIN_VERSION,
			true
		);
	}

	/**
	 * Enqueue slider assets once.
	 */
	public static function enqueue() {
		if ( self::$enqueued ) {
			return;
		}

		self::register();
		wp_enqueue_style( 'awp-slider' );
		wp_enqueue_script( 'awp-slider' );
		self::$enqueued = true;
	}

	/**
	 * Hook: register on wp_enqueue_scripts / elementor.
	 */
	public static function init() {
		add_action( 'wp_enqueue_scripts', array( __CLASS__, 'register' ) );
		add_action( 'wp_enqueue_scripts', array( __CLASS__, 'maybe_enqueue_for_shortcode' ), 20 );
		add_action( 'elementor/frontend/after_register_scripts', array( __CLASS__, 'register' ) );
		add_action( 'elementor/frontend/after_register_styles', array( __CLASS__, 'register' ) );
	}

	/**
	 * Enqueue early when the singular post content contains the shortcode.
	 */
	public static function maybe_enqueue_for_shortcode() {
		if ( ! is_singular() ) {
			return;
		}

		$post = get_post();
		if ( $post instanceof WP_Post && has_shortcode( $post->post_content, 'AWP-SLIDER' ) ) {
			self::enqueue();
		}
	}
}
