<?php
declare( strict_types=1 );

namespace FiboFilters\Integrations\Plugins;

use FlyingPress\Optimizer\Image;

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

/**
 * Class FlyingPress
 *
 * Plugin Name: FlyingPress
 * Plugin URI: https://flyingpress.com
 * Tested versions: 4.13.3
 */
class FlyingPress extends AbstractPlugin {
	public function init(): void {
		add_filter( 'fibofilters/request/single_products/output', [ $this, 'process_images' ] );
	}

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

		foreach ( $data['products'] as $id => $html ) {
			Image::parse_images( $html );
			Image::add_width_height( $html );
			Image::lazy_load( $html );
			Image::responsive_images( $html );
			$data['products'][ $id ] = Image::write_images( $html );
		}

		return $data;
	}
}
