<?php

namespace wp_opieka_globkurier;

use WC_Order_Item_Shipping;
use function Sodium\add;

class WoocommerceAddons{
	
	private $globKurier;
	
	public function __construct(){
		global $globKurier;
		$this->globKurier = $globKurier;
	}
	
	public function init(){
		
		add_filter('woocommerce_screen_ids', [$this, 'set_wc_screen_ids']);
		
		add_filter('woocommerce_get_sections_shipping', static function ($section){
			$section[ 'globkurier' ] = __('GlobKurier', 'globkurier');
			
			return $section;
		});
		
		add_filter('woocommerce_get_settings_shipping', [$this, 'globkurier_settings'], 10, 2);
		
		add_action('woocommerce_admin_field_udihidden', static function ($value){
			
			echo '<tr valign="top" class="'.$value[ 'class' ].'" '.$value[ 'style' ].'>';
			echo '	<th scope="row" class="titledesc">';
			echo '		<label for="'.$value[ 'id' ].'">'.$value[ 'title' ].'</label>';
			echo '	</th>';
			echo '	<td class="forminp forminp-text">';
			echo "		<input name='{$value['name']}' id ='{$value['id']}' type ='text' value='{$value['value']}'>";
			echo '  </td>';
			echo '</tr>';
			
		}, 10, 1);
		
		add_action('woocommerce_admin_field_udiHiddenUpdateInpostBtn', static function ($value){
			
			echo '<tr valign="top" class="'.$value[ 'class' ].'" '.$value[ 'style' ].'>';
			echo '	<th scope="row" class="titledesc" style="padding: 0;">';
			echo '		<label for="'.$value[ 'id' ].'">'.$value[ 'title' ].'</label>';
			echo '	</th>';
			echo '	<td class="forminp forminp-text" style="padding-top: 0;padding-bottom: 0; display: flex">';
			echo "		<button class='button-primary updateInpostButton' type='button'>Wgraj aktualne punkty Inpost</button>";
			echo "		<div class='udi-loader'></div>";
			echo '  </td>';
			echo '</tr>';
			
		}, 10, 1);
		
		add_action('woocommerce_admin_field_udiHiddenUpdateRuchBtn', static function ($value){
			
			echo '<tr valign="top" class="'.$value[ 'class' ].'" '.$value[ 'style' ].'>';
			echo '	<th scope="row" class="titledesc" style="padding: 0;">';
			echo '		<label for="'.$value[ 'id' ].'">'.$value[ 'title' ].'</label>';
			echo '	</th>';
			echo '	<td class="forminp forminp-text" style="padding-top: 0;padding-bottom: 0; display: flex">';
			echo "		<button class='button-primary updateRuchButton' type='button'>Wgraj aktualne punkty ORLEN Paczka</button>";
			echo "		<div class='udi-loader'></div>";
			echo '  </td>';
			echo '</tr>';
			
		}, 10, 1);
		
		add_action('woocommerce_admin_field_udireadonly', static function ($value){
			
			echo '<tr valign="top">';
			echo '	<th scope="row" class="titledesc">';
			echo '		<label for="'.$value[ 'id' ].'">'.$value[ 'title' ].'</label>';
			echo '	</th>';
			echo '	<td class="forminp forminp-text">';
			echo '		<input readonly  name="'.$value[ 'name' ].'" id="'.$value[ 'id' ].'" type="'.$value[ '_type' ].'" style="" value="'.$value[ 'value' ].'">';
			echo '  </td>';
			echo '</tr>';
			
		}, 10, 1);
		
		add_action('woocommerce_admin_field_udisectionstart', static function ($value){
			echo '<div class="udi-section-start">';
		}, 10, 1);
		
		add_action('woocommerce_admin_field_udisectionend', static function ($value){
			echo '</div>';
		}, 10, 1);
		
		add_filter('pre_update_option_globkurier', [$this, 'hashPasswordValue'], 10, 2);
		
		add_action('add_meta_boxes', [$this, 'globkurier_wc_order_meta_box']);
		
		add_action('add_meta_boxes', [$this, 'globkurier_wc_old_orders_meta_box']);
		
		add_action('woocommerce_after_shipping_rate', [$this, 'afterShippingMethodSelected'], 100, 2);
		
		add_action('woocommerce_review_order_before_order_total', function (){
			
			$chosenShippingMethods = WC()->session->get('chosen_shipping_methods');

//			$methodId = $method->get_id();
			
			global $globKurier;
			
			$googleMapsAPIKey = $globKurier->settings('googleMapApiKey');
			
			if (empty($googleMapsAPIKey)) {
				return;
			}
			
			$globkurierInpost = [
				'active'   => $globKurier->settings('inpost_active') ?? '',
				'methodId' => $globKurier->settings('inpost_method') ?? '',
			];
			
			$globkurierRuch = [
				'active'   => $globKurier->settings('ruch_active') ?? '',
				'methodId' => $globKurier->settings('ruch_method') ?? '',
			];
			
			if ($chosenShippingMethods[ 0 ] == $globkurierInpost[ 'methodId' ] && $globkurierInpost[ 'active' ]) {
//				require_once( 'inpostMap.php' );
				require_once( 'inpostMapAjax.php' );
			}
			
			if ($chosenShippingMethods[ 0 ] == $globkurierRuch[ 'methodId' ] && $globkurierRuch[ 'active' ]) {
//				require_once( 'ruchMap.php' );
				require_once( 'ruchMapWithAjaxSearch.php' );
			}
				
		});
		
		add_action('woocommerce_after_checkout_validation', [
			$this,
			'globkurier_woocommerce_after_checkout_validation'
		], 10, 2);
		
		add_action('woocommerce_after_order_itemmeta', [
			$this,
			'globkurier_woocommerce_admin_order_items_after_line_items'
		], 10, 3);
		
		add_action('woocommerce_checkout_update_order_meta', [
			$this,
			'globkurier_woocommerce_checkout_create_order'
		], 20, 3);
	}
	
