<?php
/**
 * Shipment order info pieces counter.
 *
 * @package DhlPolska\Shipment
 */

namespace DhlPolska\Shipment;

/**
 * Counts EX and DR pieces for ShipmentOrderInfo.
 */
class ShipmentOrderInfoPiecesCounter {
	use UnitsConversionTrait;

	private const EX_WEIGHT_THRESHOLD = 31.5;

	/**
	 * @param ShipmentData[] $shipment_datas .
	 *
	 * @return array{number_of_ex_pieces: int, number_of_dr_pieces: int}
	 */
	public function count( array $shipment_datas ): array {
		$number_of_ex_pieces = 0;
		$number_of_dr_pieces = 0;

		foreach ( $shipment_datas as $shipment_data ) {
			foreach ( $shipment_data->get_packages() as $package ) {
				$quantity = max( 1, (int) ( $package['quantity'] ?? 1 ) );
				$weight   = $this->get_weight_in_kg( (float) ( $package['weight'] ?? 0 ) );

				if ( null === $weight || $weight <= self::EX_WEIGHT_THRESHOLD ) {
					$number_of_ex_pieces += $quantity;
					continue;
				}

				$number_of_dr_pieces += $quantity;
			}
		}

		return [
			'number_of_ex_pieces' => $number_of_ex_pieces,
			'number_of_dr_pieces' => $number_of_dr_pieces,
		];
	}
}
