<?php
/**
 * ShipmentTrackingDataProvider class.
 *
 * @package DhlPolska\Shipment
 */

namespace DhlPolska\Shipment;

use DhlPolska\Integration\FlexibleShipping\FlexibleShippingIntegration;
use DhlPolska\WooCommerceSettings\WooCommerceDHLPolskaSettings;
use WC_Order;

/**
 * Provides tracking data for customer-facing order views.
 */
class ShipmentTrackingDataProvider {

	/**
	 * @var WooCommerceDHLPolskaSettings
	 */
	private WooCommerceDHLPolskaSettings $settings;

	public function __construct( ?WooCommerceDHLPolskaSettings $settings = null ) {
		$this->settings = $settings ?? new WooCommerceDHLPolskaSettings();
	}

	/**
	 * @param WC_Order $order .
	 *
	 * @return array<int, array{tracking_number: string, tracking_url: string}>
	 */
	public function get_tracking_data( WC_Order $order ): array {
		if ( ! $this->settings->is_allowed_email_tracking_number() || ! function_exists( 'fs_get_order_shipments' ) ) {
			return [];
		}

		$shipments     = fs_get_order_shipments( $order->get_id(), FlexibleShippingIntegration::INTEGRATION_ID );
		$tracking_data = array_map( [ $this, 'prepare_tracking_entry' ], $shipments );

		return array_values( array_filter( $tracking_data, static fn ( $value ) => $value !== null ) );
	}

	/**
	 * @param object $shipment .
	 *
	 * @return array{tracking_number: string, tracking_url: string}|null
	 */
	private function prepare_tracking_entry( $shipment ): ?array {
		if ( ! method_exists( $shipment, 'get_tracking_number' ) || ! method_exists( $shipment, 'get_tracking_url' ) ) {
			return null;
		}

		$tracking_number = trim( (string) $shipment->get_tracking_number() );
		$tracking_url    = trim( (string) $shipment->get_tracking_url() );

		if ( '' === $tracking_number || '' === $tracking_url ) {
			return null;
		}

		return [
			'tracking_number' => $tracking_number,
			'tracking_url'    => $tracking_url,
		];
	}
}