	public function set_wc_screen_ids( $screen ){
		$screen[] = 'globkurier_page_globkurier_ship_order';
		
		return $screen;
	}
	
	public function globkurier_wc_order_meta_box(){
		
		add_meta_box('globkurier_ship_new_order', __('NADAJ PRZESYŁKĘ Z GLOBKURIER', 'globkurier'), [
			$this,
			'globkurier_meta_box_content'
		], 'shop_order', 'advanced', 'high');
	}
	
	public function globkurier_meta_box_content(){
		
		require_once 'metaBox/order.php';
	}
	
	public function globkurier_wc_old_orders_meta_box(){
		
		$mataName = apply_filters('globkurier_wc_order_meta_name', 'globkurier_orders');
		
		$oldOrders = get_post_meta(get_the_ID(), $mataName, false);
		
		if (count($oldOrders) == 0) {
			return;
		}
		
		add_meta_box('globkurier_old_orders', __('PACZKI NADANE PRZEZ GLOBKURIER', 'globkurier').' ('.count($oldOrders).')', [
			$this,
			'globkurier_meta_old_orders_box_content',
		], 'shop_order', 'advanced', 'core');
	}
	
	public function globkurier_meta_old_orders_box_content(){
		
		require_once 'metaBox/oldOrders.php';
	}
	
	public function hashPasswordValue( $options ){
		
		global $globKurier;
		
		$oldPassword = $globKurier->settings('password');
		$newPassword = $_POST[ 'globkurier' ][ 'password' ];
		
		if ($newPassword !== $oldPassword) {
			$options[ 'password' ] = $globKurier->encrypter()->encrypt($newPassword);
		}
		
		return $options;
	}
	
	public function globkurier_settings( $settings, $current_section ){
		if ($current_section == 'globkurier') {
			
			global $globKurier;
			
			$settings_globkurier   = [];
			$settings_globkurier[] = [
				'name' => __('GlobKurier - konfiguracja', 'globkurier'),
				'id'   => 'globkurier-info',
				'desc' => '<div>
								<div class="udi-container-column udi-globkurier-how-to-start-container">
									<h3 class="udi-globkurier-how-to-start-header">Jak rozpocząć</h3>
										<ol class="udi-globkurier-how-to-start-list">
											<li>Uzupełnij dane Użytkownik GlobKurier</li>
											<li>Uzupełnij dane domyślne</li>
											<li>Gotowe!</li>
										</ol>
								</div>'
						  .__('Nie masz konta?', 'text-domain').' <a href="http://globkurier.pl/register" target="_blank">'.__('Zarejestruj się', 'globkurier').'</a>'
						  //				          . '<br>'
						  //				          . '<br>'
						  //				          . '<a href="' . $globKurier->getSettingsUrl() . '&updateRuchPoints=1"><button class="button-primary" type="button" style="margin-right: 15px" >' . __( 'Aktualizuj punkty RUCHu', 'text-domain' )  . '</button></a>'
						  //				          . '<a href="' . $globKurier->getSettingsUrl() . '&updateInpostPoints=1"><button class="button-primary" type="button">' . __( 'Aktualizuj punkty Inpost', 'text-domain' )  . '</button></a>'
						  .'</div>',
				'type' => 'title',
			];
			
			$user     = get_option('globkurier-username');
			$password = get_option('globkurier-password');
			
			$settings_globkurier[] = [
				'title'   => __('Język API', 'globkurier'),
				'name'    => 'globkurier[language]',
				'id'      => 'globkurier[language]',
				'value'   => get_option('globkurier')[ 'language' ] ?? '',
				'type'    => 'select',
				'options' => ['pl' => __('Polski', 'globkurier'), 'en' => __('Angielski', 'globkurier')],
			];
			
			$status = $globKurier->isUserLoggedIn(false);
			
			if (! $status) {
				$settings_globkurier = array_merge($settings_globkurier, $this->getSettingsSection_login());
			} else {
				$settings_globkurier = array_merge($settings_globkurier, $this->getSettingsSection_login());
				$settings_globkurier = array_merge($settings_globkurier, $this->getSettingsSection_defaults());
				
				if (isset($_GET[ 'updateInpostPoints' ])) {
					$globKurier->inpost()->update();
					wp_redirect($globKurier->getSettingsUrl().'&updateInpostSuccess');
					wp_die();
				}
				
				if (isset($_GET[ 'updateRuchPoints' ])) {
					$globKurier->ruch()->update();
					wp_redirect($globKurier->getSettingsUrl().'&updateRuchSuccess');
					wp_die();
				}
				
				if (isset($_GET[ 'updateInpostSuccess' ])) {
					echo "<div class=\"notice notice-info\">";
					echo "<p>Paczkomaty zostały zaktualizowane</p>";
					echo '</div>';
				}
				if (isset($_GET[ 'updateRuchSuccess' ])) {
					echo "<div class=\"notice notice-info\">";
					echo "<p>Punkt RUCHu zostały zaktualizowane</p>";
					echo '</div>';
				}
				
			}
			
			return $settings_globkurier;
		}
		
		return $settings;
	}
	
