<?php

namespace PostenBringCheckout\checkout;

use PostenBringCheckout\admin\PostenBringImages;
use PostenBringCheckout\checkout\block\CartBlock;
use PostenBringCheckout\checkout\block\CheckoutBlock;
use Automattic\WooCommerce\Blocks\Integrations\IntegrationRegistry;
use PostenBringCheckout\checkout\block\CheckoutSummaryBlock;
use PostenBringCheckout\checkout\integrations\dintero\DinteroIntegration;
use PostenBringCheckout\checkout\integrations\shipmondo\ShipmondoIntegration;
use WC_Order;
use WP_REST_Request;

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

/**
 * Public block initialization
 *
 * Class responsible for initializing the Posten Bring Checkout plugin block
 *
 * @since 0.0.1
 */
class PostenBringCheckoutPublic {

	/**
	 * Register Posten Bring Checkout blocks
	 *
	 * @param IntegrationRegistry $integration_registry Integration registry.
	 * @since 0.0.1
	 */
	public function register_posten_bring_checkout_block( IntegrationRegistry $integration_registry ): void {
		$integration_registry->register( new CheckoutBlock() );
		$integration_registry->register( new CheckoutSummaryBlock() );
	}

	/**
	 * Register Posten Bring Checkout cart block
	 *
	 * @param IntegrationRegistry $integration_registry Integration registry.
	 * @since 0.0.1
	 */
	public function register_posten_bring_cart_block( IntegrationRegistry $integration_registry ): void {
		$integration_registry->register( new CartBlock() );
	}

	/**
	 * Registers the slug as a block category with WordPress.
	 *
	 * @param array $categories WordPress block categories.
	 * @since 0.0.1
	 */
	public function register_posten_bring_checkout_block_category( array $categories ): array {
		return array_merge(
			$categories,
			array(
				array(
					'slug'  => 'posten-bring-checkout',
					'title' => __( 'Posten Bring Checkout Blocks', 'posten-bring-checkout' ),
				),
			)
		);
	}

	/**
	 * Registers our custom checkout schema extensions as order metadata
	 *
	 * @param WC_Order        $order WooCommerce order.
	 * @param WP_REST_Request $request Order request.
	 * @since 0.0.1
	 */
	public function register_order_meta_data_from_checkout_extension_data( $order, $request ): void {
		$extensions = $request['extensions']['posten-bring-checkout'];
		if ( isset( $extensions ) ) {
			$pickup_point_id = $extensions['selectedBringPickupPointId'] ?? null;
			$delivery_date   = $extensions['selectedBringDeliveryDate'] ?? null;
			$shipping_date   = $extensions['selectedBringDeliveryShippingDate'] ?? null;

			if ( ! empty( $pickup_point_id ) ) {
				$this::enrich_order_with_selected_pickup_point( $order, $pickup_point_id );
			} elseif ( ! empty( $delivery_date ) && ! empty( $shipping_date ) ) {
				$this::enrich_order_with_selected_delivery_date( $order, $delivery_date, $shipping_date);
			} else {
				$this::enrich_order_with_data_from_other_plugins( $order );
			}
		}
	}

	public function send_block_attributes_to_blocks( $blocks ) {
		$blocks[] = 'bring/posten-bring-checkout';
		$blocks[] = 'bring/posten-bring-checkout-summary';
		$blocks[] = 'bring/posten-bring-checkout-cart';
		return $blocks;
	}

