<?php
/**
 * Lazy image helpers for FoodOrd.
 *
 * @package FoodOrd
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! function_exists( 'foodord_get_lazy_placeholder_url' ) ) {
	/**
	 * Retrieve the shared lazy image placeholder asset URL.
	 *
	 * @return string
	 */
	function foodord_get_lazy_placeholder_url() {
		return FOODORD_URL . 'public/images/transparent-placeholder.svg';
	}
}

if ( ! function_exists( 'foodord_enqueue_lazy_image_script' ) ) {
	/**
	 * Ensure lazy loader script is available on the frontend.
	 */
	function foodord_enqueue_lazy_image_script() {
		if ( ! wp_script_is( 'foodord-lazy-images', 'registered' ) ) {
			wp_register_script(
				'foodord-lazy-images',
				FOODORD_URL . 'public/js/foodord-lazy-images.js',
				array(),
				FOODORD_VERSION,
				true
			);
		}

		wp_add_inline_script(
			'foodord-lazy-images',
			'window.FOODORD_LAZY_PLACEHOLDER = ' . wp_json_encode( foodord_get_lazy_placeholder_url() ) . ';',
			'before'
		);

		wp_enqueue_script( 'foodord-lazy-images' );
	}
}

if ( ! function_exists( 'foodord_get_lazy_image_html' ) ) {
	/**
	 * Build lazy-loading image markup for plugin usage.
	 *
	 * @param array $args Image arguments.
	 * @return string
	 */
	function foodord_get_lazy_image_html( $args = array() ) {
		$defaults = array(
			'id'          => 0,
			'size'        => 'full',
			'src'         => '',
			'alt'         => '',
			'class'       => '',
			'width'       => null,
			'height'      => null,
			'loading'     => 'lazy',
			'decoding'    => 'async',
			'attributes'  => array(),
			'placeholder' => foodord_get_lazy_placeholder_url(),
		);
		$args     = wp_parse_args( $args, $defaults );

		$attachment_id = absint( $args['id'] );
		if ( $attachment_id > 0 ) {
			$image = wp_get_attachment_image_src( $attachment_id, $args['size'] );
			if ( $image ) {
				$args['src']    = $image[0];
				$args['width']  = $args['width'] ? $args['width'] : $image[1];
				$args['height'] = $args['height'] ? $args['height'] : $image[2];
			}

			if ( '' === $args['alt'] ) {
				$alt_meta = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
				if ( '' !== $alt_meta ) {
					$args['alt'] = $alt_meta;
				}
			}

			$srcset = wp_get_attachment_image_srcset( $attachment_id, $args['size'] );
			if ( $srcset ) {
				$args['attributes']['data-foodord-lazy-srcset'] = $srcset;
			}

			$sizes = wp_get_attachment_image_sizes( $attachment_id, $args['size'] );
			if ( $sizes ) {
				$args['attributes']['data-foodord-lazy-sizes'] = $sizes;
			}
		}

		if ( '' === $args['src'] ) {
			return '';
		}

		$src_is_svg      = (bool) preg_match( '/\.svg(\?.*)?$/i', $args['src'] );
		$allowed_loading = in_array( $args['loading'], array( 'lazy', 'eager', 'auto' ), true ) ? $args['loading'] : 'lazy';
		$decoding_attr   = ( 'sync' === $args['decoding'] ) ? 'sync' : 'async';
		$placeholder_src = $args['placeholder'];
		$has_placeholder = ( '' !== $placeholder_src && $placeholder_src !== $args['src'] );

		if ( $src_is_svg || 'eager' === $allowed_loading || ! $has_placeholder ) {
			$plain_attributes = array();
			$classes          = trim( $args['class'] );
			if ( '' !== $classes ) {
				$plain_attributes['class'] = $classes;
			}
			$plain_attributes['src'] = $args['src'];
			$plain_attributes['alt'] = $args['alt'];
			if ( ! empty( $args['width'] ) ) {
				$plain_attributes['width'] = (string) absint( $args['width'] );
			}
			if ( ! empty( $args['height'] ) ) {
				$plain_attributes['height'] = (string) absint( $args['height'] );
			}
			if ( 'auto' !== $allowed_loading ) {
				$plain_attributes['loading'] = $allowed_loading;
			}
			$plain_attributes['decoding'] = $decoding_attr;
			foreach ( $args['attributes'] as $key => $value ) {
				if ( '' === $value ) {
					continue;
				}
				$plain_attributes[ $key ] = $value;
			}
			$plain_strings = array();
			foreach ( $plain_attributes as $key => $value ) {
				$plain_strings[] = sprintf( '%s="%s"', esc_attr( $key ), esc_attr( $value ) );
			}
			return '<img ' . implode( ' ', $plain_strings ) . ' />';
		}

		foodord_enqueue_lazy_image_script();

		$attributes = array();
		$classes    = trim( 'foodord-lazy-image ' . $args['class'] );
		if ( '' !== $classes ) {
			$attributes['class'] = $classes;
		}

		$attributes['src']                   = $placeholder_src;
		$attributes['data-foodord-lazy-src'] = $args['src'];

		$attributes['alt'] = $args['alt'];

		if ( ! empty( $args['width'] ) ) {
			$attributes['width'] = (string) absint( $args['width'] );
		}

		if ( ! empty( $args['height'] ) ) {
			$attributes['height'] = (string) absint( $args['height'] );
		}

		$attributes['loading']  = $allowed_loading;
		$attributes['decoding'] = $decoding_attr;

		foreach ( $args['attributes'] as $key => $value ) {
			if ( '' === $value ) {
				continue;
			}
			$attributes[ $key ] = $value;
		}

		$attribute_strings = array();
		foreach ( $attributes as $key => $value ) {
			$attribute_strings[] = sprintf( '%s="%s"', esc_attr( $key ), esc_attr( $value ) );
		}

		return '<img ' . implode( ' ', $attribute_strings ) . ' />';
	}
}

add_filter(
	'wp_get_attachment_image_attributes',
	function ( $attr ) {
		if ( empty( $attr['loading'] ) ) {
			$attr['loading'] = 'lazy';
		}
		$attr['decoding'] = isset( $attr['decoding'] ) && 'sync' === $attr['decoding'] ? 'sync' : 'async';
		return $attr;
	}
);