	public function getSettingsSection_login(){
		$settings_inputs = [];
		
		$settings_inputs[] = [
			'title' => __('Użytkownik GlobKurier', 'globkurier'),
			'type'  => 'title',
		];
		
		$settings_inputs[] = [
			'title' => __('Użytkownik', 'globkurier'),
			'name'  => 'globkurier[username]',
			'id'    => 'globkurier[username]',
			'value' => get_option('globkurier')[ 'username' ] ?? '',
			'type'  => 'text',
			'desc'  => __('Twój login z serwisu GlobKurier', 'globkurier'),
		];
		
		$settings_inputs[] = [
			'title' => __('Hasło', 'globkurier'),
			'id'    => 'globkurier[password]',
			'name'  => 'globkurier[password]',
			'value' => get_option('globkurier')[ 'password' ] ?? '',
			'desc'  => __('Twoje hasło z serwisu GlobKurier', 'globkurier'),
			'type'  => 'password',
		];
		
		$settings_inputs[] = [
			'title' => __('Google Maps API KEY', 'globkurier'),
			'name'  => 'globkurier[googleMapApiKey]',
			'id'    => 'globkurier[googleMapApiKey]',
			'value' => get_option('globkurier')[ 'googleMapApiKey' ] ?? '',
			'type'  => 'text',
		];
		
		$settings_inputs[] = ['type' => 'sectionend', 'id' => 'globkurier-login-end'];
		
		return $settings_inputs;
	}
	
	public function getSettingsSection_defaults(){
		$settings_inputs = [];
		
		$settings_inputs[] = ['type' => 'udisectionstart'];
		
		$settings_inputs = array_merge($settings_inputs, $this->getSettingsSection_defaults_send());
		$settings_inputs = array_merge($settings_inputs, $this->getSettingsSection_defaults_parcel());
		
		$settings_inputs[] = ['type' => 'udisectionstart'];
		
		return $settings_inputs;
	}
	
	public function getSettingsSection_defaults_send(){
	
		$settings_inputs = [];
		
		$settings_inputs[] = ['type' => 'udisectionstart'];
		
		$settings_inputs[] = [
			'title' => __('Domyślny adres nadania', 'globkurier'),
			'type'  => 'title',
		];

//		$settings_inputs[] = [
//			'title' => __( 'Nazwa', 'globkurier' ),
//			'name'  => 'globkurier[default][send][name]',
//			'id'    => 'globkurier[default][send][name]',
//			'value' => get_option( 'globkurier' )[ 'default' ][ 'send' ][ 'name' ] ?? '',
//			'type'  => 'text',
//		];
		
		$settings_inputs[] = [
			'title' => __('Imię i nazwisko', 'globkurier'),
			'name'  => 'globkurier[default][send][flnames]',
			'id'    => 'globkurier[default][send][flnames]',
			'value' => get_option('globkurier')[ 'default' ][ 'send' ][ 'flnames' ] ?? '',
			'type'  => 'text',
		];
		
		$settings_inputs[] = [
			'title' => __('Ulica', 'globkurier'),
			'name'  => 'globkurier[default][send][street]',
			'id'    => 'globkurier[default][send][street]',
			'value' => get_option('globkurier')[ 'default' ][ 'send' ][ 'street' ] ?? '',
			'type'  => 'text',
		];
		
		$settings_inputs[] = [
			'title' => __('Numer domu', 'globkurier'),
			'name'  => 'globkurier[default][send][homeNumber]',
			'id'    => 'globkurier[default][send][homeNumber]',
			'value' => get_option('globkurier')[ 'default' ][ 'send' ][ 'homeNumber' ] ?? '',
			'type'  => 'text',
		];
		
		$settings_inputs[] = [
			'title' => __('Numer lokalu', 'globkurier'),
			'name'  => 'globkurier[default][send][flatNumber]',
			'id'    => 'globkurier[default][send][flatNumber]',
			'value' => get_option('globkurier')[ 'default' ][ 'send' ][ 'flatNumber' ] ?? '',
			'type'  => 'text',
		];
		
		$settings_inputs[] = [
			'title' => __('Miasto', 'globkurier'),
			'name'  => 'globkurier[default][send][city]',
			'id'    => 'globkurier[default][send][city]',
			'value' => get_option('globkurier')[ 'default' ][ 'send' ][ 'city' ] ?? '',
			'type'  => 'text',
		];
		
		$settings_inputs[] = [
			'title' => __('Kod pocztowy', 'globkurier'),
			'name'  => 'globkurier[default][send][postal]',
			'id'    => 'globkurier[default][send][postal]',
			'value' => get_option('globkurier')[ 'default' ][ 'send' ][ 'postal' ] ?? '',
			'type'  => 'text',
		];
		
		$settings_inputs[] = [
			'title'   => __('Państwo', 'globkurier'),
			'name'    => 'globkurier[default][send][country]',
			'id'      => 'globkurier[default][send][country]',
			'value'   => get_option('globkurier')[ 'default' ][ 'send' ][ 'country' ] ?? '',
			'type'    => 'select',
			'options' => $this->globKurier->countries()->getArray(),
		];
		
		$settings_inputs[] = [
			'title' => __('Email', 'globkurier'),
			'name'  => 'globkurier[default][send][email]',
			'id'    => 'globkurier[default][send][email]',
			'value' => get_option('globkurier')[ 'default' ][ 'send' ][ 'email' ] ?? '',
			'type'  => 'email',
		];
		
		$settings_inputs[] = [
			'title' => __('Numer telefonu', 'globkurier'),
			'name'  => 'globkurier[default][send][phone]',
			'id'    => 'globkurier[default][send][phone]',
			'value' => get_option('globkurier')[ 'default' ][ 'send' ][ 'phone' ] ?? '',
			'type'  => 'text',
		];
		
		$settings_inputs[] = ['type' => 'sectionend', 'id' => 'globkurier-default-send-end'];
		
		$settings_inputs[] = ['type' => 'udisectionend'];
		
		return $settings_inputs;
	}
	
