<?php
/**
 * Lazy loading functions.
 *
 * @package woodmart
 */

if ( ! defined( 'WOODMART_THEME_DIR' ) ) {
	exit( 'No direct script access allowed' );
}

if ( ! function_exists( 'woodmart_lazy_loading_init' ) ) {
	/**
	 * Init lazy loading.
	 *
	 * @param boolean $force_init Force init.
	 * @return void
	 */
	function woodmart_lazy_loading_init( $force_init = false ) {
		if ( ( woodmart_get_opt( 'lazy_loading_bg_images' ) || $force_init ) && ! is_admin() ) {
			add_filter( 'render_block', 'woodmart_add_lazy_load_background', 10, 3 );
		}

		if (
			(
				(
					! woodmart_get_opt( 'lazy_loading' ) ||
					is_admin()
				) &&
				! $force_init
			) ||
			! apply_filters( 'woodmart_enable_lazy_loading', true )
		) {
			return;
		}

		// Used for avatar images.
		add_filter( 'get_avatar', 'woodmart_lazy_image_standard', 10 );

		// Used for instagram images.
		add_filter( 'woodmart_image', 'woodmart_lazy_image_standard', 10, 1 );

		// Images generated by WPBakery functions.
		add_filter( 'vc_wpb_getimagesize', 'woodmart_lazy_image', 10, 3 );

		// Products, blog, a lot of other standard WordPress images.
		add_filter( 'wp_get_attachment_image_attributes', 'woodmart_lazy_attributes', 10, 2 );

		// Elementor.
		add_filter( 'elementor/image_size/get_attachment_image_html', 'woodmart_filter_elementor_images', 10, 4 );

		// Gutenberg.
		add_action( 'wp_content_img_tag', 'woodmart_lazy_gutenberg_images', 20 );

		add_filter( 'render_block_wd/video', 'woodmart_video_poster_lazy_loading', 10, 2 );
		add_filter( 'woodmart_video_html', 'woodmart_video_poster_lazy_loading', 10, 2 );
	}

	add_action( 'init', 'woodmart_lazy_loading_init', 120 );
}

if ( ! function_exists( 'woodmart_lazy_gutenberg_images' ) ) {
	/**
	 * Filters HTML <img> tag and adds lazy loading attributes. Used for gutenberg images.
	 *
	 * @param string $filtered_image Full img tag with attributes that will replace the source img tag.

	 * @return string
	 */
	function woodmart_lazy_gutenberg_images( $filtered_image ) {
		if ( str_contains( $filtered_image, woodmart_lazy_get_default_preview() ) || ! preg_match( '/class=["\'].*wp-image-.*["\']/is', $filtered_image ) ) {
			return $filtered_image;
		}

		woodmart_enqueue_js_script( 'lazy-loading' );

		return woodmart_lazy_replace_image( $filtered_image, woodmart_lazy_get_default_preview() );
	}
}

if ( ! function_exists( 'woodmart_filter_elementor_images' ) ) {
	/**
	 * Filters HTML <img> tag and adds lazy loading attributes. Used for elementor images.
	 *
	 * @since 1.0.0
	 *
	 * @param string $html           Image html.
	 * @param array  $settings       Control settings.
	 * @param string $image_size_key Optional. Settings key for image size.
	 * @param string $image_key      Optional. Settings key for image.
	 *
	 * @return string
	 */
	function woodmart_filter_elementor_images( $html, $settings, $image_size_key, $image_key ) {
		if ( str_contains( $html, woodmart_lazy_get_default_preview() ) ) {
			return $html;
		}

		$image         = $settings[ $image_key ];
		$image_sizes   = get_intermediate_image_sizes();
		$image_sizes[] = 'full';
		$size          = $settings[ $image_size_key . '_size' ];

		if ( $image['id'] && in_array( $size, $image_sizes ) ) { // phpcs:ignore
			return $html;
		}

		woodmart_enqueue_js_script( 'lazy-loading' );

		return woodmart_lazy_replace_image( $html, woodmart_lazy_get_default_preview() );
	}
}

