<?php

namespace Simplyin\Simplyin_W_Plugin\Hooks;

use Simplyin\Simplyin_W_Plugin\Tracking_Numbers;
use WC_Order;

class Fs_Shipment {
	private const INTEGRATION_PROVIDER_MAP = array(
		'dhl'        => 'dhl',
		'dhl_polska' => 'dhl',
		'inpost'     => 'inpost',
		'easypack'   => 'inpost',
		'paczkomaty' => 'inpost',
		'dpd'        => 'dpd',
	);

	public function handle_shipment_confirmed( $flexible_shipping_shipment ) {
		$log = simplyin()
			->get_simplyin_logger();

		if ( $flexible_shipping_shipment instanceof \WPDesk_Flexible_Shipping_Shipment_Interface ) {
			$order = $flexible_shipping_shipment->get_order();

			if ( $order instanceof WC_Order ) {
				$simplyin_order_id = $order->get_meta( 'SimplyInOrderId' );
				if ( empty( $simplyin_order_id ) ) {
					return;// skip no-simplyin order
				}

				$tracking_number = (string) $flexible_shipping_shipment->get_tracking_number();
				$provider        = $this->normalize_integration_provider(
					(string) $flexible_shipping_shipment->get_integration()
				);

				if ( '' === $tracking_number ) {
					return;
				}

				( new Tracking_Numbers() )->update_tracking_numbers(
					array( $tracking_number ),
					$provider,
					$order
				);

				$log->log_if_wpdebug_on(
					sprintf(
						'[Fs_Shipment] [handle_shipment_confirmed] action hooks done [%s]',
						wp_json_encode(
							array(
								'class passed to callback' => get_class( $flexible_shipping_shipment ),
								'order_id'                 => $order->get_id(),
							)
						)
					)
				);

			} else {
				$log->log_if_wpdebug_on(
					sprintf(
						'[Fs_Shipment] [handle_shipment_confirmed] Failure [%s]',
						wp_json_encode(
							array(
								'reason' => 'order is not wc_order',
								'order'  => $order,

							)
						)
					)
				);
			}
		} else {
			$log->log_if_wpdebug_on(
				sprintf(
					'[Fs_Shipment] [handle_shipment_confirmed] Failure [%s]',
					wp_json_encode(
						array(
							'reason'    => 'invalid type of passed flexible_shipping_shipment',
							'classname' => get_class( $flexible_shipping_shipment ),

						)
					)
				)
			);
		}
	}

	private function normalize_integration_provider( string $integration ): string {
		return self::INTEGRATION_PROVIDER_MAP[ $integration ] ?? $integration;
	}
}