	public function getSettingsSection_defaults_parcel(){
		$settings_inputs = [];
		
		$settings_inputs[] = ['type' => 'udisectionstart'];
		
		$settings_inputs[] = [
			'title' => __('Domyślne parametry przesyłki', 'globkurier'),
			'type'  => 'title',
		];
		
		$settings_inputs[] = [
			'title' => __('Długość [cm]', 'globkurier'),
			'name'  => 'globkurier[default][parcel][length]',
			'id'    => 'globkurier[default][parcel][length]',
			'value' => get_option('globkurier')[ 'default' ][ 'parcel' ][ 'length' ] ?? '',
			'type'  => 'number',
		];
		$settings_inputs[] = [
			'title' => __('Szerokość [cm]', 'globkurier'),
			'name'  => 'globkurier[default][parcel][width]',
			'id'    => 'globkurier[default][parcel][width]',
			'value' => get_option('globkurier')[ 'default' ][ 'parcel' ][ 'width' ] ?? '',
			'type'  => 'number',
		];
		
		$settings_inputs[] = [
			'title' => __('Wysokość [cm]', 'globkurier'),
			'name'  => 'globkurier[default][parcel][height]',
			'id'    => 'globkurier[default][parcel][height]',
			'value' => get_option('globkurier')[ 'default' ][ 'parcel' ][ 'height' ] ?? '',
			'type'  => 'number',
		];
		
		$settings_inputs[] = [
			'title' => __('Waga (w kg)', 'globkurier'),
			'name'  => 'globkurier[default][parcel][weight]',
			'id'    => 'globkurier[default][parcel][weight]',
			'value' => get_option('globkurier')[ 'default' ][ 'parcel' ][ 'weight' ] ?? '',
			'type'  => 'number',
		];
		
		$settings_inputs[] = [
			'title'   => __('Zawartość', 'globkurier'),
			'name'    => 'globkurier[default][parcel][content]',
			'id'      => 'globkurier[default][parcel][content]',
			'value'   => get_option('globkurier')[ 'default' ][ 'parcel' ][ 'content' ] ?? '',
			'type'    => 'select',
			'options' => $this->globKurier->contentsList(),
		];
		
		if ((get_option('globkurier')[ 'default' ][ 'parcel' ][ 'content' ] ?? '') == 'Inne') {
			$style = '';
		} else {
			$style = 'style="display:none"';
		}
		
		$settings_inputs[] = [
			'title' => __('Inna zawartość - jaka?', 'globkurier'),
			'name'  => 'globkurier[default][parcel][otherContent]',
			'id'    => 'globkurier[default][parcel][otherContent]',
			'class' => 'globkurier-content-other',
			'value' => get_option('globkurier')[ 'default' ][ 'parcel' ][ 'otherContent' ] ?? '',
			'style' => $style,
			'type'  => 'udihidden',
		];
		
		$settings_inputs[] = [
			'title' => __('Numer konta bankowego do pobrań', 'globkurier'),
			'desc'  => 'Numer konta w formacie IBAN ( PL29109015199335376470438408 )',
			'name'  => 'globkurier[default][parcel][cod][account][number]',
			'id'    => 'globkurier[default][parcel][cod][account][number]',
			'value' => get_option('globkurier')[ 'default' ][ 'parcel' ][ 'cod' ][ 'account' ][ 'number' ] ?? '',
			'type'  => 'text',
		];
		
		$settings_inputs[] = [
			'title' => __('Nazwa właściciela rachunku', 'globkurier'),
			'name'  => 'globkurier[default][parcel][cod][account][name]',
			'id'    => 'globkurier[default][parcel][cod][account][name]',
			'value' => get_option('globkurier')[ 'default' ][ 'parcel' ][ 'cod' ][ 'account' ][ 'name' ] ?? '',
			'type'  => 'text',
		];
		
		$settings_inputs[] = [
			'title' => __('Ulica właściciela rachunku', 'globkurier'),
			'name'  => 'globkurier[default][parcel][cod][account][owner]',
			'id'    => 'globkurier[default][parcel][cod][account][owner]',
			'value' => get_option('globkurier')[ 'default' ][ 'parcel' ][ 'cod' ][ 'account' ][ 'owner' ] ?? '',
			'type'  => 'text',
		];
		
		$settings_inputs[] = [
			'title' => __('Kod pocztowy i miejscowość właściciela rachunku', 'globkurier'),
			'name'  => 'globkurier[default][parcel][cod][account][address]',
			'id'    => 'globkurier[default][parcel][cod][account][address]',
			'value' => get_option('globkurier')[ 'default' ][ 'parcel' ][ 'cod' ][ 'account' ][ 'address' ] ?? '',
			'type'  => 'text',
		];
		
		$settings_inputs[] = [
			'title'   => __('Domyślna metoda płatności', 'globkurier'),
			'name'    => 'globkurier[payment]',
			'id'      => 'globkurier[payment]',
			'type'    => 'select',
			'value'   => get_option('globkurier')[ 'payment' ] ?? '',
			'options' => $this->globKurier->user()->paymentMethods(),
		];
		
		$settings_inputs[] = ['type' => 'sectionend', 'id' => 'globkurier-default-parcel-end'];
		$settings_inputs[] = ['type' => 'udisectionend'];
		
		$settings_inputs[] = ['type' => 'udisectionstart'];
		
		$settings_inputs[] = [
			'title' => __('InPost paczkomaty', 'globkurier'),
			'type'  => 'title',
		];
		
		$inpostValue = get_option('globkurier')[ 'inpost_active' ] ?? '';
		
		
		$settings_inputs[] = [
			'title'   => __('Włącz obsługę paczkomatów InPost', 'globkurier'),
			'name'    => 'globkurier[inpost_active]',
			'id'      => 'globkurier[inpost_active]',
			'value'   => $inpostValue,
			'type'    => 'select',
			'options' => [
				0 => __('NIE', 'globkurier'),
				1 => __('TAK', 'globkurier'),
			],
		];
		
		$settings_inputs[] = [
			'title' => '',
			'name'  => 'updateInpost',
			'id'    => 'updateInpost',
			'class' => 'updateInpostContainer',
			'value' => '',
			'style' => ($inpostValue == 0) ? 'style="display:none"' : '',
			'type'  => 'udiHiddenUpdateInpostBtn',
		];
		
		$settings_inputs[] = [
			'title'   => __('Wymuś aktualizację punktów Inpost jeśli starsze niż 1 dzień', 'globkurier'),
			'name'    => 'globkurier[inpost_points_valid_time_checker_is_active]',
			'id'      => 'globkurier[inpost_points_valid_time_checker_is_active]',
			'value'   => get_option('globkurier')[ 'inpost_points_valid_time_checker_is_active' ] ?? 0,
			'type'    => 'select',
			'options' => [
				0 => __('NIE', 'globkurier'),
				1 => __('TAK', 'globkurier'),
			],
		];
		
		$settings_inputs[] = [
			'title'   => __('Zapisz punkty Inpost w pliku json', 'globkurier'),
			'name'    => 'globkurier[storeInpostPointsInFile]',
			'id'      => 'globkurier[storeInpostPointsInFile]',
			'value'   => get_option('globkurier')[ 'storeInpostPointsInFile' ] ?? 1,
			'type'    => 'select',
			'options' => [
				0 => __('NIE', 'globkurier'),
				1 => __('TAK', 'globkurier'),
			],
		];
		
		$settings_inputs[] = [
			'title'   => __('Metoda wysyłki do obłsugi paczkomatów InPost', 'globkurier'),
			'name'    => 'globkurier[inpost_method]',
			'id'      => 'globkurier[inpost_method]',
			'value'   => get_option('globkurier')[ 'inpost_method' ] ?? '',
			'type'    => 'select',
			'options' => $this->globKurier->wcShippingMethods()->getArray(),
		];
		
		$settings_inputs[] = [
			'title' => __('Wpisz miasto domyślnego paczkomatu nadawczego', 'globkurier'),
			'name'  => 'globkurier[inpost_default]',
			'id'    => 'globkurier[inpost_default]',
			'value' => get_option('globkurier')[ 'inpost_default' ] ?? '',
			'type'  => 'text',
		];
		
		$settings_inputs[] = [
			'title' => __('Kod paczkomatu nadawczego', 'globkurier'),
			'name'  => 'globkurier[inpost_default_code]',
			'id'    => 'globkurier[inpost_default_code]',
			'value' => get_option('globkurier')[ 'inpost_default_code' ] ?? '',
			'type'  => 'udireadonly',
			'_type' => 'text',
		];
		
		$settings_inputs[] = ['type' => 'sectionend', 'id' => 'globkurier-inpost-end'];
		$settings_inputs[] = ['type' => 'udisectionend'];
		
		$settings_inputs[] = ['type' => 'udisectionstart'];
		
		$settings_inputs[] = [
			'title' => __( 'ORLEN Paczka', 'globkurier' ),
			'type'  => 'title',
		];
		
		
		$ruchValue         = get_option('globkurier')[ 'ruch_active' ] ?? '';
		$settings_inputs[] = [
			'title'   => __( 'Włącz obsługę ORLEN Paczka', 'globkurier' ),
			'name'    => 'globkurier[ruch_active]',
			'id'      => 'globkurier[ruch_active]',
			'value'   => $ruchValue,
			'type'    => 'select',
			'options' => [
				0 => __('NIE', 'globkurier'),
				1 => __('TAK', 'globkurier'),
			],
		];
		
		$settings_inputs[] = [
			'title' => '',
			'name'  => 'updateRuch',
			'id'    => 'updateRuch',
			'class' => 'updateRuchContainer',
			'value' => '',
			'style' => ($ruchValue == 0) ? 'style="display:none"' : '',
			'type'  => 'udiHiddenUpdateRuchBtn',
		];
		
		$settings_inputs[] = [
			'title'   => __('Wymuś aktualizację punktów Orlen jeśli starsze niż 1 dzień', 'globkurier'),
			'name'    => 'globkurier[ruch_points_valid_time_checker_is_active]',
			'id'      => 'globkurier[ruch_points_valid_time_checker_is_active]',
			'value'   => get_option('globkurier')[ 'ruch_points_valid_time_checker_is_active' ] ?? 0,
			'type'    => 'select',
			'options' => [
				0 => __('NIE', 'globkurier'),
				1 => __('TAK', 'globkurier'),
			],
		];
		
		$settings_inputs[] = [
			'title'   => __('Zapisz punkty Orlen w pliku json', 'globkurier'),
			'name'    => 'globkurier[storeRuchPointsInFile]',
			'id'      => 'globkurier[storeRuchPointsInFile]',
			'value'   => get_option('globkurier')[ 'storeRuchPointsInFile' ] ?? 1,
			'type'    => 'select',
			'options' => [
				0 => __('NIE', 'globkurier'),
				1 => __('TAK', 'globkurier'),
			],
		];
		
		$settings_inputs[] = [
			'title'   => __('Wybierz przewoźnika do obsługi ORLEN Paczka', 'globkurier'),
			'name'    => 'globkurier[ruch_method]',
			'id'      => 'globkurier[ruch_method]',
			'value'   => get_option('globkurier')[ 'ruch_method' ] ?? '',
			'type'    => 'select',
			'options' => $this->globKurier->wcShippingMethods()->getArray(),
		];
		
		$settings_inputs[] = ['type' => 'sectionend', 'id' => 'globkurier-ruch-end'];
		$settings_inputs[] = ['type' => 'udisectionend'];
		
		return $settings_inputs;
	}
	