	public function add_pickup_point_selector_script() {
		if ( is_checkout() ) {
			$checkout_page_id = wc_get_page_id( 'checkout' );
			if ( ! has_block( 'woocommerce/checkout', get_post_field( 'post_content', $checkout_page_id ) ) ) {
				wp_enqueue_script( 'posten-bring-checkout', plugin_dir_url( dirname( __FILE__ ) ) . 'checkout/js/posten-bring-checkout.js', array( 'jquery' ), '1', true );
				wp_enqueue_style( 'posten-bring-checkout', plugin_dir_url( dirname( __FILE__ ) ) . 'checkout/css/posten-bring-checkout.css', array(), '1' );
				wp_localize_script('posten-bring-checkout', 'PostenBringCheckout', array( 'cssUrl' => plugin_dir_url( dirname( __FILE__ ) ) . 'checkout/css/posten-bring-checkout.css' ) );
			}

			$address_autocomplete_enabled = get_option( 'woocommerce_address_autocomplete_enabled' ) === 'yes';
			if ( $address_autocomplete_enabled ) {
				wp_enqueue_script( 'posten-bring-checkout-address-provider', plugin_dir_url( dirname( __FILE__ ) ) . 'checkout/js/posten-bring-checkout-address-provider.js', array( 'wc-address-autocomplete' ), '1.0.0', true);
				wp_localize_script(
					'posten-bring-checkout-address-provider',
					'PostenBringCheckoutAddressProvider',
					array(
						'nonce' => wp_create_nonce('wp_rest'),
						'apiUrl' => rest_url( 'posten-bring-checkout/v1/' )
					)
				);
			}
		}

		if ( is_cart() ) {
			$cart_page_id = wc_get_page_id( 'cart' );
			if ( ! has_block( 'woocommerce/cart', get_post_field( 'post_content', $cart_page_id ) ) ) {
				wp_enqueue_script( 'posten-bring-checkout', plugin_dir_url( dirname( __FILE__ ) ) . 'checkout/js/posten-bring-checkout.js', array( 'jquery' ), '1', true );
				wp_enqueue_style( 'posten-bring-checkout', plugin_dir_url( dirname( __FILE__ ) ) . 'checkout/css/posten-bring-checkout.css', array(), '1' );
				wp_localize_script('posten-bring-checkout', 'PostenBringCheckout', array( 'cssUrl' => plugin_dir_url( dirname( __FILE__ ) ) . 'checkout/css/posten-bring-checkout.css' ) );
			}
		}
	}

	public function display_free_when_shipping_is_free( $label, $rate ) {
		if ( str_starts_with($rate->id, 'posten-bring-checkout-' ) ) {
			$has_cost = floatval( $rate->get_cost() ) > 0;
			if ( $has_cost ) {
				return $label;
			}

			$free_label = sprintf(
				'<span class="woocommerce-Price-amount amount"><bdi>%s</bdi></span>',
				esc_html__( 'FREE', 'posten-bring-checkout' )
			);

			return trim( $rate->get_label() . ': ' . $free_label );
		} else {
			return $label;
		}
	}