if ( ! function_exists( 'woodmart_lazy_loading_rss_deinit' ) ) {
	/**
	 * Lazy loading deinit for RSS.
	 *
	 * @return void
	 */
	function woodmart_lazy_loading_rss_deinit() {
		if ( is_feed() ) {
			woodmart_lazy_loading_deinit( true );
		}
	}

	add_action( 'wp', 'woodmart_lazy_loading_rss_deinit', 10 );
}

if ( ! function_exists( 'woodmart_lazy_loading_deinit' ) ) {
	/**
	 * Lazy loading deinit.
	 *
	 * @param boolean $force_deinit Force deinit.
	 * @return void
	 */
	function woodmart_lazy_loading_deinit( $force_deinit = false ) {
		if ( ! woodmart_get_opt( 'lazy_loading_bg_images' ) || $force_deinit ) {
			remove_filter( 'render_block', 'woodmart_add_lazy_load_background', 10 );
		}

		if ( woodmart_get_opt( 'lazy_loading' ) && ! $force_deinit ) {
			return;
		}

		remove_action( 'get_avatar', 'woodmart_lazy_image_standard', 10 );
		remove_action( 'woodmart_image', 'woodmart_lazy_image_standard', 10 );
		remove_action( 'vc_wpb_getimagesize', 'woodmart_lazy_image', 10 );
		remove_action( 'wp_get_attachment_image_attributes', 'woodmart_lazy_attributes', 10 );
		remove_action( 'elementor/image_size/get_attachment_image_html', 'woodmart_filter_elementor_images', 10 );
		remove_action( 'wp_content_img_tag', 'woodmart_lazy_gutenberg_images', 20 );
		remove_action( 'render_block_wd/video', 'woodmart_video_poster_lazy_loading', 10, 2 );
		remove_action( 'woodmart_video_html', 'woodmart_video_poster_lazy_loading', 10, 2 );
	}
}

if ( ! function_exists( 'woodmart_lazy_loading_force_deinit' ) ) {
	/**
	 * Fix Woocommerce email with lazy load.
	 *
	 * @return void
	 */
	function woodmart_lazy_loading_force_deinit() {
		woodmart_lazy_loading_deinit( true );
	}

	add_action( 'woocommerce_email_before_order_table', 'woodmart_lazy_loading_force_deinit', 20 );
	add_action( 'woocommerce_email_header', 'woodmart_lazy_loading_force_deinit', 20 );
	add_action( 'woocommerce_before_mini_cart_contents', 'woodmart_lazy_loading_force_deinit', 20 );
}

if ( ! function_exists( 'woodmart_lazy_loading_force_init' ) ) {
	/**
	 * Fix Woocommerce email with lazy load.
	 *
	 * @return void
	 */
	function woodmart_lazy_loading_force_init() {
		woodmart_lazy_loading_init( true );
	}

	add_action( 'woocommerce_email_after_order_table', 'woodmart_lazy_loading_force_init', 20 );
	add_action( 'woocommerce_email_footer', 'woodmart_lazy_loading_force_init', 20 );
	add_action( 'woocommerce_mini_cart_contents', 'woodmart_lazy_loading_init', 20 );
}

if ( ! function_exists( 'woodmart_lazy_image_standard' ) ) {
	/**
	 * Filters HTML <img> tag and adds lazy loading attributes. Used for instagram images.
	 *
	 * @param string $html Image html.
	 * @return string
	 */
	function woodmart_lazy_image_standard( $html ) {
		if ( str_contains( $html, woodmart_lazy_get_default_preview() ) ) {
			return $html;
		}

		woodmart_enqueue_js_script( 'lazy-loading' );

		return woodmart_lazy_replace_image( $html, woodmart_lazy_get_default_preview() );
	}
}

if ( ! function_exists( 'woodmart_lazy_get_default_preview' ) ) {
	/**
	 * Get default preview image.
	 *
	 * @return mixed|null
	 */
	function woodmart_lazy_get_default_preview() {
		$placeholder = woodmart_get_opt( 'lazy_custom_placeholder' );

		if ( ! empty( $placeholder['url'] ) ) {
			return $placeholder['url'];
		}

		return WOODMART_IMAGES . '/lazy.svg';
	}
}