	public function afterShippingMethodSelected( $method, $index ){
		
		global $globKurier;
		
		if( is_cart() ){
			return;
		}
		
		$googleMapsAPIKey = $globKurier->settings('googleMapApiKey');
		
		if (! empty($googleMapsAPIKey)) {
			return;
		}
		
		$chosenShippingMethods = WC()->session->get('chosen_shipping_methods');
		
		$methodId = $method->get_id();
		
		if ($chosenShippingMethods[ 0 ] == $methodId) {
			
			$globkurierInpost = [
				'active'   => $globKurier->settings('inpost_active') ?? '',
				'methodId' => $globKurier->settings('inpost_method') ?? '',
			];
			
			$globkurierRuch = [
				'active'   => $globKurier->settings('ruch_active') ?? '',
				'methodId' => $globKurier->settings('ruch_method') ?? '',
			];
			
			if ($globkurierInpost[ 'active' ] && $globkurierInpost[ 'methodId' ] === $methodId) {
				$inpost_id  = WC()->session->get('globkurier_inpost_selected_point_id') ?? '';
				$inpost_val = WC()->session->get('globkurier_inpost_selected_point_value') ?? '';
				
				$allPoints = $globKurier->inpost()->getAllPoints();
				
				?>
				</li>
				<div class="globkurier-inpost-container">
					<input type="hidden" name="globkurier_method_id" id="globkurier_method_id" value="<?php echo $methodId ?>">

					<input type="hidden" name="globkurier_inpost_input" id="globkurier_inpost_input" value="<?php echo $inpost_val ?>" required>
					<input type="hidden" name="globkurier_inpost_input_hidden_value" id="globkurier_inpost_input_hidden_value" value="<?php echo $inpost_id ?>" required>

					<select style="width: 100%; display: none" class="udi-select2" id="udi-select-inpost" name="globkurier_inpost_input_value">
						<?php
//						foreach( $allPoints as $point ){
//							echo "<option value='".$point['id']."'>".$point['value']."</option>";
//						}
						?>
					</select>

					<script>
						( function ( $ ) {
							$( function () {
								
								const globkurierInput = '#globkurier_inpost_input';
								const globkurierInputHiddenValue = '#globkurier_inpost_input_hidden_value';
								const ajaxurl = data[ 'ajaxUrl' ];
								const saveSessionAction = 'globkurierSaveInpostPointsSession';
								
								function gkSaveSession( d ) {
									$.post( {
										url: ajaxurl,
										dataType: 'json',
										minLength: 3,
										data: {
											action: saveSessionAction,
											id: d.id,
											value: d.value || d.text,
										},
									} );
								}
								function matchStart( params, data ) {
									params.term = params.term || '';
									if ( data.text.toUpperCase().indexOf( params.term.toUpperCase() ) == 0 ) {
										return data;
									}
									return null;
								}
								
								$( document ).find( '.udi-select2#udi-select-inpost' ).select2( {
									placeholder: 'Znajdź punkt dostawy',
			                         // matcher: function(params, data) {
				                     //     return matchStart(params, data);
			                         // },
									language: {
										searching: function () {
											return 'Szukaj Paczkomat InPost';
										},
										inputTooShort: function () {
											return 'Wpisz miasto';
										},
										noResults: function () {
											return 'Brak wyników';
										},
										errorLoading: function () {
											return 'Szukanie...';
										},
										loadingMore: function () {
											return 'Szukanie...';
										},
									},
			                         ajax: {
				                         url: data[ 'ajaxUrl' ],
				                         dataType: 'json',
				                         data: function ( params ) {
					                         return {
						                         city: params.term,
						                         action: 'globkurierGetInpostPointsSelect2',
					                         };
				                         },
				                         processResults: function ( data ) {
					                         let parsedData = JSON.parse( data );
					
					                         let options = [];
					                         if ( parsedData ) {
						                         $.each( parsedData, function ( index, data ) {
							                         options.push( {
								                         id: data.id,
								                         text: data.label,
								                         latitude: data.latitude,
								                         longitude: data.longitude,
								                         city: data.city,
								                         address: data.address,
								                         openingHours: data.openingHours,
							                         } );
						                         } );
					                         }
					                         return {
						                         results: options
					                         };
				                         },
				                         cache: true
			                         },
									minimumInputLength: 3,
								} ).on( 'select2:select', function ( e ) {
				                         let option = $(e.params.data)[0];
									
				                         $( globkurierInput ).val( option.text );
				                         $( globkurierInputHiddenValue ).val( option.id );
									
									gkSaveSession( {
					                         id: option.id,
					                         value: option.text,
									} );
								} );
								
								<?php if( isset($inpost_id) && $inpost_id != '' ){?>
								$( document ).find( '.globkurier-inpost-container .select2-selection__rendered' ).text( '<?php echo $inpost_val ?>' );
								<?php } ?>
								
							} );
						} )( jQuery );
					</script>
				</div>
				<li>
				<?php
			}
			
			if ($globkurierRuch[ 'active' ] && $globkurierRuch[ 'methodId' ] === $methodId) {
				$r_id  = WC()->session->get('globkurier_ruch_selected_point_id') ?? '';
				$r_val = WC()->session->get('globkurier_ruch_selected_point_value') ?? '';
				
//				$allPoints = $globKurier->ruch()->getAllPoints( );
				
				?>
				</li>
				
				<div class="globkurier-ruch-container">
					<input type="hidden" name="globkurier_method_id" id="globkurier_method_id" value="<?php echo $methodId ?>">
					<input type="hidden" name="globkurier_ruch_input" id="globkurier_ruch_input" value="<?php echo $r_val ?>" required>
					<input type="hidden" name="globkurier_ruch_input_hidden_value" id="globkurier_ruch_input_hidden_value" value="<?php echo $r_id ?>" required>

					<select style="width: 100%; display: none" class="udi-select2" id="udi-select-ruch" name="globkurier_ruch_input_value">
						<option></option>
						<?php
						foreach( $allPoints ?? [] as $point ){
							echo "<option value='".$point[ 'id' ]."'>".$point[ 'value' ]."</option>";
						}
						?>
					</select>
					<script>
						( function ( $ ) {
							$( function () {
								
								const ajaxurl = data[ 'ajaxUrl' ];
								
								const globkurierInput = '#globkurier_ruch_input';
								const globkurierInputHiddenValue = '#globkurier_ruch_input_hidden_value';
								const saveSessionAction = 'globkurierSaveRuchPointsSession';
								
								function matchStart( params, data ) {
									params.term = params.term || '';
									if ( data.text.toUpperCase().indexOf( params.term.toUpperCase() ) == 0 ) {
										return data;
									}
									return null;
								}
								function gkSaveSession( d ) {
									$.post( {
										url: ajaxurl,
										dataType: 'json',
										minLength: 3,
										data: {
											action: saveSessionAction,
											id: d.id,
											value: d.value || d.text,
										},
									} );
								}
								
								$( document ).find( '.udi-select2#udi-select-ruch' ).select2( {
									placeholder: 'Znajdź punkt dostawy',
									language: {
										searching: function () {
											return 'Szukaj Paczka w RUCHu';
										},
										inputTooShort: function () {
											return 'Wpisz miasto';
										},
										noResults: function () {
											return 'Brak wyników';
										},
										errorLoading: function () {
											return 'Szukanie...';
										},
										loadingMore: function () {
											return 'Szukanie...';
										},
									},
									minimumInputLength: 3,
									ajax: {
										url: data[ 'ajaxUrl' ],
										dataType: 'json',
										data: function ( params ) {
											return {
												city: params.term,
												action: 'globkurierGetRuchPointsSelect2',
											};
										},
										processResults: function ( data ) {
											let parsedData = JSON.parse( data );
											
											let options = [];
											if ( parsedData ) {
												$.each( parsedData, function ( index, data ) {
													options.push( {
														id: data.id,
														text: data.label,
														latitude: data.latitude,
														longitude: data.longitude,
														city: data.city,
														address: data.address,
														openingHours: data.openingHours,
													} );
												} );
											}
											return {
												results: options
											};
										},
										cache: true
									},
								} ).on( 'select2:select', function ( e ) {
									let option = $( e.params.data );
									
									$( globkurierInput ).val( option[0].text );
									$( globkurierInputHiddenValue ).val( option[0].id );
									
									gkSaveSession( {
										id: option[0].id,
										value: option[0].text,
									} );
								} );
								
								
								// $( document ).find( '.udi-select2#udi-select-ruch' ).select2( {
								// 	placeholder: 'Znajdź punkt dostawy',
								// 	language: {
								// 		searching: function () {
								// 			return 'Szukaj Paczka w RUCHu';
								// 		},
								// 		inputTooShort: function () {
								// 			return 'Wpisz miasto';
								// 		},
								// 		noResults: function () {
								// 			return 'Brak wyników';
								// 		},
								// 		errorLoading: function () {
								// 			return 'Szukanie...';
								// 		},
								// 		loadingMore: function () {
								// 			return 'Szukanie...';
								// 		},
								// 	},
								// 	matcher: function(params, data) {
								// 		return matchStart(params, data);
								// 	},
								// 	minimumInputLength: 3,
								// } ).on( 'select2:select', function ( e ) {
								// 	let option = $(e.params.data.element);
								//
								// 	$( globkurierInput ).val( option[0].text );
								// 	$( globkurierInputHiddenValue ).val( option[0].value );
								//
								// 	gkSaveSession( {
								// 		id: option[0].value,
								// 		value: option[0].text,
								// 	} );
								// } );
								
								
								<?php if( isset($r_val) && $r_val != '' ){?>
								$( document ).find( '.globkurier-ruch-container .select2-selection__rendered' ).text( '<?php echo $r_val ?>' );
								<?php } ?>
								
							} );
						} )( jQuery );
					</script>
				</div>
				<li>
				<?php
			}
		
		}
		
	}
	