	public function add_pickup_point_selector_to_shortcode_checkout( $shipping_rate , $index ) {
		if ( $shipping_rate->get_id() === 'posten-bring-checkout-pickup-point' || $shipping_rate->get_id() === 'posten-bring-checkout-parcel-locker' ) {
			$dark_mode = get_option('posten-bring-checkout-dark-mode');
			$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
			$meta_data = $shipping_rate->get_meta_data();
			$brand = strtolower( $meta_data['brand'] ?? '');
			$pickup_points = $meta_data['pickup_points'];

			$default_display_name = !empty($pickup_points) ? $pickup_points[0]['displayName'] : $meta_data['service_name'];
			$default_id = !empty($pickup_points) ? $pickup_points[0]['id'] : '';
			$default_eta = !empty($pickup_points) ? $pickup_points[0]['leadTime'] : '';
			$description = $meta_data['service_description'] ?? '';
			$environmental_data = $meta_data['environmental_data'] ?? null;

			if ( isset($chosen_shipping_methods[$index]) && $chosen_shipping_methods[$index] === $shipping_rate->get_id() ) {
				?>
				<div id="posten-bring-checkout-pp-shadow-container">
					<div class="posten-bring-checkout-container <?php echo esc_attr($brand); ?> <?php echo esc_attr($dark_mode ? 'dark' : ''); ?>" >
						<div>
							<div class="selected">
								<span class="name">
									<span id="pp-name"><?php echo esc_html($default_display_name); ?></span>
									<?php
									if ($brand === 'bring') {
										?>
										<span class="dot">•</span>
										<span id="pp-distance" class="distance"><?php echo esc_html($pickup_points[0]['distance'] . ' km'); ?></span>
										<?php
									}
									?>
								</span>
								<div>
									<img class="logo" src="<?php echo esc_url(PostenBringImages::get_logo($brand)); ?>" alt=""/>
								</div>
							</div>
							<?php
							if (!empty($default_eta)) {
								?>
								<div id="pp-description" class="leadtime">
									<?php echo esc_html($default_eta['description'] ?? '') ?>
								</div>
								<?php
							}
							?>
							<div class="address">
								<span id="pp-address"><?php echo esc_html($pickup_points[0]['address']) ?></span>
								<span id="pp-opening-hours"><?php echo esc_html(( $pickup_points[0]['open247'] ?? false ) ? $pickup_points[0]['lockerDescription'] : $pickup_points[0]['openingHours']) ?></span>
							</div>
							<?php
							if ( ! empty( $pickup_points ) ) {
								?>
								<button type="button" id="choose-pickup-point" class="button__plain"><?php echo esc_html(__('Choose pickup point', 'posten-bring-checkout')); ?></button>
								<?php
							}
							?>

							<p class="service-description"><?php echo esc_html( $description ); ?></p>
							<?php
							if ( !empty( $environmental_data ) && $environmental_data['fossilFree']) {
								?>
								<div class="environmental">
									<img src="<?php echo esc_url( $environmental_data['tagUrl'] )?>" alt="" />
								</div>
								<?php
							}
							?>
						</div>
						<div id="posten-bring-checkout-pickup-points" class="<?php echo esc_attr($brand); ?>" aria-labelledby="posten-bring-checkout-heading" style="display: none">
							<div class="content-container">
								<div class="pickup-point-list">
									<fieldset>
										<legend><?php echo esc_html(__('Choose pickup point', 'posten-bring-checkout')); ?></legend>
										<?php
										foreach ($pickup_points as $index_counter => $pickup_point) :
											$is_default_selected = $pickup_point['id'] === $default_id;
											$opening_hours = ( $pickup_point['open247'] ?? false ) ? $pickup_point['lockerDescription'] : $pickup_point['openingHours'];
											?>
											<div class="posten-bring-checkout-radio <?php echo $index_counter > 4 ? 'hidden' : ''; ?>">
												<label for="<?php echo 'pp_' . esc_attr($pickup_point['id']); ?>">
													<input id="<?php echo 'pp_' . esc_attr($pickup_point['id']); ?>"
														   type="radio"
														   name="posten-bring-checkout-pickuppoint"
														   class="radio__checkmark"
														   value="<?php echo esc_attr($pickup_point['id']); ?>"
														   data-display-name="<?php echo esc_attr($pickup_point['displayName']); ?>"
														   data-description="<?php echo esc_attr($pickup_point['leadTime']['description'] ?? ''); ?>"
														   data-address="<?php echo esc_attr($pickup_point['address']); ?>"
														   data-opening-hours="<?php echo esc_attr($opening_hours); ?>"
														   data-distance="<?php echo esc_attr(($pickup_point['distance'] ?? '') . ' km'); ?>"
														<?php echo $is_default_selected ? 'checked' : ''; ?>
													/>
													<span class="name">
														<?php echo esc_html($pickup_point['displayName']); ?>
														<span class="dot">•</span>
														<span class="distance"><?php echo esc_html(($pickup_point['distance'] ?? '') . ' km'); ?></span>
													</span>
												</label>
												<?php
												if ( ! empty ($pickup_point['leadTime']) ) {
													?>
													<div class="leadtime"><?php echo esc_html( $pickup_point['leadTime']['description'] ?? '' ); ?></div>
													<?php
												}
												?>
												<div class="address">
													<span id="pp-address"><?php echo esc_html($pickup_point['address']) ?></span>
													<span id="pp-opening-hours"><?php echo esc_html(( $pickup_point['open247'] ?? false ) ? $pickup_point['lockerDescription'] : $pickup_point['openingHours']) ?></span>
												</div>
											</div>
										<?php
										endforeach;
										?>
										<button id="posten-bring-checkout-more" type="button" class="button__plain"><?php echo esc_html(__('Show more', 'posten-bring-checkout')); ?></button>
									</fieldset>
									<div class="posten-bring-checkout-header">
										<img class="posten-bring-checkout-logo" src="<?php echo esc_url(PostenBringImages::get_logo($brand)); ?>" alt=""/>
									</div>
								</div>
								<div class="close">
									<button id="posten-bring-checkout-close" type="button" class="button__plain"><?php echo esc_html(__('Close', 'posten-bring-checkout')); ?></button>
								</div>
							</div>
						</div>
					</div>
				</div>
				<input id="posten-bring-checkout-selected-pickuppoint" name="posten-bring-checkout-pickuppoint" type="hidden" value="<?php echo esc_attr($pickup_points[0]['id'])?>" />
				<?php
			}
		} else if ( in_array( $shipping_rate->get_id(), array('posten-bring-checkout-mailbox', 'posten-bring-checkout-parcel-to-business', 'posten-bring-checkout-groupage', 'posten-bring-checkout-pallet'), true) ) {
			$dark_mode = get_option('posten-bring-checkout-dark-mode');
			$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
			$meta_data = $shipping_rate->get_meta_data();
			$brand = strtolower( $meta_data['brand'] );
			$service_name = $meta_data['service_name'];
			$lead_time = $meta_data['lead_time'];
			$description = $meta_data['service_description'];
			$environmental_data = $meta_data['environmental_data'];

			if ( isset($chosen_shipping_methods[$index]) && $chosen_shipping_methods[$index] === $shipping_rate->id ) {
				?>
				<div id="posten-bring-checkout-general-shipping-option-shadow-container">
					<div class="posten-bring-checkout-container <?php echo esc_attr($brand); ?> <?php echo esc_attr($dark_mode ? 'dark' : ''); ?>">
						<div class="selected">
							<span class="name"><?php echo esc_html($service_name) ?></span>
							<div>
								<img class="logo" src="<?php echo esc_url(PostenBringImages::get_logo($brand)); ?>" alt=""/>
							</div>
						</div>
						<?php
						if ( !empty( $lead_time) ) {
							?>
							<div class="leadtime"><?php echo esc_html( $lead_time['description'] ) ?></div>
							<?php
						}
						?>
						<p class="service-description"><?php echo esc_html( $description ); ?></p>
						<?php
						if ( !empty( $environmental_data ) && $environmental_data['fossilFree']) {
							?>
							<div class="environmental">
								<img src="<?php echo esc_url( $environmental_data['tagUrl'] )?>" alt="" />
							</div>
							<?php
						}
						?>
					</div>
				</div>
				<?php
			}
		} else if ( $shipping_rate->get_id() === 'posten-bring-checkout-home-delivery' ) {
			$dark_mode = get_option('posten-bring-checkout-dark-mode');
			$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
			$meta_data = $shipping_rate->get_meta_data();
			$brand = strtolower( $meta_data['brand'] );
			$service_name = $meta_data['service_name'];
			$lead_time = $meta_data['lead_time'];
			$default_delivery_date = $lead_time['deliveryDateAlternatives'] ? $lead_time['deliveryDateAlternatives'][0] : '';
			$description = $meta_data['service_description'];
			$environmental_data = $meta_data['environmental_data'];
			$current_locale    = get_locale();
			if ( function_exists( 'icl_get_languages' ) ) { // If WPML is installed.
				$current_locale = apply_filters( 'wpml_current_language', NULL );
			} elseif ( function_exists( 'pll_current_language' ) ) { // If Polylang is installed.
				$current_locale = pll_current_language();
			}

			if ( isset($chosen_shipping_methods[$index]) && $chosen_shipping_methods[$index] === $shipping_rate->id ) {
				?>
				<div id="posten-bring-checkout-hd-shadow-container">
					<div class="posten-bring-checkout-container <?php echo esc_attr($brand); ?> <?php echo esc_attr($dark_mode ? 'dark' : ''); ?>">
						<div class="selected">
							<span class="name"><?php echo esc_html($service_name) ?></span>
							<div>
								<img class="logo" src="<?php echo esc_url(PostenBringImages::get_logo($brand)); ?>" alt=""/>
							</div>
						</div>
						<?php
						if ( !empty( $default_delivery_date ) ) {
							?>
							<div id="hd-delivery-date" class="leadtime">
								<?php echo esc_html( __('Delivered', 'posten-bring-checkout') . ' ' . (str_starts_with($current_locale, 'en') ? $default_delivery_date['description'] : strtolower($default_delivery_date['description'])) . ' ' . $default_delivery_date['deliveryDateFormatted'] ) ?>
							</div>
							<?php
						}
						if ( !empty( $lead_time['deliveryDateAlternatives'] ) ) {
							?>
							<button type="button" id="choose-delivery-date" class="button__plain"><?php echo esc_html(__('Choose delivery date', 'posten-bring-checkout')); ?></button>
							<?php
						}
						?>
						<p class="service-description"><?php echo esc_html( $description ); ?></p>
						<?php
						if ( !empty( $environmental_data ) && $environmental_data['fossilFree']) {
							?>
							<div class="environmental">
								<img src="<?php echo esc_url( $environmental_data['tagUrl'] )?>" alt="" />
							</div>
							<?php
						}
						?>
						<div id="posten-bring-checkout-delivery-dates" class="<?php echo esc_attr($brand); ?>" aria-labelledby="posten-bring-checkout-heading" style="display: none">
							<div class="content-container">
								<div class="delivery-dates">
									<fieldset class="alternatives">
										<legend><?php echo esc_html(__('Choose delivery date', 'posten-bring-checkout')); ?></legend>
										<?php
										foreach ($lead_time['deliveryDateAlternatives'] as $delivery_date) :
											$is_default_selected = $delivery_date['deliveryDate'] === $default_delivery_date['deliveryDate'];
											?>
											<div class="alternative radio">
												<label for="<?php echo 'alt_' . esc_attr($delivery_date['deliveryDate']); ?>">
													<input
														id="<?php echo 'alt_' . esc_attr($delivery_date['deliveryDate']); ?>"
														type="radio"
														name="delivery_date"
														class="radio__checkmark"
														value="<?php echo esc_attr($delivery_date['deliveryDate']); ?>"
														data-description="<?php echo esc_attr( __('Delivered', 'posten-bring-checkout') . ' ' . (str_starts_with($current_locale, 'en') ? $delivery_date['description'] : strtolower($delivery_date['description'])) . ' ' . $delivery_date['deliveryDateFormatted']); ?>"
														data-shipping-date="<?php echo esc_attr($delivery_date['shippingDate']); ?>"
														<?php echo $is_default_selected ? 'checked' : ''; ?>
													/>
													<div class="alternative_date">
														<span style="font-size: 16px;" class="date-description"><?php echo esc_html($delivery_date['description']); ?></span>
														<span style="font-size: 12px;"><?php echo esc_html($delivery_date['deliveryDateFormatted']); ?></span>
													</div>
												</label>
											</div>
										<?php
										endforeach;
										?>
									</fieldset>
									<div class="posten-bring-checkout-header">
										<img class="posten-bring-checkout-logo" src="<?php echo esc_url(PostenBringImages::get_logo($brand)); ?>" alt=""/>
									</div>
								</div>
								<div class="close">
									<button id="posten-bring-checkout-close" type="button" class="button__plain"><?php echo esc_html(__('Close', 'posten-bring-checkout')); ?></button>
								</div>
							</div>
						</div>
					</div>
				</div>
				<input id="posten-bring-checkout-selected-delivery-date" name="posten-bring-checkout-deliverydate" type="hidden" value="<?php echo esc_attr($default_delivery_date ? $default_delivery_date['deliveryDate'] : '')?>" />
				<input id="posten-bring-checkout-selected-shipping-date" name="posten-bring-checkout-shippingdate" type="hidden" value="<?php echo esc_attr($default_delivery_date ? $default_delivery_date['shippingDate'] : '')?>" />
				<?php
			}
		}
	}

