<?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' ) || is_admin() ) && ! $force_init ) {
			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, 3 );

		// 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, 3 );
	}

	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.
	 * @param string $context Additional context, like the current filter name or the function name from where this was called.
	 * @param int    $attachment_id The image attachment ID. May be 0 in case the image is not an attachment.

	 * @return string
	 */
	function woodmart_lazy_gutenberg_images( $filtered_image, $context, $attachment_id ) {
		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' ) && ! $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 );
	}
}

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 ) {
		$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.
	 * @param string $size Size.
	 * @return array
	 */
	function woodmart_lazy_attributes( $attr, $attachment, $size ) {
		if ( wp_is_serving_rest_request() || $attr['src'] == woodmart_lazy_get_default_preview() ) {
			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 ( 'none' !== $lazy_effect ) {
			$class .= ' wd-lazy-' . $lazy_effect;
		}

		$class .= woodmart_get_old_classes( ' wd-lazy-load woodmart-lazy-load' );

		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.
	 * @param WP_Block $instance The block instance.
	 *
	 * @return string
	 */
	function woodmart_add_lazy_load_background( $block_content, $block, $instance ) {
		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'] );
				}
			);

			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'] );
				}
			);

			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;
	}

	add_filter( 'render_block', 'woodmart_add_lazy_load_background', 10, 3 );
}