	public function globkurier_woocommerce_after_checkout_validation( $fields, $errors ){
		
		$methodId = $_POST[ 'globkurier_method_id' ];
		
		global $globKurier;
		
		$globkurierInpost = [
			'active'   => $globKurier->settings('inpost_active') ?? '',
			'methodId' => $globKurier->settings('inpost_method') ?? '',
		];
		
		$globkurierRuch = [
			'active'   => $globKurier->settings('ruch_active') ?? '',
			'methodId' => $globKurier->settings('ruch_method') ?? '',
		];
		
		if ($globkurierInpost[ 'active' ] && $globkurierInpost[ 'methodId' ] === $methodId) {
			if (empty($_POST[ 'globkurier_inpost_input' ]) || empty($_POST[ 'globkurier_inpost_input_hidden_value' ])) {
				$errors->add('required-field', __('<strong>Paczkomat InPost</strong> jest niepoprawny', 'globkurier'));
			}
		}
		
		if ($globkurierRuch[ 'active' ] && $globkurierRuch[ 'methodId' ] === $methodId) {
			if (empty($_POST[ 'globkurier_ruch_input' ]) || empty($_POST[ 'globkurier_ruch_input_hidden_value' ])) {
				$errors->add('required-field', __('<strong>Punkt Orlen Paczki</strong> jest niepoprawny', 'globkurier'));
			}
		}
		
	}
	