	public function set_phone_number_mandatory( $fields ) {
		$fields['shipping_phone']['required'] = true;
		return $fields;
	}

	public function add_phone_number_prefix( $posted_data ) {
		parse_str($posted_data, $parsed_data);

		if ( isset( $parsed_data['ship_to_different_address'] ) ) {
			$recipient_country = $parsed_data['ship_to_different_address'] ? $parsed_data['shipping_country'] : $parsed_data['billing_country'];
		} else {
			$recipient_country = $parsed_data['billing_country'];
		}

		$billing_phone = $parsed_data['billing_phone'];

		if (($recipient_country == 'NO' || $recipient_country == 'DK') && (empty($billing_phone) || $billing_phone == '+47' || $billing_phone == '+45')) {
			WC()->session->set('billing_phone', ($recipient_country == 'NO' ? '+47' : '+45'));
		} else if ($recipient_country != 'NO' && $recipient_country != 'DK' && ($billing_phone == '+47' || $billing_phone == '+45')) {
			WC()->session->set('billing_phone', 'empty');
		}
	}

	public function get_phone_from_session( $value, $input_name ) {
		if ($input_name === 'billing_phone') {
			$session_value = WC()->session->get('billing_phone');
			if (!empty($session_value) && $session_value != 'empty') {
				WC()->session->__unset('billing_phone');
				return $session_value;
			}
		}
		return $value;
	}

