<?php
declare( strict_types=1 );

namespace FiboFilters\Integrations\Plugins;

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

/**
 * Class Imagify
 *
 * Plugin Name: Imagify
 * Plugin URI: https://wordpress.org/plugins/imagify/
 * Tested versions: 2.2.5
 */
class Imagify extends AbstractPlugin {
	public function init(): void {
		add_filter( 'fibofilters/request/single_products/output', [ $this, 'process_images' ] );
	}

	/**
	 * Image processing for single products
	 *
	 * As part of the integration, we do what Imagify does during normal processing of website content.
	 *
	 * @see \Imagify\Picture\Display::process_content()
	 *
	 * @param array $data Output data.
	 */
	public function process_images( $data ): array {
		if ( ! is_array( $data['products'] ) ) {
			return $data;
		}

		if ( ! function_exists( 'get_imagify_option' ) ) {
			return $data;
		}

		/** @see \Imagify\Picture\Display::start_content_process() */
		if ( ! get_imagify_option( 'display_nextgen' ) ) {
			return $data;
		}

		if ( get_imagify_option( 'display_nextgen_method' ) !== 'picture' ) {
			return $data;
		}

		// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
		$allow = apply_filters( 'imagify_allow_picture_tags_for_nextgen', true );

		if ( ! $allow ) {
			return $data;
		}

		// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
		$imagify_container = apply_filters( 'imagify_container', null );
		if ( empty( $imagify_container ) ) {
			return $data;
		}

		/** @var \Imagify\Picture\Display $display */
		$display = $imagify_container->get( \Imagify\Picture\Display::class );
		foreach ( $data['products'] as $prod_id => $html ) {
			$data['products'][ $prod_id ] = $display->process_content( $html );
		}

		return $data;
	}
}