	public function globkurier_woocommerce_admin_order_items_after_line_items( $item_id, $item ){
		
		if ($item instanceof WC_Order_Item_Shipping) {
			
			$order_id = get_the_ID();
			
			$methodId = $item->get_method_id().':'.$item->get_instance_id();
			
			global $globKurier;
			
			$globkurierInpost = [
				'active'   => $globKurier->settings('inpost_active') ?? '',
				'methodId' => $globKurier->settings('inpost_method') ?? '',
			];
			
			$globkurierRuch = [
				'active'   => $globKurier->settings('ruch_active') ?? '',
				'methodId' => $globKurier->settings('ruch_method') ?? '',
			];
			
			if ($globkurierInpost[ 'active' ] && $globkurierInpost[ 'methodId' ] === $methodId) {
				$id    = get_post_meta($order_id, 'globkurier_inpost_id', true);
				$value = get_post_meta($order_id, 'globkurier_inpost_input_hidden_value', true);
				
				?>
				<div class="view">
					<table cellspacing="0" class="display_meta">
						<tbody>
						<tr>
							<th><?php echo __( 'Paczkomat', 'globkurier' ) ?>:</th>
							<td>
								<p><?php echo $id ?></p>
							</td>
						</tr>
						</tbody>
					</table>
				</div>
				<?php
			}
			
			if ($globkurierRuch[ 'active' ] && $globkurierRuch[ 'methodId' ] === $methodId) {
				$id    = get_post_meta($order_id, 'globkurier_ruch_id', true);
				$value = get_post_meta($order_id, 'globkurier_ruch_input_hidden_value', true);
				?>
				<div class="view">
					<table cellspacing="0" class="display_meta">
						<tbody>
						<tr>
							<th><?php echo __( 'Punkt Paczka Orlen', 'globkurier' ) ?>:</th>
							<td><p><?php echo $id ?></p>
							</td>
						</tr>
						</tbody>
					</table>
				</div>
				<?php
			}
			
		}
		
	}
	