if ( ! function_exists( 'woodmart_lazy_image' ) ) {
	/**
	 * Filters WPBakery generated image. Needs an HTML, its ID, and params with image size.
	 *
	 * @param array   $img Image.
	 * @param integer $attach_id Attachment ID.
	 * @param array   $params Params.
	 * @return array
	 */
	function woodmart_lazy_image( $img, $attach_id, $params ) {
		if ( str_contains( $img['thumbnail'], woodmart_lazy_get_default_preview() ) ) {
			return $img;
		}

		if ( ! empty( $params['thumb_size'] ) ) {
			$image_sizes   = get_intermediate_image_sizes();
			$image_sizes[] = 'full';

			if ( in_array( $params['thumb_size'], $image_sizes ) ) { // phpcs:ignore
				return $img;
			}
		}

		$img['thumbnail'] = woodmart_lazy_replace_image( $img['thumbnail'], woodmart_lazy_get_default_preview() );

		woodmart_enqueue_js_script( 'lazy-loading' );

		return $img;
	}
}

if ( ! function_exists( 'woodmart_lazy_replace_image' ) ) {
	/**
	 * Filters <img> tag passed as an argument.
	 *
	 * @param string $html HTML.
	 * @param string $src Image src.
	 * @return string
	 */
	function woodmart_lazy_replace_image( $html, $src ) {
		if ( ! preg_match( '/<img[^>]*\ssrc=(["\'])(.*?)\1/i', $html, $match ) || str_contains( $html, 'fetchpriority' ) ) {
			return $html;
		}

		$original_src = $match[2];

		if ( in_array( $original_src, apply_filters( 'woodmart_exclude_lazyload_urls', array() ), true ) ) {
			return $html;
		}

		$class = woodmart_lazy_css_class();

		$new = preg_replace( '/<img(.*?)src=/is', '<img$1src="' . $src . '" data-src=', $html );
		$new = preg_replace( '/<img(.*?)srcset=/is', '<img$1srcset="" data-srcset=', $new );

		if ( $class ) {
			if ( preg_match( '/<img(.*?)class=["\']/i', $new ) ) {
				$new = preg_replace( '/class=(["\'])(.*?)["\']/is', 'class=$1' . $class . ' $2$1', $new );
			} else {
				$new = preg_replace( '/<img/is', '<img class="' . $class . '"', $new );
			}
		}

		return $new;
	}
}

if ( ! function_exists( 'woodmart_lazy_attributes' ) ) {
	/**
	 * Filters default WordPress images ATTRIBUTES array called by core API functions.
	 *
	 * @param array  $attr Attributes image.
	 * @param object $attachment Attachment.
	 * @return array
	 */
	function woodmart_lazy_attributes( $attr, $attachment ) {
		if ( wp_is_serving_rest_request() || woodmart_lazy_get_default_preview() === $attr['src'] || in_array( $attr['src'], apply_filters( 'woodmart_exclude_lazyload_urls', array() ), true ) || ! empty( $attr['fetchpriority'] ) ) {
			return $attr;
		}

		$attr['data-src'] = $attr['src'];

		if ( ! empty( $attr['srcset'] ) ) {
			$attr['data-srcset'] = $attr['srcset'];
		}

		if ( is_object( $attachment ) ) {
			$attr['src'] = woodmart_lazy_get_default_preview();
		}

		$attr['srcset'] = '';

		$attr['class'] = $attr['class'] . woodmart_lazy_css_class();

		woodmart_enqueue_js_script( 'lazy-loading' );

		return $attr;
	}
}

if ( ! function_exists( 'woodmart_lazy_css_class' ) ) {
	/**
	 * Get lazy loading image CSS class.
	 *
	 * @return string
	 */
	function woodmart_lazy_css_class() {
		$class       = '';
		$lazy_effect = woodmart_get_opt( 'lazy_effect', 'none' );

		if ( $lazy_effect && 'none' !== $lazy_effect ) {
			$class .= ' wd-lazy-' . $lazy_effect;
		}

		return $class;
	}
}

