<?php

namespace Prodigy\Includes\Frontend\Traits;

use Prodigy\Includes\Content\Prodigy_Product_Parser;

defined( 'ABSPATH' ) || exit;

/**
 * Requires the using class to expose a `Prodigy_Request_Maker $request_maker` property.
 */
trait Prodigy_Mlc_Charge_Trait {

	/**
	 * @param array $logos
	 * @param int   $product_id
	 *
	 * @return array Logos with extra-charge-amount populated from Multiple Logo Charge settings where missing.
	 */
	protected function apply_mlc_extra_charges_to_logos( array $logos, int $product_id ): array {
		if ( empty( $logos ) || $product_id <= 0 ) {
			return $logos;
		}

		$product_data = $this->request_maker->do_product_request( $product_id );
		if ( empty( $product_data ) ) {
			return $logos;
		}

		$product_parser = new Prodigy_Product_Parser( $product_data );
		$mlc_settings   = $product_parser->get_multiple_logo_charge_settings();

		if ( empty( $mlc_settings ) || empty( $mlc_settings['enabled'] ) ) {
			return $logos;
		}

		$mlc_mode_raw          = strtolower( trim( (string) ( $mlc_settings['mode'] ?? '' ) ) );
		$mlc_mode_aliases      = array(
			'additional_per_location'             => 'additional_per_location',
			'additional_per_logo_location'        => 'additional_per_location',
			'additional_price_per_logo_location'  => 'additional_per_location',
			'custom_per_location'                 => 'custom_per_location',
			'custom_per_logo_location'            => 'custom_per_location',
			'custom_price_per_logo_location'      => 'custom_per_location',
			'custom_price_for_each_logo_location' => 'custom_per_location',
		);
		$mlc_mode              = $mlc_mode_aliases[ $mlc_mode_raw ] ?? $mlc_mode_raw;
		$mlc_custom_amounts    = $mlc_settings['custom-amounts'] ?? array();
		$mlc_additional_amount = (float) ( $mlc_settings['additional-amount'] ?? 0 );

		$crl_enabled = ! empty( $mlc_settings['charge-required-location'] );

		$slot_index = 0;
		foreach ( $logos as $key => $logo ) {
			$is_location_required = ! empty( $logo['location']['required'] );

			if ( $is_location_required && ! $crl_enabled ) {
				$logos[ $key ]['extra-charge-amount']      = 0.0;
				$logos[ $key ]['suppress-location-charge'] = true;
				++$slot_index;
				continue;
			}

			if ( (float) ( $logo['extra-charge-amount'] ?? 0 ) === 0.0 ) {
				if ( 'custom_per_location' === $mlc_mode && ! empty( $mlc_custom_amounts ) ) {
					$idx                                  = isset( $mlc_custom_amounts[ $slot_index ] ) ? $slot_index : count( $mlc_custom_amounts ) - 1;
					$entry                                = $mlc_custom_amounts[ $idx ];
					$logos[ $key ]['extra-charge-amount'] = is_array( $entry ) && isset( $entry['amount'] )
						? (float) $entry['amount']
						: (float) $entry;
				} elseif ( 'additional_per_location' === $mlc_mode && $slot_index > 0 ) {
					$logos[ $key ]['extra-charge-amount'] = $mlc_additional_amount;
				}
			}
			++$slot_index;
		}

		return $logos;
	}
}
