<?php
/**
 * Resolves Grundpreis from WooCommerce German Market.
 *
 * @package PhoenixWP\PriceLabels
 */

declare(strict_types=1);

namespace PhoenixWP\PriceLabels\Compliance\Providers;

use PhoenixWP\PriceLabels\Compliance\Unit_Price_Provider_Interface;
use PhoenixWP\PriceLabels\Compliance\Unit_Price_Text;
use WC_Product;

defined( 'ABSPATH' ) || exit;

/**
 * Uses WGM_Price_Per_Unit API or the gm_product_ppu shortcode.
 */
final class German_Market_Provider implements Unit_Price_Provider_Interface {

	public function get_id(): string {
		return 'german_market';
	}

	public function resolve( WC_Product $product ): ?string {
		if ( ! class_exists( \WGM_Price_Per_Unit::class ) && ! shortcode_exists( 'gm_product_ppu' ) ) {
			return null;
		}

		$from_api = $this->resolve_from_api( $product );
		if ( null !== $from_api && '' !== $from_api ) {
			return $from_api;
		}

		return $this->resolve_from_shortcode( $product );
	}

	private function resolve_from_api( WC_Product $product ): ?string {
		if ( ! class_exists( \WGM_Price_Per_Unit::class ) || ! method_exists( \WGM_Price_Per_Unit::class, 'get_price_per_unit_data' ) ) {
			return null;
		}

		$data = null;

		if ( $product->is_type( 'variation' ) && function_exists( 'wcppufv_get_price_per_unit_data' ) ) {
			$data = wcppufv_get_price_per_unit_data( $product->get_id(), $product );
		} else {
			$data = \WGM_Price_Per_Unit::get_price_per_unit_data( $product );
		}

		if ( ! is_array( $data ) ) {
			return null;
		}

		if ( isset( $data['formatted'] ) && is_string( $data['formatted'] ) && '' !== trim( $data['formatted'] ) ) {
			return Unit_Price_Text::normalize( $data['formatted'] );
		}

		if ( isset( $data['price_per_unit_formatted'] ) && is_string( $data['price_per_unit_formatted'] ) ) {
			$text = Unit_Price_Text::normalize( $data['price_per_unit_formatted'] );
			if ( '' !== $text ) {
				return $text;
			}
		}

		$mult  = isset( $data['mult'] ) ? (float) $data['mult'] : 0.0;
		$unit  = isset( $data['unit'] ) ? trim( (string) $data['unit'] ) : '';
		$price = isset( $data['price_per_unit'] ) ? (float) $data['price_per_unit'] : 0.0;

		if ( $price <= 0 && isset( $data['complete_product_quantity'] ) && $mult > 0 && '' !== $unit ) {
			$quantity = (float) $data['complete_product_quantity'];
			$display  = (float) wc_get_price_to_display( $product );

			if ( $quantity > 0 && $display > 0 ) {
				$price = ( $display / $quantity ) * $mult;
			}
		}

		if ( $price <= 0 || '' === $unit ) {
			return null;
		}

		return Unit_Price_Text::format_per_unit( $price, $mult > 0 ? $mult : 1.0, $unit );
	}

	private function resolve_from_shortcode( WC_Product $product ): ?string {
		if ( ! shortcode_exists( 'gm_product_ppu' ) ) {
			return null;
		}

		$text = do_shortcode(
			'[gm_product_ppu product_id="' . absint( $product->get_id() ) . '" markup="no"]'
		);

		$text = Unit_Price_Text::normalize( (string) $text );

		return '' !== $text ? $text : null;
	}
}
