<?php

namespace Simplyin\Simplyin_W_Plugin\Shipping_Mapping\Integration\Dhl_Polska;

use Simplyin\Simplyin_W_Plugin\Shipping_Mapping\Integration\Abstract_Integration_Factory;
use Simplyin\Simplyin_W_Plugin\Shipping_Mapping\Integration\Integration_Factory_Interface;
use Simplyin\Simplyin_W_Plugin\Shipping_Mapping\Integration\Integration_Interface;
use WC_Shipping_Method;

class Dhl_Polska_Integration_Factory extends Abstract_Integration_Factory implements Integration_Factory_Interface {

	private const SHIPPING_METHOD_ID = 'dhl_polska_flat_rate';
	private const SERVICE_POINT = 'SERVICEPOINT';
	private const INSTANCE_SETTING_SERVICE = 'service';
	private const INSTANCE_SETTING_SERVICE_FALLBACK = 'dhl_polska_service';

	public function create( WC_Shipping_Method $method ): ?Integration_Interface {
		$method_id = $this->get_method_id_by_rate_id( $method->get_rate_id() );

		if ( ! $this->is_dhl_polska( $method_id ) ) {
			return null;
		}

		if ( ! $this->is_service_point( $method ) ) {
			return null;
		}

		return $this->create_integration_by_method_id(
			$method_id,
			$method->get_instance_id(),
			$method->get_title()
		);
	}

	private function is_dhl_polska( string $method_id ): bool {
		return $method_id === self::SHIPPING_METHOD_ID;
	}

	private function is_service_point( WC_Shipping_Method $method ): bool {
		$instance_settings = $this->get_instance_settings( $method );

		if ( $instance_settings === null ) {
			return false;
		}

		$service = $this->get_service_from_instance_settings( $instance_settings );

		return $service === self::SERVICE_POINT;
	}

	private function get_service_from_instance_settings( array $instance_settings
	): string {
		$service = '';
		if ( ! empty( $instance_settings[ self::INSTANCE_SETTING_SERVICE ] ) ) {
			$service = (string) $instance_settings[ self::INSTANCE_SETTING_SERVICE ];
		} elseif ( ! empty( $instance_settings[ self::INSTANCE_SETTING_SERVICE_FALLBACK ] ) ) {
			$service = (string) $instance_settings[ self::INSTANCE_SETTING_SERVICE_FALLBACK ];
		}

		return strtoupper( trim( $service ) );
	}

	public function create_integration_by_method_id(
		string $method_id,
		int $instance_id,
		string $title
	): ?Integration_Interface {

		return new Dhl_Polska_Parcel_Point_Integration(
			$method_id,
			$instance_id,
			$title
		);
	}
}