	public function globkurier_woocommerce_checkout_create_order( $order_id, $data ){
		
		$methodId = $data[ 'shipping_method' ][ 0 ] ?? '';
		
		global $globKurier;
		
		$globkurierInpost = [
			'active'   => $globKurier->settings('inpost_active') ?? '',
			'methodId' => $globKurier->settings('inpost_method') ?? '',
		];
		
		$globkurierRuch = [
			'active'   => $globKurier->settings('ruch_active') ?? '',
			'methodId' => $globKurier->settings('ruch_method') ?? '',
		];
		
		if ($globkurierInpost[ 'active' ] && $globkurierInpost[ 'methodId' ] === $methodId) {
			update_post_meta($order_id, 'globkurier_inpost_id', esc_attr(htmlspecialchars($_POST[ 'globkurier_inpost_input' ])));
			update_post_meta($order_id, 'globkurier_inpost_value', esc_attr(htmlspecialchars($_POST[ 'globkurier_inpost_input_hidden_value' ])));
		}
		
		if ($globkurierRuch[ 'active' ] && $globkurierRuch[ 'methodId' ] === $methodId) {
			update_post_meta($order_id, 'globkurier_ruch_id', esc_attr(htmlspecialchars($_POST[ 'globkurier_ruch_input' ])));
			update_post_meta($order_id, 'globkurier_ruch_value', esc_attr(htmlspecialchars($_POST[ 'globkurier_ruch_input_hidden_value' ])));
		}
		
	}
	
}