	public function refresh_billing_phone_fragment( $fragments ) {
		$session_value = WC()->session->get('billing_phone');

		if (!empty($session_value) || $session_value == 'empty') {
			ob_start();
			?>
			<input type="tel" class="input-text " name="billing_phone" id="billing_phone" placeholder="" value="<?php echo esc_attr($session_value == 'empty' ? '' : $session_value); ?>" aria-required="true" autocomplete="tel">
			<?php
			$billing_phone_fragment = ob_get_clean();
			$fragments['#billing_phone'] = $billing_phone_fragment;
			WC()->session->__unset('billing_phone');
		}
		return $fragments;
	}

	public function validate_recipient_phone_number_and_address( $data, $errors ) {
		$selected_shipping_methods = $data['shipping_method'];

		if ( isset( $selected_shipping_methods[0] ) && str_starts_with( $selected_shipping_methods[0], 'posten-bring-checkout' ) ) {
			$phone       = preg_replace( '/[^\d+]|(?<=\+)\D/', '', $data['shipping_phone'] ?? $data['billing_phone'] );
			$phone_field = empty( $data['shipping_phone'] ) ? 'billing_phone' : 'shipping_phone';
			$first_name  = $data['shipping_first_name'];
			$last_name   = $data['shipping_last_name'];
			$address_1   = $data['shipping_address_1'];
			$address_2   = $data['shipping_address_2'];
			$to_country  = $data['shipping_country'];

			$emojiRegex = '/[\x{1F600}-\x{1F64F}' .  // Emoticons
				'\x{1F300}-\x{1F5FF}' .  // Misc Symbols and Pictographs
				'\x{1F680}-\x{1F6FF}' .  // Transport and Map
				'\x{1F1E6}-\x{1F1FF}' .  // Regional indicator symbols (flags)
				'\x{2600}-\x{26FF}' .    // Misc symbols
				'\x{2700}-\x{27BF}' .    // Dingbats
				'\x{1F900}-\x{1F9FF}' .  // Supplemental Symbols and Pictographs
				'\x{1F3FB}-\x{1F3FF}' .  // Skin tone modifiers
				']+/u';                  // u flag for Unicode support

			if ( ! empty( $phone ) && ! preg_match( '/^((\+|(00))(45|46|47|358))/', $phone ) ) {
				if ( $to_country === 'SE' ) {
					if ( ! preg_match( '/^(((\+|(00))46)?(0?7)\d{8})$/', $phone ) ) {
						if ( strlen( $phone ) === 8 && ! preg_match( '/^((\+|(00))46)?(0?7)/', $phone ) && ! preg_match( '/^((\+|(00))(45|47))/', $phone ) ) {
							$errors->add( $phone_field . '_prefix_required', __( 'Please provide a phone number including country code prefix', 'posten-bring-checkout' ) . ' (' . __('e.g.', 'posten-bring-checkout') . ' +46', array( 'id' => $phone_field ) );
						}
					} elseif ( strlen( $phone ) < 11 ) {
						$errors->add( $phone_field . '_required', __( 'Phone number is required', 'posten-bring-checkout' ), array( 'id' => 'billing_phone' ) );
					}
				} elseif ( $to_country === 'FI' ) {
					if ( ! preg_match( '/^(((\+|(00))358)?(0457|04\d|050)\d{7})$/', $phone ) ) {
						if ( ( strlen( $phone ) === 10 || strlen( $phone ) === 11) && ! preg_match( '/^((\+|(00))46)?(0?7)/', $phone ) && ! preg_match( '/^((\+|(00))(45|47|358))/', $phone ) ) {
							$errors->add( $phone_field . '_prefix_required', __( 'Please provide a phone number including country code prefix', 'posten-bring-checkout' ) . ' (' . __('e.g.', 'posten-bring-checkout') . ' +46', array( 'id' => $phone_field ) );
						}
					} elseif ( strlen( $phone ) < 11 ) {
						$errors->add( $phone_field . '_required', __( 'Phone number is required', 'posten-bring-checkout' ), array( 'id' => 'billing_phone' ) );
					}
				} elseif ( in_array( $to_country, array( 'NO', 'DK', 'SJ' ) ) ) {
					if ( ! preg_match( '/^((\+|(00))(45|46|47|358))/', $phone ) ) {
						$errors->add( $phone_field . '_prefix_required', __( 'Please provide a phone number including country code prefix', 'posten-bring-checkout' ) . ' (' . __('e.g.', 'posten-bring-checkout') . ($to_country === 'NO' ? ' +47)' : ' +45)'), array( 'id' => $phone_field ) );
					} else if ( strlen( $phone ) < 11 ) {
						$errors->add( $phone_field . '_required', __( 'Phone number is required', 'posten-bring-checkout' ), array( 'id' => 'billing_phone' ) );
					}
				}
			} elseif ( in_array( $to_country, array( 'NO', 'DK', 'SJ', 'FI' ) ) && ( empty( $phone ) || strlen ( $phone ) < 11 ) ) {
				$errors->add( $phone_field . '_required', __( 'Phone number is required', 'posten-bring-checkout' ), array( 'id' => 'billing_phone' ) );
			}

			if ( ! empty( $first_name ) && preg_match($emojiRegex, $first_name) ) {
				$errors->add( 'shipping_first_name_emojis_not_supported', __( "First name can't contain emojis", 'posten-bring-checkout'), array( 'id' => 'shipping_first_name' ) );
			}

			if ( ! empty( $last_name ) && preg_match($emojiRegex, $last_name) ) {
				$errors->add( 'shipping_last_name_emojis_not_supported', __( "Last name can't contain emojis", 'posten-bring-checkout'), array( 'id' => 'shipping_last_name' ) );
			}

			if ( ! empty( $address_1 ) && preg_match($emojiRegex, $address_1) ) {
				$errors->add( 'shipping_address_1_emojis_not_supported', __( "Address can't contain emojis", 'posten-bring-checkout'), array( 'id' => 'shipping_address_1' ) );
			}

			if ( ! empty( $address_2 ) && preg_match($emojiRegex, $address_2) ) {
				$errors->add( 'shipping_address_2_emojis_not_supported', __( "Address can't contain emojis", 'posten-bring-checkout'), array( 'id' => 'shipping_address_2' ) );
			}
		}
	}

