<?php

namespace PostenBringCheckout\checkout\integrations\shipmenttracking;

use PostenBringCheckout\admin\bring\models\booking\MyBringBookingResponse;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Shipment Tracking integration.
 *
 * Adds Posten/Bring providers to WooCommerce Shipment Tracking and syncs
 * consignment numbers created by our booking flow.
 */
class ShipmentTrackingIntegration {
	private const PROVIDER_POSTEN     = 'Posten';
	private const PROVIDER_BRING      = 'Bring';
	private const PROVIDER_GROUP      = 'Posten Bring';
	private const POSTEN_TRACKING_URL = 'https://sporing.posten.no/sporing/%1$s';
	private const BRING_TRACKING_URL  = 'https://sporing.bring.no/sporing/%1$s';

	/**
	 * Adds Posten and Bring to the Shipment Tracking provider list.
	 *
	 * @param array $providers Registered providers.
	 *
	 * @return array
	 */
	public function add_custom_tracking_providers( array $providers ): array {
		if ( ! isset( $providers[ self::PROVIDER_GROUP ] ) || ! is_array( $providers[ self::PROVIDER_GROUP ] ) ) {
			$providers[ self::PROVIDER_GROUP ] = array();
		}

		$providers[ self::PROVIDER_GROUP ][ self::PROVIDER_POSTEN ] = self::POSTEN_TRACKING_URL;
		$providers[ self::PROVIDER_GROUP ][ self::PROVIDER_BRING ]  = self::BRING_TRACKING_URL;

		return $providers;
	}

	/**
	 * Syncs newly created bookings into WooCommerce Shipment Tracking.
	 *
	 * @param mixed $wc_order The WooCommerce order.
	 * @param array $bookings New booking responses.
	 *
	 * @return void
	 */
	public static function sync_booking_to_order_tracking( $wc_order, array $bookings ): void {
		if ( ! $wc_order || empty( $bookings ) || ! function_exists( 'wc_st_add_tracking_number' ) ) {
			return;
		}

		$provider     = self::get_tracking_provider( $wc_order );
		$date_shipped = time();

		foreach ( $bookings as $booking ) {
			if ( ! $booking instanceof MyBringBookingResponse || empty( $booking->consignmentNumber ) ) {
				continue;
			}

			wc_st_add_tracking_number( $wc_order->get_id(), $booking->consignmentNumber, $provider, $date_shipped );
		}
	}

	/**
	 * Resolves the Shipment Tracking provider from the order shipping brand.
	 *
	 * @param mixed $wc_order The WooCommerce order.
	 *
	 * @return string
	 */
	private static function get_tracking_provider( $wc_order ): string {
		$shipping_method = current( $wc_order->get_shipping_methods() );

		if ( $shipping_method && method_exists( $shipping_method, 'get_meta' ) && $shipping_method->get_meta( 'brand' ) === self::PROVIDER_POSTEN ) {
			return self::PROVIDER_POSTEN;
		}

		return self::PROVIDER_BRING;
	}
}
