<?php

use FS\InPost\PickupPoints\PickupPointsManager;
use FS\InPost\Shipment\LabelSettingsFactory;

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

require_once __DIR__ . '/shipX/class-api-shipx-status-translation.php';

if ( class_exists( 'WPDesk_Flexible_Shipping_Shipment' ) ) {
	/**
	 * Class WPDesk_Flexible_Shipping_Shipment_Paczkomaty
	 */
	class WPDesk_Flexible_Shipping_Shipment_Paczkomaty extends WPDesk_Flexible_Shipping_Shipment implements WPDesk_Flexible_Shipping_Shipment_Interface {

		/**
		 * Meta field names
		 */
		const META_KEY_PACZKOMATY_USLUGA            = '_paczkomaty_usluga';
		const META_PACZKOMAT_ID                     = '_paczkomat_id';
		const META_PACZKOMAT_SENDING_METHOD         = '_paczkomat_sending_method';
		const META_PACZKOMAT_WIDTH                  = '_paczkomat_width';
		const META_PACZKOMAT_HEIGHT                 = '_paczkomat_height';
		const META_PACZKOMAT_LENGTH                 = '_paczkomat_length';
		const META_PACZKOMAT_DROPOFF_PARCEL_MACHINE = '_paczkomat_dropoff_parcel_machine';
		const META_PACZKOMAT_CUSTOMER_REF           = '_paczkomat_customer_ref';
		const META_PACZKOMAT_COD_AMOUNT             = '_paczkomat_cod_amount';
		const META_PACZKOMAT_WEIGHT                 = '_paczkomat_weight';
		const META_PACZKOMAT_COD                    = '_paczkomat_cod';
		const META_FLEXIBLE_SHIPPING_STATUS         = '_flexible_shipping_status';
		const META_PACZKOMAT_DROPOFF_POP            = '_paczkomat_dropoff_pop';
		const META_PACZKOMAT_DROPOFF_DISPATCH_POINT = '_paczkomat_dropoff_dispatch_point';
		const META_PACZKOMAT_UBEZPIECZENIE          = '_paczkomat_ubezpieczenie';
		const META_PACZKOMAT_UBEZPIECZENIE_AMOUNT   = '_paczkomat_ubezpieczenie_amount';
		const META_PACZKOMAT_SIZE                   = '_paczkomat_size';
		const META_PACZKOMAT_PUNKT_NADANIA          = '_paczkomat_punkt_nadania';
		const META_PACZKOMAT_SHIPMENT_ID            = '_paczkomat_shipment_id';

		const FILTER_SHIPMENT_DATA = 'woocommerce_paczkomaty_inpost_shipment_data';

		const INPOST_LOCKER_STANDARD = 'inpost_locker_standard';
		const INPOST_LOCKER_ALLEGRO  = 'inpost_locker_allegro';

		const SERVICE_KURIER     = 'kurier';
		const SERVICE_POLECONY   = 'polecony';
		const SERVICE_PACZKOMATY = 'paczkomaty';

		const DELIVERY_FIELD_ID       = 'delivery_point_id';
		const DELIVERY_FIELD_NAME     = 'delivery_point_name';
		const DELIVERY_FIELD_ADDRESS  = 'delivery_point_address';
		const DELIVERY_FIELD_POSTCODE = 'delivery_point_postcode';
		const DELIVERY_FIELD_CITY     = 'delivery_point_city';

		/**
		 * @var WPDesk_Paczkomaty_ShipX
		 */
		private $ship_x = null;

		/**
		 * @var WPDesk_Paczkomaty_Plugin
		 */
		private $plugin;

		/**
		 * @var WPDesk_Paczkomaty_Plugin
		 */
		public static $_plugin;

		/**
		 * @var bool|WPDesk_Paczkomaty_Logger
		 */
		private $logger;

		/** @var WPDesk_Flexible_Shipping_Order_Auto_Complete */
		private $order_auto_complete_functionality;

		/**
		 * @var array
		 */
		private $packege_templates = [
			'A' => 'small',
			'B' => 'medium',
			'C' => 'large',
		];

		/**
		 * Shipment options.
		 *
		 * @var WPDesk_Paczkomaty_Additional_Service[]
		 */
		private $shipment_options = [];

		/**
		 * @var PickupPointsManager
		 */
		public static $pickup_points_manager;

		/**
		 * WPDesk_Flexible_Shipping_Shipment_Paczkomaty constructor.
		 *
		 * @param               $shipment
		 * @param WC_Order|null $order
		 */
		public function __construct( $shipment, WC_Order $order = null ) {
			parent::__construct( $shipment, $order );

			$this->shipment_options[] = new WPDesk_Paczkomaty_End_Of_Week_Collection( $this );
			$this->shipment_options[] = new WPDesk_Paczkomaty_Additional_Service_Saturday( $this );
			$this->shipment_options[] = new WPDesk_Paczkomaty_Additional_Service_SMS_Notification( $this );
			$this->shipment_options[] = new WPDesk_Paczkomaty_Additional_Service_Email_Notification( $this );

			$this->plugin = self::$_plugin;
			$this->logger = $this->get_logger();

			$this->order_auto_complete_functionality = new WPDesk_Flexible_Shipping_Order_Auto_Complete( $this );

			$this->hooks();
		}

		/**
		 * Hook various behaviors to filters and actions.
		 */
		public function hooks() {
			add_action( 'admin_enqueue_scripts', [ $this, 'i18n_js_support' ] );
		}

		public function i18n_js_support() {
			$current_screen = get_current_screen();

			if ( 'shop_order' == $current_screen->id && isset( $_GET['action'] ) && 'edit' == $_GET['action'] ) {
				wp_register_script( 'i18n_support', trailingslashit( plugins_url( '/', dirname( __FILE__ ) ) ) . 'assets/js/i18n-support.js', [ 'wp-i18n' ], false, true );
				wp_enqueue_script( 'i18n_support' );

				wp_set_script_translations( 'i18n_support', 'woocommerce-paczkomaty-inpost' );
			}
		}

		/**
		 * @return bool|WPDesk_Paczkomaty_Logger
		 */
		public function get_logger() {
			return $this->plugin->get_logger();
		}

		/**
		 * .
		 * @param array $fs_method .
		 * @param array $package   .
		 */
		public function checkout( array $fs_method, $package ) {
			$checkout = new WPDesk_Flexible_Shipping_Shipment_Paczkomaty_Checkout(
				$this,
				$this->get_paczkomaty_shipping_method(),
				$this->shipment_options,
				$fs_method,
				$package,
				self::$pickup_points_manager
			);
			$checkout->process_checkout( $_POST ); // phpcs:ignore.
		}

		/**
		 * Tries to get unavailability reasons from offer
		 *
		 * @param stdClass|mixed $offer
		 *
		 * @return string
		 * @see https://docs.inpost24.com/pages/viewpage.action?pageId=983186
		 */
		private function get_unavability_reasons_message_from_offer( $offer ) {
			if ( $offer instanceof stdClass ) {
				if ( is_array( $offer->unavailability_reasons ) ) {
					$message_array = array_reduce( $offer->unavailability_reasons, function ( array $carry, $reason ) {
						if ( $reason instanceof stdClass ) {
							if ( isset( $reason->message ) ) {
								$carry[] = $reason->message;
							} elseif ( isset( $reason->receiver ) ) {
								$carry[] = $reason->receiver;
							}
						}

						return $carry;
					}, [] );
				}

				return implode( ', ', $message_array );
			}

			return '';
		}

		/**
		 * @return string
		 */
		public function order_metabox_content() {
			$status_translator = new WPDesk_Paczkomaty_ShipX_Status_Translation( $this->get_shipX(), get_locale() );

			$args = [];

			$paczkomat_shipment                           = $this->get_meta( '_paczkomat_shipment', new stdClass() );
			$args['paczkomat_shipment']                   = $paczkomat_shipment;
			$args['shipment_data_send']                   = $this->get_meta( '_shipment_data_send', '' );
			$args['paczkomaty_usluga']                    = $this->get_meta( '_paczkomaty_usluga' );
			$args['paczkomat_id']                         = $this->get_meta( '_paczkomat_id' );
			$args['paczkomat_shipx']                      = $this->get_meta( '_paczkomat_shipx' );
			$args['paczkomat_shipment']                   = $this->get_meta( '_paczkomat_shipment' );
			$args['paczkomat_shipment_status']            = $this->get_meta( '_paczkomat_shipment_status' );
			$args['paczkomat_shipment_status_translated'] = $status_translator->translate_status( $args['paczkomat_shipment_status'] );
			$args['paczkomat_size']                       = $this->get_meta( self::META_PACZKOMAT_SIZE );
			$args['paczkomat_width']                      = $this->get_meta( '_paczkomat_width' );
			$args['paczkomat_height']                     = $this->get_meta( '_paczkomat_height' );
			$args['paczkomat_length']                     = $this->get_meta( '_paczkomat_length' );
			$args['paczkomat_weight']                     = $this->get_meta( '_paczkomat_weight' );
			$args['phone']                                = wpdesk_get_order_meta( $this->get_order(), '_billing_phone', true );
			$args['paczkomat_packcode']                   = $this->get_meta( '_paczkomat_packcode' );
			$args['paczkomat_ubezpieczenie']              = $this->get_meta( self::META_PACZKOMAT_UBEZPIECZENIE );
			$args['paczkomat_ubezpieczenie_amount']       = $this->get_meta( self::META_PACZKOMAT_UBEZPIECZENIE_AMOUNT );
			$args['paczkomat_cod']                        = $this->get_meta( '_paczkomat_cod' );
			$args['paczkomat_cod_amount']                 = $this->get_meta( '_paczkomat_cod_amount' );
			$args['paczkomat_how_to_give']                = $this->get_meta( '_paczkomat_how_to_give' );
			$args['paczkomat_error']                      = $this->get_meta( '_paczkomat_error' );
			$args['post_id']                              = wpdesk_get_order_id( $this->get_order() );
			$args['label_url']                            = $this->get_label_url();
			$args['status']                               = $this->get_status();
			$args['create_shipment_allowed']              = 'shop_subscription' !== $this->get_order()->get_type();
			$args['customer_ref_available']               = 'shop_subscription' !== $this->get_order()->get_type();

			foreach ( $this->shipment_options as $shipment_option ) {
				$args = $shipment_option->prepare_metabox_field_values( $args );
			}

			$paczkomaty_shipping_method = $this->get_paczkomaty_shipping_method();

			$settings                           = $paczkomaty_shipping_method->settings;
			$args['paczkomaty_shipping_method'] = $paczkomaty_shipping_method;

			if ( $this->get_meta( '_paczkomat_sending_method', '' ) != '' ) {
				$args['paczkomat_sending_method'] = $this->get_meta( '_paczkomat_sending_method' );
			} else {
				$args['paczkomat_sending_method'] = $paczkomaty_shipping_method->get_option( 'sending_method', '' );
			}

			$args['select2'] = true;

			if ( $args['paczkomat_ubezpieczenie_amount'] == '' ) {
				$args['paczkomat_ubezpieczenie_amount'] = $this->get_order()->get_total();
			}
			if ( $args['paczkomat_cod_amount'] == '' ) {
				$args['paczkomat_cod_amount'] = $this->get_order()->get_total();
			}

			$args['paczkomat_customer_ref'] = $this->get_meta( '_paczkomat_customer_ref' );

			if ( $args['paczkomat_customer_ref'] == '' ) {
				$args['paczkomat_customer_ref'] = sprintf( __( 'Zamówienie %s', 'woocommerce-paczkomaty-inpost' ), $this->get_order()->get_order_number() );
			} else {
				$args['paczkomat_customer_ref'] = sprintf( $args['paczkomat_customer_ref'], $this->get_order()->get_order_number() );
			}

			$args['paczkomat_punkt_nadania'] = $this->get_meta( self::META_PACZKOMAT_PUNKT_NADANIA, true );

			$args['punkty_nadania'] = apply_filters( 'paczkomaty_shipping_method_pickup_points', [ $args['paczkomat_punkt_nadania'] => $args['paczkomat_punkt_nadania'] . ' ' . __( '(Błąd ładowania listy punktów nadania!)', 'woocommerce-paczkomaty-inpost' ) ] );

			if ( ! empty( $paczkomat_shipment->offers ) && is_array( $paczkomat_shipment->offers ) ) {
				foreach ( $paczkomat_shipment->offers as $offer ) {
					if ( $offer->status == 'unavailable' ) {
						if ( empty( $args['paczkomat_offers_message'] ) ) {
							$args['paczkomat_offers_message'] = '';
						} else {
							$args['paczkomat_offers_message'] .= '<br/>';
						}
						$args['paczkomat_offers_message'] .= $this->get_unavability_reasons_message_from_offer( $offer );
					}
				}
			}

			$args['shipX'] = true;
			if ( $this->get_meta( '_paczkomaty_usluga' ) == 'paczkomaty' && $paczkomaty_shipping_method->get_parcel_lockers_api() == 'XML' ) {
				$args['shipX'] = false;
			}

			$id = $this->get_id();

			$label_avaliable = $this->label_avaliable();

			$editable = true;
			if ( $this->get_status() != 'fs-new' && $this->get_status() != 'fs-failed' ) {
				$editable = false;
			}

			$allegro = false;

			if ( wpdesk_get_order_meta( $this->get_order(), '_allegro_journal_deal', true ) != '' ) {
				$allegro = true;
			}

			ob_start();

			$echo = false;

			include( 'views/order-metabox-content.php' );

			$content = ob_get_contents();

			ob_end_clean();

			return $content;

		}

		/**
		 *
		 */
		public function order_metabox() {
			echo $this->order_metabox_content();
		}

		/**
		 * @return string|void
		 */
		public function get_order_metabox_title() {
			return __( 'InPost', 'woocommerce-paczkomaty-inpost' );
		}

		/**
		 * @param string $action
		 * @param array  $data
		 *
		 * @return array|string|void
		 * @throws Exception
		 */
		public function ajax_request( $action, $data ) {
			if ( $action == 'save' ) {
				$this->save_ajax_data( $data );
				$this->save();
			} elseif ( $action == 'send' ) {
				$this->save_ajax_data( $data );
				$this->api_create();
				$this->save();
			} elseif ( $action == 'refresh' ) {
				$this->api_refresh();
				$this->show_exception_message_when_pack_code_is_missing();
			} elseif ( $action == 'cancel' ) {
				$this->api_cancel();

				return [
					'content' => $this->order_metabox_content(),
					'message' => __( 'Przesyłka została anulowana', 'woocommerce-paczkomaty-inpost' ),
				];
			} else {
				throw new Exception( __( 'Nieznana akcja: "' . $action . '"', 'woocommerce-paczkomaty-inpost' ) );
			}

			return $this->order_metabox_content();
		}

		/**
		 * Check if parcel pack code is generated
		 * '_paczkomat_packcode' => '602236056943300010795018' || '_paczkomat_packcode' => null
		 *
		 * @return bool
		 */
		private function check_if_parcel_pack_code_is_generated() {
			return null !== $this->get_meta( '_paczkomat_packcode' );
		}

		/**
		 * Throw exception message when parcel pack code is not generated
		 *
		 * @throws Exception
		 */
		private function show_exception_message_when_pack_code_is_missing() {
			if ( false === $this->check_if_parcel_pack_code_is_generated() ) {
				throw new Exception( __(
					'Nie można wygenerować etykiety nadawczej dla przesyłki ze statusem Oferta wybrana. Jeżeli korzystasz z konta
					prepaid upewnij się, że znajdują się na nim wystarczające środki do nadania przesyłki.
					Jeśli posiadasz podpisaną umowę z InPost, a błąd nadal występuje, skontaktuj się ze swoim opiekunem InPost.
				', 'woocommerce-paczkomaty-inpost'
				) );
			}
		}

		/**
		 * Use when shipments is confirmed to notify all additional functionalities.
		 */
		public function set_info_shipment_is_confirmed() {
			do_action( 'flexible_shipping_shipment_confirmed', $this );
			$this->order_auto_complete_functionality->handle_order();
		}

		/**
		 * @throws Exception
		 * @throws WPDesk_Paczkomaty_ShipX_Exception
		 */
		public function api_cancel() {
			if ( $this->get_meta( '_paczkomat_shipx', '0' ) == '1' ) {
				$shipment_id = $this->get_meta( self::META_PACZKOMAT_SHIPMENT_ID );
				$shipX       = $this->get_shipX();
				$shipX->delete_shipment( $shipment_id );
				$this->delete_meta( '_paczkomat_shipment' );
				$this->delete_meta( self::META_PACZKOMAT_SHIPMENT_ID );
				$this->delete_meta( '_paczkomat_packcode' );
				$this->delete_meta( '_paczkomat_shipment_status' );
				$this->update_status( 'fs-new' );
				$this->save();
				do_action( 'flexible_shipping_shipment_canceled', $this );
			}
		}

		/**
		 * @throws Exception
		 * @throws WPDesk_Paczkomaty_ShipX_Exception
		 */
		public function api_refresh() {
			if ( $this->get_meta( '_paczkomat_shipx', '0' ) == '1' ) {
				$shipment_id = $this->get_meta( self::META_PACZKOMAT_SHIPMENT_ID );
				$shipX       = $this->get_shipX();
				$shipment    = $shipX->get_shipment( $shipment_id );
				$this->set_meta( '_paczkomat_shipment', $shipment );
				$this->set_meta( self::META_PACZKOMAT_SHIPMENT_ID, $shipment->id );
				$this->set_meta( '_paczkomat_shipment_status', $shipment->status );
				$this->set_meta( '_paczkomat_packcode', $shipment->tracking_number );
				$trigger_hook = false;
				if ( $this->is_inpost_status_considered_as_confirmed( $shipment->status ) ) {
					if ( $this->get_status() !== 'fs-confirmed' ) {
						$this->add_order_note_tracking_id();
						$this->update_status( 'fs-confirmed' );
						$trigger_hook = true;
					}
				}
				$this->save();
				if ( $trigger_hook ) {
					$this->set_info_shipment_is_confirmed();
				}
			}
		}

		/**
		 * Should InPost shipment status be understood as FS fs-confirmed?
		 *
		 * @param string $status Inpost shipment status
		 *
		 * @return bool
		 */
		private function is_inpost_status_considered_as_confirmed( $status ) {
			return ! in_array( $status, [ 'created', 'offers_prepared', 'offer_selected', 'other' ], true );
		}

		/**
		 * @param $data
		 *
		 * @throws Exception
		 */
		public function save_ajax_data( $data ) {
			if ( isset( $data['paczkomat_usluga'] ) ) {
				$this->set_meta( '_paczkomaty_usluga', $data['paczkomat_usluga'] );
			} else {
				throw new Exception( __( 'Brak usługi!', 'woocommerce-paczkomaty-inpost' ) );
			}
			if ( isset( $data['paczkomat_id'] ) ) {
				$this->set_meta( '_paczkomat_id', $data['paczkomat_id'] );

				if ( ! empty( $data['paczkomat_id'] ) ) {
					$point = self::$pickup_points_manager->get_point_details( $data['paczkomat_id'] );

					$this->set_meta( self::DELIVERY_FIELD_ID, $point->get_point_id() );
					$this->set_meta( self::DELIVERY_FIELD_NAME, $point->get_name() );
					$this->set_meta( self::DELIVERY_FIELD_ADDRESS, $point->get_address_1() );
					$this->set_meta( self::DELIVERY_FIELD_POSTCODE, $point->get_zipcode() );
					$this->set_meta( self::DELIVERY_FIELD_CITY, $point->get_city() );
				}
			} else {
				throw new Exception( __( 'Brak identyfikatora paczkomatu!', 'woocommerce-paczkomaty-inpost' ) );
			}
			if ( isset( $data['paczkomat_size'] ) ) {
				$this->set_meta( self::META_PACZKOMAT_SIZE, $data['paczkomat_size'] );
			} else {
				throw new Exception( __( 'Brak rozmiaru przesyłki!', 'woocommerce-paczkomaty-inpost' ) );
			}
			if ( isset( $data['paczkomat_width'] ) ) {
				$this->set_meta( '_paczkomat_width', $data['paczkomat_width'] );
			} else {
				throw new Exception( __( 'Brak szrokości przesyłki!', 'woocommerce-paczkomaty-inpost' ) );
			}
			if ( isset( $data['paczkomat_height'] ) ) {
				$this->set_meta( '_paczkomat_height', $data['paczkomat_height'] );
			} else {
				throw new Exception( __( 'Brak wysokości przesyłki!', 'woocommerce-paczkomaty-inpost' ) );
			}
			if ( isset( $data['paczkomat_length'] ) ) {
				$this->set_meta( '_paczkomat_length', $data['paczkomat_length'] );
			} else {
				throw new Exception( __( 'Brak długości przesyłki przesyłki!', 'woocommerce-paczkomaty-inpost' ) );
			}
			if ( isset( $data['paczkomat_weight'] ) ) {
				$this->set_meta( '_paczkomat_weight', $data['paczkomat_weight'] );
			} else {
				throw new Exception( __( 'Brak wagi przesyłki!', 'woocommerce-paczkomaty-inpost' ) );
			}
			if ( isset( $data['paczkomat_sending_method'] ) ) {
				$this->set_meta( '_paczkomat_sending_method', $data['paczkomat_sending_method'] );
			} else {
				throw new Exception( __( 'Brak sposobu nadania!', 'woocommerce-paczkomaty-inpost' ) );
			}
			if ( isset( $data['paczkomat_customer_ref'] ) ) {
				$this->set_meta( '_paczkomat_customer_ref', $data['paczkomat_customer_ref'] );
			} else {
				if ( $this->get_order()->get_type() !== 'shop_subscription' ) {
					throw new Exception( __( 'Brak numeru referencyjnego!', 'woocommerce-paczkomaty-inpost' ) );
				}
			}
			if ( isset( $data['paczkomat_ubezpieczenie'] ) ) {
				$this->set_meta( self::META_PACZKOMAT_UBEZPIECZENIE, $data['paczkomat_ubezpieczenie'] );
			} else {
				$this->set_meta( self::META_PACZKOMAT_UBEZPIECZENIE, 0 );
			}
			if ( isset( $data['paczkomat_ubezpieczenie_amount'] ) ) {
				$this->set_meta( self::META_PACZKOMAT_UBEZPIECZENIE_AMOUNT, $data['paczkomat_ubezpieczenie_amount'] );
			} else {
				$this->set_meta( self::META_PACZKOMAT_UBEZPIECZENIE_AMOUNT, '' );
			}
			if ( isset( $data['paczkomat_cod'] ) ) {
				$this->set_meta( '_paczkomat_cod', $data['paczkomat_cod'] );
			} else {
				$this->set_meta( '_paczkomat_cod', 0 );
			}
			if ( isset( $data['paczkomat_cod_amount'] ) ) {
				$this->set_meta( '_paczkomat_cod_amount', $data['paczkomat_cod_amount'] );
			} else {
				$this->set_meta( '_paczkomat_cod_amount', '' );
			}
			foreach ( $this->shipment_options as $shipment_option ) {
				$shipment_option->save_ajax_data( $data );
			}


		}

		/**
		 * @return null|string
		 */
		public function get_error_message() {
			return $this->get_meta( '_paczkomat_error' );
		}

		/**
		 * @return array|mixed|null|string
		 */
		public function get_tracking_number() {
			return $this->get_meta( '_paczkomat_packcode' );
		}

		/**
		 * @return string
		 */
		public function get_tracking_url() {
			$tracking_number = $this->get_tracking_number();
			if ( ! empty( $tracking_number ) ) {
				return 'https://inpost.pl/pl/pomoc/znajdz-przesylke?parcel=' . $this->get_tracking_number();
			}

			return '';
		}

		/**
		 * Get InPost service.
		 *
		 * @return string
		 */
		public function get_inpost_service() {
			return $this->get_meta( '_paczkomaty_usluga', '' );
		}

		/**
		 * @throws Exception
		 */
		public function api_create() {
			$paczkomaty_usluga = $this->get_meta( '_paczkomaty_usluga', '' );
			if ( $this->get_status() != 'fs-new' && $this->get_status() != 'fs-failed' ) {
				throw new Exception( __( 'Przesyłka została już utworzona.', 'woocommerce-paczkomaty-inpost' ) );
			}

			$paczkomaty_shipping_method = $this->get_paczkomaty_shipping_method();

			if ( $paczkomaty_usluga == 'paczkomaty' || $paczkomaty_usluga == 'allegro_paczkomaty' ) {
				$allegro = false;
				if ( $paczkomaty_usluga == 'allegro_paczkomaty' ) {
					$allegro = true;
				}
				if ( $paczkomaty_shipping_method->get_parcel_lockers_api() == 'XML' ) {
					$this->api_create_paczkomaty( $allegro );
				} else {
					$this->api_create_shipX( $allegro );
				}
			} elseif ( $paczkomaty_usluga == 'polecony' || $paczkomaty_usluga == 'allegro_polecony' ) {
				$allegro = false;
				if ( $paczkomaty_usluga == 'allegro_polecony' ) {
					$allegro = true;
				}
				if ( $paczkomaty_shipping_method->get_parcel_lockers_api() == 'XML' ) {
					$this->api_create_polecony( $allegro );
				} else {
					$this->api_create_shipX( $allegro );
				}
			} elseif ( $paczkomaty_usluga == self::SERVICE_KURIER || $paczkomaty_usluga == 'allegro_kurier' ) {
				$allegro = false;
				if ( $paczkomaty_usluga == 'allegro_kurier' ) {
					$allegro = true;
				}
				$this->api_create_shipX( $allegro );
			} else {
				throw new Exception( sprintf( __( 'Nieznana usługa: "%s"!', 'woocommerce-paczkomaty-inpost' ), $paczkomaty_usluga ) );
			}
		}

		/**
		 * @return array
		 * @throws Exception
		 */
		public function get_label() {
			if ( ! $this->label_avaliable() ) {
				throw new Exception( sprintf( __( 'Etykieta niedostępna dla statusu ', 'woocommerce-paczkomaty-inpost' ), $this->get_status() ) );
			}

			return $this->api_get_label();
		}

		/**
		 * @return mixed|void
		 */
		public function get_after_order_table() {
			if ( $this->get_meta( '_paczkomaty_usluga', '' ) == 'paczkomaty' ) {
				$args              = [ 'paczkomat_id' => $this->get_meta( '_paczkomat_id' ) ];
				$paczkomaty        = apply_filters( 'paczkomaty_shipping_method_admin_machines', [ $args['paczkomat_id'] => $args['paczkomat_id'] ] );
				$args['paczkomat'] = $paczkomaty[ $args['paczkomat_id'] ];
				echo $this->plugin->load_template( 'order-items-table', '', $args );
			}
			if ( $this->get_tracking_url() != '' ) {
				$args['tracking_url']    = $this->get_tracking_url();
				$args['tracking_number'] = $this->get_tracking_number();
				echo $this->plugin->load_template( 'order-items-table-tracking', '', $args );
			}
		}

		/**
		 * @return mixed|void
		 */
		public function get_email_after_order_table() {
			if ( $this->get_meta( '_paczkomaty_usluga', '' ) == 'paczkomaty' ) {
				$args              = [ 'paczkomat_id' => $this->get_meta( '_paczkomat_id' ) ];
				$paczkomaty        = apply_filters( 'paczkomaty_shipping_method_admin_machines', [ $args['paczkomat_id'] => $args['paczkomat_id'] ] );
				$args['paczkomat'] = '';
				if ( isset( $args['paczkomat_id'] ) && isset( $paczkomaty[ $args['paczkomat_id'] ] ) ) {
					$args['paczkomat'] = $paczkomaty[ $args['paczkomat_id'] ];
				}
				echo $this->plugin->load_template( 'order-items-table', '', $args );
			}
			if ( $this->get_tracking_url() != '' ) {
				$args['tracking_url']    = $this->get_tracking_url();
				$args['tracking_number'] = $this->get_tracking_number();
				echo $this->plugin->load_template( 'order-items-table-tracking', '', $args );
			}
		}

		/**
		 * @return array
		 * @throws Exception
		 * @throws WPDesk_Paczkomaty_ShipX_Exception
		 */
		public function api_get_label() {
			$paczkomaty_shipping_method = $this->get_paczkomaty_shipping_method();

			$label_settings = ( new LabelSettingsFactory( $paczkomaty_shipping_method ) )->get_settings();

			$label_data = [
				'label_format' => $label_settings->get_extension(),
				'content'      => null,
				'file_name'    => 'inpost_' . $this->get_tracking_number() . '.' . $label_settings->get_extension(),
			];

			$paczkomat_shipx = $this->get_meta( '_paczkomat_shipx', '' );
			if ( $paczkomat_shipx == '' ) {
				$packcode = $this->get_meta( '_paczkomat_packcode', true );
				if ( ! empty( $packcode ) ) {
					if ( $label_data['content'] = inpost_get_sticker( $paczkomaty_shipping_method->get_option( 'email', '' ), $paczkomaty_shipping_method->get_option( 'password', '' ), $packcode, $label_type, $label_format ) ) {
						if ( is_array( $label_data['content'] ) && isset( $label_data['content']['error'] ) ) {
							throw new Exception( __( "Error: " . $label_data['content']['error']['message'], 'woocommerce-paczkomaty-inpost' ) );
						}
					} else {
						throw new Exception( __( 'Błąd: Nie udało się wygenerować etykiety', 'woocommerce-paczkomaty-inpost' ) );
					}
				} else {
					throw new Exception( __( 'Błąd: Niepoprawny numer paczki', 'woocommerce-paczkomaty-inpost' ) );
				}
			} else {
				$shipment_id = $this->get_meta( self::META_PACZKOMAT_SHIPMENT_ID );
				if ( ! empty( $shipment_id ) ) {
					$shipX                 = $this->get_shipX();
					$label_data['content'] = $shipX->get_shipments_labels( $shipment_id, $label_settings->get_format(), $label_settings->get_type() );
				}
			}

			return $label_data;
		}

		/**
		 * @param bool $allegro
		 *
		 * @throws Exception
		 */
		private function api_create_paczkomaty( $allegro = false ) {

			$paczkomaty_shipping_method = $this->get_paczkomaty_shipping_method();

			$order = $this->get_order();

			$packData                   = [];
			$packData['senderEmail']    = $paczkomaty_shipping_method->get_option( 'email', '' );
			$packData['boxMachineName'] = $this->get_meta( '_paczkomat_id' );
			$packData['adreseeEmail']   = wpdesk_get_order_meta( $order, '_billing_email', true );
			$packData['phoneNum']       = $this->format_phone_number( wpdesk_get_order_meta( $order, '_billing_phone', true ) );
			$packData['customerRef']    = $this->get_meta( '_paczkomat_customer_ref' );
			if ( $this->get_meta( self::META_PACZKOMAT_UBEZPIECZENIE, '0' ) == '1' ) {
				$packData['insuranceAmount'] = $this->get_meta( self::META_PACZKOMAT_UBEZPIECZENIE_AMOUNT );
			}
			if ( $this->get_meta( '_paczkomat_cod', '0' ) == '1' ) {
				$packData['onDeliveryAmount'] = $this->get_meta( '_paczkomat_cod_amount' );
			}

			$selfSend = 0;
			if ( $this->get_meta( '_paczkomat_sending_method', '' ) == 'parcel_locker'
			     || $this->get_meta( '_paczkomat_sending_method', '' ) == 'pop'
			) {
				$selfSend = 1;
			} else {
				$selfSend = 0;
			}

			$packData['packType'] = $this->get_meta( self::META_PACZKOMAT_SIZE );

			if ( $allegro ) {
				$_allegro_journal_deal  = wpdesk_get_order_meta( $order, '_allegro_journal_deal', true );
				$_allegro_tansaction_id = wpdesk_get_order_meta( $order, '_allegro_tansaction_id', true );
				if ( $_allegro_journal_deal != '' && $_allegro_tansaction_id != '' ) {
					$packData['allegro']                  = [];
					$packData['allegro']['userId']        = $_allegro_journal_deal->dealSellerId;
					$packData['allegro']['transactionId'] = $_allegro_tansaction_id;
				}
			}
			$response = inpost_send_packs( $paczkomaty_shipping_method->get_option( 'email', '' ), $paczkomaty_shipping_method->get_option( 'password', '' ), [ $packData ], 1, $selfSend );

			if ( ! empty( $response[0]['error_key'] ) || ! empty( $response[0]['error_message'] ) ) {
				$this->set_meta( "_paczkomat_error", $response[0]['error_message'] );
				$this->update_status( 'fs-failed' );
				$this->save();
				throw new Exception( $response[0]['error_message'] );
			} elseif ( ! empty( $response['error'] ) ) {
				$this->set_meta( "_paczkomat_error", $response['error']['message'] );
				$this->update_status( 'fs-failed' );
				$this->save();
				throw new Exception( $response['error']['message'] );
			} elseif ( isset( $response[0]['packcode'] ) ) {
				//save in order info
				$this->set_meta( "_paczkomat_packcode", $response[0]['packcode'] );
				$this->delete_meta( '_paczkomat_error' );
				$this->update_status( 'fs-confirmed' );
				$this->save();
				$this->add_order_note_tracking_id();
				$this->set_info_shipment_is_confirmed();
			} else {
				$this->set_meta( "_paczkomat_error", __( 'Wystąpił błąd podczas przetwarzania żądania.', 'woocommerce-paczkomaty-inpost' ) );
				$this->update_status( 'fs-failed' );
				$this->save();
				throw new Exception( __( 'Wystąpił błąd podczas przetwarzania żądania.', 'woocommerce-paczkomaty-inpost' ) );
			}
		}

		/**
		 * @param $allegro
		 *
		 * @throws Exception
		 */
		private function api_create_polecony( $allegro ) {

			$paczkomaty_shipping_method = $this->get_paczkomaty_shipping_method();

			$order = $this->get_order();

			$address   = trim( wpdesk_get_order_meta( $order, '_shipping_address_1', true ) . ' ' . wpdesk_get_order_meta( $order, '_shipping_address_2', true ) );
			$address_2 = trim( substr( $address, strripos( $address, ' ' ) ) );
			$address_1 = trim( substr( $address, 0, strripos( $address, ' ' ) ) );

			if ( $address_1 == '' ) {
				$address_1 = $address_2;
				$address_2 = '';
			}

			$packData                                   = [];
			$packData['senderEmail']                    = $paczkomaty_shipping_method->get_option( 'polecony_sender_email', '' );
			$packData['adreseeEmail']                   = wpdesk_get_order_meta( $order, '_billing_email', true );
			$packData['phoneNum']                       = $this->format_phone_number( wpdesk_get_order_meta( $order, '_billing_phone', true ) );
			$packData['senderBoxMachineName']           = $this->get_meta( self::META_PACZKOMAT_PUNKT_NADANIA );
			$packData['receiverAddress']                = [];
			$packData['receiverAddress']['name']        = wpdesk_get_order_meta( $order, '_shipping_first_name', true );
			$packData['receiverAddress']['surName']     = wpdesk_get_order_meta( $order, '_shipping_last_name', true );
			$packData['receiverAddress']['companyName'] = wpdesk_get_order_meta( $order, '_shipping_company', true );
			$packData['receiverAddress']['email']       = wpdesk_get_order_meta( $order, '_billing_email', true );
			$packData['receiverAddress']['phoneNum']    = $this->format_phone_number( wpdesk_get_order_meta( $order, '_billing_phone', true ) );
			$packData['receiverAddress']['street']      = $address_1;
			$packData['receiverAddress']['buildingNo']  = $address_2;
			$packData['receiverAddress']['town']        = wpdesk_get_order_meta( $order, '_shipping_city', true );
			$packData['receiverAddress']['zipCode']     = wpdesk_get_order_meta( $order, '_shipping_postcode', true );
			//
			$packData['senderAddress']                = [];
			$packData['senderAddress']['name']        = $paczkomaty_shipping_method->get_option( 'polecony_sender_name', '' );
			$packData['senderAddress']['surName']     = $paczkomaty_shipping_method->get_option( 'polecony_sender_surName', '' );
			$packData['senderAddress']['companyName'] = $paczkomaty_shipping_method->get_option( 'polecony_sender_companyName', '' );
			$packData['senderAddress']['email']       = $paczkomaty_shipping_method->get_option( 'polecony_sender_email', '' );
			$packData['senderAddress']['phoneNum']    = $paczkomaty_shipping_method->get_option( 'polecony_sender_phoneNum', '' );
			$packData['senderAddress']['street']      = $paczkomaty_shipping_method->get_option( 'polecony_sender_street', '' );
			$packData['senderAddress']['buildingNo']  = $paczkomaty_shipping_method->get_option( 'polecony_sender_street_number', '' );
			$packData['senderAddress']['town']        = $paczkomaty_shipping_method->get_option( 'polecony_sender_town', '' );
			$packData['senderAddress']['zipCode']     = $paczkomaty_shipping_method->get_option( 'polecony_sender_zipCode', '' );

			$selfSend = 0;

			if ( $allegro ) {
				$_allegro_journal_deal  = wpdesk_get_order_meta( $order, '_allegro_journal_deal', true );
				$_allegro_tansaction_id = wpdesk_get_order_meta( $order, '_allegro_tansaction_id', true );
				if ( $_allegro_journal_deal != '' && $_allegro_tansaction_id != '' ) {
					$packData['allegro']                  = [];
					$packData['allegro']['userId']        = $_allegro_journal_deal->dealSellerId;
					$packData['allegro']['transactionId'] = $_allegro_tansaction_id;
				}
			}

			$response = inpost_send_letters( $paczkomaty_shipping_method->get_option( 'email', '' ), $paczkomaty_shipping_method->get_option( 'password', '' ), [ $packData ], 1 );

			if ( ! empty( $response['error']['key'] ) ) {
				$this->set_meta( "_paczkomat_error", $response['error']['message'] );
				$this->update_status( 'fs-failed' );
				$this->save();
				throw new Exception( $response['error']['message'] );

			} elseif ( isset( $response[0]['packcode'] ) ) {
				$this->set_meta( "_paczkomat_packcode", $response[0]['packcode'] );
				$this->delete_meta( '_paczkomat_error' );
				$this->update_status( 'fs-confirmed' );
				$this->save();
				$this->add_order_note_tracking_id();
				$this->set_info_shipment_is_confirmed();
			} else {
				$this->set_meta( "_paczkomat_error", __( 'Wystąpił błąd podczas przetwarzania żądania.', 'woocommerce-paczkomaty-inpost' ) );
				$this->update_status( 'fs-failed' );
				$this->save();
				throw new Exception( __( 'Wystąpił błąd podczas przetwarzania żądania.', 'woocommerce-paczkomaty-inpost' ) );
			}

		}

		/**
		 * @param bool $allegro
		 *
		 * @throws Exception
		 */
		private function api_create_shipX( $allegro = false ) {

			$shipment_data = new stdClass();

			$shipment_data->service = $this->get_service();

			$shipment_data = $this->add_parcel_to_shipment( $shipment_data );

			$shipment_data = $this->add_receiver_to_shipment( $shipment_data );

			$shipment_data = $this->add_sender_to_shipment( $shipment_data );

			$shipment_data = $this->add_reference_to_shipment( $shipment_data );

			$shipment_data = $this->add_custom_attributes_to_shipment( $shipment_data );

			$shipment_data = $this->add_sending_method_to_shipment( $shipment_data );

			$shipment_data = $this->add_target_point_to_shipment( $shipment_data );

			$shipment_data = $this->add_insurance_to_shipment( $shipment_data );

			$shipment_data = $this->add_cod_to_shipment( $shipment_data );

			$shipment_data = $this->add_allegro_shipment( $shipment_data, $allegro );

			foreach ( $this->shipment_options as $shipment_option ) {
				$shipment_data = $shipment_option->modify_shipment_data( $shipment_data );
			}

			try {
				$shipX = $this->get_shipX();
				/**
				 * Filter woocommerce_paczkomaty_inpost_shipment_data.
				 * Can modify request data before send it to API.
				 *
				 * @param stdClass $shipment_data Original shipment data created by plugin.
				 *                                $shipment_data structure: @param WPDesk_Flexible_Shipping_Shipment_Paczkomaty $this Shipment data.
				 *
				 * @see            https://docs.inpost24.com/pages/viewpage.action?pageId=983195
				 *                 $shipment_data contains minimal required data to create shipment in API.
				 *                 ie. does not contains sender - sender data is defined on API side in user organisation.
				 */
				$shipment_data = apply_filters( self::FILTER_SHIPMENT_DATA, $shipment_data, $this );
				$this->set_meta( "_shipment_data_send", $shipment_data );
				$shipment = $shipX->create_shipment( $shipment_data );
				$this->set_meta( "_paczkomat_shipx", 1 );
				$this->set_meta( "_paczkomat_shipment", $shipment );
				$this->set_meta( self::META_PACZKOMAT_SHIPMENT_ID, $shipment->id );
				$this->set_meta( "_paczkomat_shipment_status", $shipment->status );
				$this->set_meta( "_paczkomat_error", '' );
				$this->set_meta( '_flexible_shipping_status', 'created' );
				$this->delete_meta( '_paczkomat_error' );
				$this->update_status( 'fs-created' );
				$this->save();
				/**
				 * Action woocommerce_paczkomaty_inpost_shipment_created.
				 * Fires when shipment is successfully created in API.
				 *
				 * @param WPDesk_Flexible_Shipping_Shipment_Paczkomaty $shipment Shipment.
				 */
				do_action( 'woocommerce_paczkomaty_inpost_shipment_created', $this );
			} catch ( Exception $e ) {
				$this->set_meta( "_paczkomat_error", $e->getMessage() );
				$this->update_status( 'fs-failed' );
				$this->save();
				throw new Exception( $e->getMessage() );
			}

		}

		/**
		 * @param stdClass $shipment_data
		 *
		 * @return stdClass
		 */
		public function add_parcel_to_shipment( $shipment_data ) {
			$parcel = new stdClass();
			if ( $this->is_shipment_to_parcel_locker() ) {
				$parcel->template = $this->size_to_template( $this->get_meta( self::META_PACZKOMAT_SIZE ) );
			} elseif ( $this->get_service() == 'inpost_letter_allegro' ) {
				$parcel->template = 'letter_a';
			} else {
				$parcel->dimensions         = new stdClass();
				$parcel->dimensions->unit   = 'mm';
				$parcel->dimensions->width  = $this->get_meta( '_paczkomat_width' );
				$parcel->dimensions->length = $this->get_meta( '_paczkomat_length' );
				$parcel->dimensions->height = $this->get_meta( '_paczkomat_height' );

				$parcel->weight         = new stdClass();
				$parcel->weight->amount = $this->get_meta( '_paczkomat_weight' );
				$parcel->weight->unit   = 'kg';
			}

			$shipment_data->parcels   = [];
			$shipment_data->parcels[] = $parcel;

			return $shipment_data;
		}

		/**
		 * @param stdClass $shipment_data
		 *
		 * @return stdClass
		 */
		public function add_receiver_to_shipment( $shipment_data ) {

			$order = $this->get_order();

			$receiver = new stdClass();

			if ( ! $this->is_shipment_to_parcel_locker() ) {

				$address   = trim( wpdesk_get_order_meta( $order, '_shipping_address_1',
						true ) . ' ' . wpdesk_get_order_meta( $order, '_shipping_address_2', true ) );
				$address_2 = trim( substr( $address, strripos( $address, ' ' ) ) );
				$address_1 = trim( substr( $address, 0, strripos( $address, ' ' ) ) );

				if ( $address_1 == '' ) {
					$address_1 = $address_2;
					$address_2 = '';
				}

				$receiver_address                  = new stdClass();
				$receiver_address->street          = $address_1;
				$receiver_address->building_number = $address_2;
				$receiver_address->city            = wpdesk_get_order_meta( $order, '_shipping_city', true );
				$receiver_address->post_code       = wpdesk_get_order_meta( $order, '_shipping_postcode', true );
				$receiver_address->country_code    = wpdesk_get_order_meta( $order, '_shipping_country', true );

				$receiver->address = $receiver_address;

				$receiver->company_name = wpdesk_get_order_meta( $order, '_shipping_company', true );
				$receiver->first_name   = wpdesk_get_order_meta( $order, '_shipping_first_name', true );
				$receiver->last_name    = wpdesk_get_order_meta( $order, '_shipping_last_name', true );
			}

			$receiver->email = wpdesk_get_order_meta( $order, '_billing_email', true );
			$receiver->phone = $this->format_phone_number( wpdesk_get_order_meta( $order, '_billing_phone', true ) );

			$shipment_data->receiver = $receiver;

			return $shipment_data;
		}

		/**
		 * @param stdClass $shipment_data
		 *
		 * @return stdClass
		 */
		public function add_sender_to_shipment( $shipment_data ) {
			// TODO disabled sender data for now
			/*
			if ( !empty( $paczkomaty_shipping_method->polecony_sender_name ) ) {
				$sender_address = new stdClass();
				$sender_address->street = $paczkomaty_shipping_method->polecony_sender_street;
				$sender_address->building_number = $paczkomaty_shipping_method->polecony_sender_street_number;
				$sender_address->city = $paczkomaty_shipping_method->polecony_sender_town;
				$sender_address->post_code = $paczkomaty_shipping_method->polecony_sender_zipCode;
				$sender_address->country_code = 'PL';

				$sender = new stdClass();
				$sender->company_name = $paczkomaty_shipping_method->polecony_sender_companyName;
				$sender->first_name = $paczkomaty_shipping_method->polecony_sender_name;
				$sender->last_name = $paczkomaty_shipping_method->polecony_sender_surName;
				$sender->email = $paczkomaty_shipping_method->polecony_sender_email;
				$sender->phone = $paczkomaty_shipping_method->polecony_sender_phoneNum;
				$sender->address = $sender_address;

				$shipment_data->sender = $sender;

			}
			*/
			return $shipment_data;
		}

		/**
		 * @param stdClass $shipment_data
		 *
		 * @return stdClass
		 */
		public function add_reference_to_shipment( $shipment_data ) {
			$shipment_data->reference = $this->get_meta( '_paczkomat_customer_ref' );

			return $shipment_data;
		}

		/**
		 * @param stdClass $shipment_data
		 *
		 * @return stdClass
		 */
		public function add_custom_attributes_to_shipment( $shipment_data ) {
			$shipment_data->custom_attributes = new stdClass();

			return $shipment_data;
		}

		/**
		 * @param stdClass $shipment_data
		 *
		 * @return stdClass
		 */
		public function add_sending_method_to_shipment( $shipment_data ) {
			$shipment_data->custom_attributes->sending_method = $this->get_meta( '_paczkomat_sending_method' );
			if ( $this->get_meta( '_paczkomat_sending_method' ) == 'parcel_locker' ) {
				$drop_off_point = $this->get_meta( '_paczkomat_dropoff_parcel_machine' );
				if ( empty( $drop_off_point ) ) {
					$paczkomaty_shipping_method = $this->get_paczkomaty_shipping_method();
					$drop_off_point             = $paczkomaty_shipping_method->get_option( 'default_parcel_locker' );
				}
				$shipment_data->custom_attributes->dropoff_point = $drop_off_point;
			}

			$shipment_data->sending_method = $this->get_meta( '_paczkomat_sending_method' );

			return $shipment_data;
		}

		/**
		 * Is shipment to parcel locker.
		 *
		 * @return bool
		 */
		private function is_shipment_to_parcel_locker() {
			return $this->get_service() === self::INPOST_LOCKER_STANDARD || $this->get_service() === self::INPOST_LOCKER_ALLEGRO;
		}

		/**
		 * @param stdClass $shipment_data
		 *
		 * @return stdClass
		 */
		public function add_target_point_to_shipment( $shipment_data ) {
			if ( $this->is_shipment_to_parcel_locker() ) {
				$shipment_data->custom_attributes->target_point = $this->get_meta( '_paczkomat_id' );
			}

			return $shipment_data;
		}

		/**
		 * @return bool
		 */
		public function is_insurance_available() {
			$available = true;

			return $available;
		}

		/**
		 * @param stdClass $shipment_data
		 *
		 * @return stdClass
		 */
		public function add_insurance_to_shipment( $shipment_data ) {
			if ( $this->is_insurance_available() ) {
				if ( $this->get_meta( self::META_PACZKOMAT_UBEZPIECZENIE, '0' ) == '1' ) {
					$order                              = $this->get_order();
					$shipment_data->insurance           = new stdClass();
					$shipment_data->insurance->amount   = $this->get_meta( self::META_PACZKOMAT_UBEZPIECZENIE_AMOUNT );
					$shipment_data->insurance->currency = wpdesk_get_order_meta( $order, '_order_currency', true );
				}
			}

			return $shipment_data;
		}

		/**
		 * @return bool
		 */
		public function is_cod_available() {
			$available = true;

			return $available;
		}

		/**
		 * @param stdClass $shipment_data
		 *
		 * @return stdClass
		 */
		public function add_cod_to_shipment( $shipment_data ) {
			if ( $this->is_cod_available() ) {
				if ( $this->get_meta( '_paczkomat_cod', '0' ) == '1' ) {
					$order                        = $this->get_order();
					$shipment_data->cod           = new stdClass();
					$shipment_data->cod->amount   = $this->get_meta( '_paczkomat_cod_amount' );
					$shipment_data->cod->currency = wpdesk_get_order_meta( $order, '_order_currency', true );
				}
			}

			return $shipment_data;
		}

		/**
		 * @param stdClass $shipment_data
		 * @param bool     $allegro
		 *
		 * @return stdClass
		 */
		public function add_allegro_shipment( $shipment_data, $allegro ) {
			if ( $allegro ) {
				$order                  = $this->get_order();
				$_allegro_journal_deal  = wpdesk_get_order_meta( $order, '_allegro_journal_deal', true );
				$_allegro_tansaction_id = wpdesk_get_order_meta( $order, '_allegro_tansaction_id', true );
				if ( $_allegro_journal_deal != '' && $_allegro_tansaction_id != '' ) {
					$shipment_data->custom_attributes->allegro_user_id        = $_allegro_journal_deal->dealSellerId;
					$shipment_data->custom_attributes->allegro_transaction_id = $_allegro_tansaction_id;
				}
			}

			return $shipment_data;
		}

		/**
		 * @param $size
		 *
		 * @return mixed
		 */
		private function size_to_template( $size ) {
			return $this->packege_templates[ $size ];
		}

		/**
		 * @return string
		 */
		private function get_service() {
			$service        = self::INPOST_LOCKER_STANDARD;
			$sending_method = $this->get_meta( self::META_PACZKOMAT_SENDING_METHOD );
			if ( $this->get_meta( '_paczkomaty_usluga', 'paczkomaty' ) == 'allegro_paczkomaty' ) {
				$service = self::INPOST_LOCKER_ALLEGRO;
			}
			if ( $this->get_meta( '_paczkomaty_usluga', 'paczkomaty' ) == self::SERVICE_KURIER ) {
				if ( $sending_method === 'parcel_locker' ) {
					$service = 'inpost_courier_c2c';
				} else {
					$service = 'inpost_courier_standard';
				}
			}
			if ( $this->get_meta( '_paczkomaty_usluga', 'paczkomaty' ) == 'allegro_kurier' ) {
				$service = 'inpost_courier_allegro';
			}
			if ( $this->get_meta( '_paczkomaty_usluga', 'paczkomaty' ) == 'allegro_polecony' ) {
				$service = 'inpost_letter_allegro';
			}

			return $service;
		}

		/**
		 * @return WPDesk_Paczkomaty_ShipX
		 */
		public function get_shipX() {
			if ( $this->ship_x == null ) {
				$paczkomaty_shipping_method = $this->get_paczkomaty_shipping_method();
				$test_mode                  = true;
				if ( $paczkomaty_shipping_method->get_option( 'test_mode', '' ) != 'yes' ) {
					$test_mode = false;
				}
				$organization_id = $paczkomaty_shipping_method->get_option( 'organization_id', '' );
				$this->ship_x    = new WPDesk_Paczkomaty_ShipX( $paczkomaty_shipping_method->get_option( 'token', '' ), $paczkomaty_shipping_method->get_option( 'token_test_mode', '' ), $test_mode );
				$this->ship_x->set_organization_id( $organization_id );
			}

			return $this->ship_x;
		}

		/**
		 *
		 */
		private function add_order_note_tracking_id() {
			$order = $this->get_order();
			$order->add_order_note( sprintf( __( 'Do zamówienia została utworzona przesyłka %s InPost. Link do śledzenia przesyłki: %s', 'woocommerce-paczkomaty-inpost' ), $this->get_tracking_number(), $this->get_tracking_url() ), 1 );
		}

		/**
		 *
		 */
		public function admin_add_shipment() {
			$this->set_meta( '_paczkomaty_usluga', 'paczkomaty' );
			$this->set_meta( '_paczkomat_weight', ( new WooCommerce_Order_Weight_Calculator( $this->get_order() ) )->get_order_weight_kg() );
		}

		/**
		 * Compatibility with XML API for:
		 *      _sending_method
		 *
		 * @param string $meta_key
		 * @param null   $default
		 *
		 * @return array|mixed|null|string
		 */
		public function get_meta( $meta_key = '', $default = null ) {
			$meta_value = parent::get_meta( $meta_key, $default );
			if ( $meta_key == '_paczkomat_sending_method' && empty( $meta_value ) ) {
				$paczkomaty_how_to_give = $this->get_meta( '_paczkomat_how_to_give', '' );
				if ( $paczkomaty_how_to_give == '1' ) {
					$meta_value = 'parcel_locker';
				}
				if ( $paczkomaty_how_to_give == '3' ) {
					$meta_value = 'dispatch_order';
				}
			}

			return $meta_value;
		}

		/**
		 * @return WC_Paczkomaty_Shipping_Method
		 */
		public function get_paczkomaty_shipping_method() {
			$all_shipping_methods = WC()->shipping()->get_shipping_methods();
			if ( empty( $all_shipping_methods ) ) {
				$all_shipping_methods = WC()->shipping()->load_shipping_methods();
			}
			$paczkomaty_shipping_method = $all_shipping_methods['paczkomaty_shipping_method'];

			return $paczkomaty_shipping_method;
		}

		/**
		 * @param string $phone_number
		 *
		 * @return string
		 */
		public function format_phone_number( $phone_number ) {
			$phone_number = str_replace( ' ', '', $phone_number );
			if ( strpos( $phone_number, '+48' ) === 0 ) {
				$phone_number = substr( $phone_number, 3 );
			}
			if ( strpos( $phone_number, '0' ) === 0 ) {
				$phone_number = substr( $phone_number, 1 );
			}

			return $phone_number;
		}

	}

}