	public function register_order_meta_data_from_shortcode_checkout( $order, $data ) {
		if ( isset($_POST['woocommerce-process-checkout-nonce']) && wp_verify_nonce(sanitize_key($_POST['woocommerce-process-checkout-nonce']), 'woocommerce-process_checkout')) {
			if ( ! empty( $_POST['posten-bring-checkout-pickuppoint'] ) ) {
				$pickup_point_id = sanitize_key( $_POST['posten-bring-checkout-pickuppoint'] );
				$this::enrich_order_with_selected_pickup_point( $order, $pickup_point_id );
			}

			if ( ! empty( $_POST['posten-bring-checkout-deliverydate'] ) && ! empty( $_POST['posten-bring-checkout-shippingdate'] ) ) {
				$delivery_date = sanitize_key( $_POST['posten-bring-checkout-deliverydate'] );
				$shipping_date = sanitize_key( $_POST['posten-bring-checkout-shippingdate'] );

				$this::enrich_order_with_selected_delivery_date( $order, $delivery_date, $shipping_date);
			}

			$this::enrich_order_with_data_from_other_plugins( $order );
		}
	}

	public function add_delivery_time_to_shipping_options( $rate, $args, $shipping_method ) {
		if ( str_starts_with( $rate->get_method_id(), 'posten-bring-checkout') ) {
			if ( method_exists( $rate, 'set_delivery_time') && isset( $args['delivery_time_summary'] ) ) {
				$rate->set_delivery_time( $args['delivery_time_summary'] );
			}
		}
		return $rate;
	}