if ( ! function_exists( 'woodmart_disable_default_lazy_loading' ) ) {
	/**
	 * Disable default lazy loading.
	 *
	 * @return void
	 */
	function woodmart_disable_default_lazy_loading() {
		if ( woodmart_get_opt( 'disable_wordpress_lazy_loading' ) ) {
			add_filter( 'wp_lazy_loading_enabled', '__return_false' );
		}
	}

	add_action( 'init', 'woodmart_disable_default_lazy_loading', 120 );
}

if ( ! function_exists( 'woodmart_add_lazy_load_background' ) ) {
	/**
	 * Add lazy load background for block.
	 *
	 * @param string $block_content The block content.
	 * @param array  $block The full block, including name and attributes.
	 *
	 * @return string
	 */
	function woodmart_add_lazy_load_background( $block_content, $block ) {
		if ( ! woodmart_get_opt( 'lazy_loading_bg_images' ) ) {
			return $block_content;
		}

		$bg_attributes = array( 'bgImage', 'bgImageTablet', 'bgImageMobile', 'bgHoverImage', 'bgHoverImageTablet', 'bgHoverImageMobile', 'bgParentHoverImage', 'bgParentHoverTablet', 'bgParentHoverMobile' );

		$bg_overlay_attributes = array( 'overlayImage', 'overlayImageTablet', 'overlayImageMobile', 'overlayHoverImage', 'overlayHoverImageTablet', 'overlayHoverImageMobile', 'overlayParentHoverImage', 'overlayParentHoverImageTablet', 'overlayParentHoverImageMobile' );

		if ( ! empty( $block['attrs'] ) && ( ( empty( $block['attrs']['bgExcludeLazyLoad'] ) && array_intersect( array_keys( $block['attrs'] ), $bg_attributes ) ) || ( empty( $block['attrs']['overlayExcludeLazyLoad'] ) && array_intersect( array_keys( $block['attrs'] ), $bg_overlay_attributes ) ) ) ) {
			$tags = new WP_HTML_Tag_Processor( $block_content );

			$has_bg_image = array_filter(
				$bg_attributes,
				function ( $key ) use ( $block ) {
					return ! empty( $block['attrs'][ $key ] ) && is_array( $block['attrs'][ $key ] ) && ! empty( $block['attrs'][ $key ]['url'] ) && ! in_array( $block['attrs'][ $key ]['url'], apply_filters( 'woodmart_exclude_lazyload_urls', array() ), true );
				}
			);

			if ( empty( $block['attrs']['bgExcludeLazyLoad'] ) && $has_bg_image && $tags->next_tag() ) {
				$tags->add_class( 'wd-lazy-bg' );
			}

			$has_overlay = array_filter(
				$bg_overlay_attributes,
				function ( $key ) use ( $block ) {
					return ! empty( $block['attrs'][ $key ] ) && is_array( $block['attrs'][ $key ] ) && ! empty( $block['attrs'][ $key ]['url'] ) && ! in_array( $block['attrs'][ $key ]['url'], apply_filters( 'woodmart_exclude_lazyload_urls', array() ), true );
				}
			);

			if ( empty( $block['attrs']['overlayExcludeLazyLoad'] ) && $has_overlay && $tags->next_tag( array( 'class_name' => 'wd-bg-overlay' ) ) ) {
				$tags->add_class( 'wd-lazy-bg' );
			}

			woodmart_enqueue_js_script( 'lazy-loading' );

			return $tags->get_updated_html();
		}

		return $block_content;
	}
}

if ( ! function_exists( 'woodmart_video_poster_lazy_loading' ) ) {
	/**
	 * Filters video poster HTML and adds lazy loading attributes.
	 *
	 * @param string $html Video HTML.
	 * @return string
	 */
	function woodmart_video_poster_lazy_loading( $html ) {
		if ( str_contains( $html, 'data-poster' ) ) {
			return $html;
		}

		woodmart_enqueue_js_script( 'lazy-loading' );

		return preg_replace( '/\bposter\s*=\s*([\'"])(.*?)\1/i', 'data-poster=$1$2$1', $html );
	}
}