	/**
	 * Registers Posten Bring Checkout as an address provider
	 *
	 * @param array $providers List of address providers.
	 *
	 * @return array List of providers
	 * @since 1.1.36
	 */
	public function register_address_provider( $providers ) {
		if ( class_exists( 'PostenBringCheckout\checkout\address\AddressProvider' ) ) {
			/** @noinspection PhpFullyQualifiedNameUsageInspection */
			$providers[] = new \PostenBringCheckout\checkout\address\AddressProvider();
		}

		return $providers;
	}

	public static function enrich_order_with_selected_delivery_date( $order, $delivery_date, $shipping_date ) {
		$order->update_meta_data( '_posten_bring_checkout_selected_delivery_date', $delivery_date );
		$order->update_meta_data( '_posten_bring_checkout_selected_delivery_shipping_date', $shipping_date );
		$order->save();
	}

	public static function enrich_order_with_selected_pickup_point( $order, $pickup_point_id ) {
		$shipping_option = current( $order->get_shipping_methods() );
		$pickup_points   = $shipping_option->get_meta( 'pickup_points' );
		$shipmondo       = $shipping_option->get_meta( 'third_party_shipping_provider' ) == 'SHIPMONDO';

		if ( ! is_array( $pickup_points ) ) {
			  return;
		}

		$matching_pickup_points  = array_filter(
			$pickup_points,
			function ( $entry ) use ( $pickup_point_id ) {
				return isset( $entry['id'] ) && $entry['id'] == $pickup_point_id;
			}
		);

		if ( count( $matching_pickup_points ) == 1 ) {
			$order->update_meta_data( '_posten_bring_checkout_selected_pickup_point_id', $pickup_point_id );
			$order->save();

			if ( $shipmondo) {
				ShipmondoIntegration::add_pickup_point_details( current( $matching_pickup_points ), $order );
			}
		}
	}

	public static function enrich_order_with_data_from_other_plugins( $order ) {
		$selected_pickup_point = DinteroIntegration::get_selected_pickup_point( $order );

		if ( isset( $selected_pickup_point ) ) {
			self::enrich_order_with_selected_pickup_point($order, $selected_pickup_point);
		}

	}
}
