<?php

namespace PostenBringCheckout\admin;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use PostenBringCheckout\admin\api\handlers\AddressHandler;
use PostenBringCheckout\admin\api\handlers\SettingsHandler;
use PostenBringCheckout\admin\api\models\OrderItem;
use PostenBringCheckout\admin\bring\models\service\MybringServiceDetails;
use PostenBringCheckout\admin\log\RemoteLogHandler;
use Exception;
use PostenBringCheckout\admin\api\handlers\BookingHandler;
use PostenBringCheckout\admin\api\handlers\CredentialsHandler;
use PostenBringCheckout\admin\api\handlers\FeedbackHandler;
use PostenBringCheckout\admin\api\handlers\RemoteLogApiHandler;
use PostenBringCheckout\admin\api\models\OrderMapper;
use PostenBringCheckout\admin\bring\CheckoutApi;
use PostenBringCheckout\admin\bring\CredentialsService;
use PostenBringCheckout\admin\bring\models\booking\ValidationRequest;
use PostenBringCheckout\Includes\WooActivationTask;
use WC_Order;
use WC_Order_Item_Product;
use WC_Order_Item_Shipping;
use WC_Product;
use WP_Error;

/**
 * Admin/backoffice initialization
 *
 * Class responsible for initializing the Posten Bring Checkout plugin backoffice
 *
 * @since 0.0.1
 */
class Backoffice {
	/**
	 * Plugin name.
	 *
	 * @since 0.0.1
	 * @var string $plugin_name Plugin name
	 */
	private string $plugin_name;

	/**
	 * Constructor
	 *
	 * @param string $plugine_name Plugin name.
	 *
	 * @since 0.0.1
	 */
	public function __construct( string $plugine_name ) {
		$this->plugin_name = $plugine_name;
	}

	/**
	 * Enqueue admin frontend scripts
	 *
	 * This callback function will enqueue all frontend scripts required
	 *
	 * @since 0.0.1
	 */
	public function enqueue_scripts(): void {
		$style_path   = '/build/admin-index.css';
		$style_url    = plugin_dir_url( dirname( __FILE__ ) ) . $style_path;
		$admin_assets = require plugin_dir_path( dirname( __FILE__ ) ) . 'build/admin-index.asset.php';

		wp_register_style(
			'admin-styles',
			$style_url,
			array(),
			$this->get_file_version( plugin_dir_path( dirname( __FILE__ ) ) . $style_path )
		);
		wp_enqueue_style( 'admin-styles' );

		wp_register_script( $this->plugin_name, plugin_dir_url( dirname( __FILE__ ) ) . 'build/admin-index.js', $admin_assets['dependencies'], $admin_assets['version'], true );
		wp_enqueue_script( $this->plugin_name );
		wp_enqueue_script( 'bring-logo', plugin_dir_url( dirname( __FILE__ ) ) . 'admin/bring/js/bring-logo.js', array( 'jquery' ), '1', true );

		$task_assets = require plugin_dir_path( dirname( __FILE__ ) ) . 'build/tasks-index.asset.php';
		wp_register_script( 'add-posten-bring-checkout-task', plugin_dir_url( dirname( __FILE__ ) ) . 'build/tasks-index.js', $task_assets['dependencies'], $task_assets['version'], true );
		wp_enqueue_script( 'add-posten-bring-checkout-task' );

		$page = isset( $_GET['page'] ) ? sanitize_key( $_GET['page'] ) : '';
		$post_type = isset( $_GET['post_type'] ) ? sanitize_key( $_GET['post_type'] ) : '';

		if ( $page === 'wc-orders' || $post_type === 'shop_order' ) {
			wp_enqueue_script( 'posten-bring-checkout-mass-booking', plugin_dir_url( __FILE__ ) . 'js/posten-bring-checkout-mass-booking.js', array( 'jquery' ), '1', true );
			wp_enqueue_style( 'posten-bring-modal-styles', plugin_dir_url( __FILE__ ) . 'css/posten-bring-checkout-modal.css', array(), '1' );
		}

		wp_enqueue_script('posten-bring-checkout-notifications', plugin_dir_url( __FILE__ ) . 'js/posten-bring-checkout-notifications.js', array( 'jquery' ), '1', true );;
		wp_localize_script('posten-bring-checkout-notifications', 'PostenBringCheckoutNotice', [
			'ajaxurl' => admin_url('admin-ajax.php'),
			'nonce'   => wp_create_nonce('posten_bring_checkout_dismiss_notice'),
			'action'  => 'posten_bring_checkout_dismiss_notice',
		]);

		wp_set_script_translations( $this->plugin_name, 'posten-bring-checkout', plugin_dir_path( dirname( __FILE__ ) ) . 'languages' );

		$screen = get_current_screen();
		if ( $screen->id === 'plugins') {
			wp_enqueue_script('posten-bring-checkout-review', plugin_dir_url( __FILE__ ) . 'js/posten-bring-checkout-deactivate.js', array( 'jquery' ), '1', true );
			wp_enqueue_style( 'posten-bring-modal-styles', plugin_dir_url( __FILE__ ) . 'css/posten-bring-checkout-modal.css', array(), '1' );
			wp_enqueue_style('wp-components');
		}
	}

	public function check_if_block_checkout_is_active(): void {
		$page = isset( $_GET['page'] ) ? sanitize_key( $_GET['page'] ) : '';
		$path = isset( $_GET['path'] ) ? sanitize_key( $_GET['path'] ) : '';
		$tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : '';

		if ( $page === 'wc-admin' ||
			( $page === 'wc-settings'  && ( str_starts_with( $path, '/posten-bring-checkout' ) || $tab === 'integration' ) )
		) {
			$checkout_page_id = wc_get_page_id( 'checkout' );
			$blocks           = parse_blocks( get_post_field( 'post_content', $checkout_page_id ) );
			$active           = false;

			foreach ( $blocks as $block ) {
				if ( $block['blockName'] === 'woocommerce/checkout' ) {
					$active = true;
				}
			}

			$storeName       = get_option( 'blogname' );
			$storeAddress    = get_option( 'woocommerce_store_address' );
			$storeCity       = get_option( 'woocommerce_store_city' );
			$storePostcode   = get_option( 'woocommerce_store_postcode' );
			$storeRawCountry = get_option( 'woocommerce_default_country' );

			$darkModeActive = get_option( 'posten-bring-checkout-dark-mode' );

			$addressConfigured = ! empty( $storeAddress ) && ! empty( $storeCity ) && ! empty( $storePostcode ) && ! empty( $storeRawCountry ) && ! empty( $storeName );

			wp_add_inline_script(
				$this->plugin_name,
				'var shopDetails = ' . wp_json_encode(
					array(
						'checkoutBlockActive'   => $active,
						'shopAddressConfigured' => $addressConfigured,
						'darkMode'              => $darkModeActive
					)
				),
				'before',
			);
		}
	}

	public function prefetch_order(): void {
		$action = isset( $_GET['action'] ) ? sanitize_key( $_GET['action'] ) : '';
		$page = isset( $_GET['page'] ) ? sanitize_key( $_GET['page'] ) : '';
		$post = isset( $_GET['post'] ) ? sanitize_key( $_GET['post'] ) : null;
		$id = isset( $_GET['id'] ) ? sanitize_key( $_GET['id'] ) : null;

		if ( $action === 'edit' &&
			( $page === 'wc-orders' && !empty( $id ) ) ||
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			( isset( $_SERVER['REQUEST_URI'] ) && strpos($_SERVER['REQUEST_URI'], 'post.php') !== false && !empty( $post ) )
		) {
			$order_id = $id ?? $post;

			$wc_order = wc_get_order( intval( $order_id ) );

			if ( ! $wc_order || $wc_order instanceof WC_Order_Refund ) {
				return;
			}

			$mybring_bookings = $wc_order->get_meta( 'mybring_bookings' );
			if ( empty( $mybring_bookings ) ) {
				$mybring_bookings = array();
			}

			try {
				$validation_response     = CheckoutApi::get_instance()->validateOrders( new ValidationRequest( array( $wc_order ) ) );
				$order_validation_errors = $validation_response->getOrder( $wc_order->get_id() );
				$order                   = OrderMapper::mapToOrder( $wc_order, $mybring_bookings, $order_validation_errors );
				if ( ! empty( $order->to_country ) && ! empty ( $order->from_country ) ) {
					$customers_and_services  = CheckoutApi::get_instance()->getBookingCustomersAndServices( $order->from_country, $order->to_country );
					$shipping_options        = CheckoutApi::get_instance()->get_shipping_options( $order->from_country, $order->to_country );

					$shipping_options = array_filter(
						$shipping_options,
						function ( MybringServiceDetails $shipping_option ) use ( $order ) {
							if ( $shipping_option->service_id == '3584' ) {
								$total_weight_in_kgs = ($order->total_weight?? 0) / 1000;
								return $shipping_option->max_weight_in_kgs >= $total_weight_in_kgs;
							} else {
								$overweight_items = array_filter( $order->items, function ( OrderItem $item ) use ( $shipping_option) {
									return ($item->weight_in_grams / 1000) > $shipping_option->max_weight_in_kgs;
								});

								return empty($overweight_items);
							}
						}
					);
				} else {
					$customers_and_services = array();
					$shipping_options       = array();
					wc_get_logger()->warning(
						"Order $order_id with no origin or destination country set. Cannot fetch available customers and shipping options",
						array('source'    => 'posten-bring-checkout')
					);
				}

				if ( empty($shipping_options) ) {
					wc_get_logger()->warning(
						"No shipping options available for order $order_id which could be caused by too heavy items. Ordered item weights (in grams): " . implode(
							', ',
							array_map( function (OrderItem $item) { return $item->weight_in_grams; }, $order->items )
						),
						array('source'    => 'posten-bring-checkout')
					);
				}

				$update_available = false;

				if ( current_user_can('update_plugins' ) ) {
					$plugin_updates = get_site_transient( 'update_plugins' );
					if ( isset( $plugin_updates->response['posten-bring-checkout/posten-bring-checkout.php'] ) ) {
						$update_available = true;
					}
				}

				wp_add_inline_script(
					$this->plugin_name,
					'var prefetchedOrder = ' . wp_json_encode(
						array(
							$order_id => array(
								'order'           => $order,
								'customers'       => $customers_and_services,
								'shippingOptions' => array_values($shipping_options),
							),
							'updateAvailable' => $update_available
						)
					),
					'before',
				);
			} catch ( Exception $e ) {
				wc_get_logger()->error(
					'Failed to prefetch order - ' . esc_html($e->getMessage()),
					array(
						'source'    => 'posten-bring-checkout',
						'backtrace' => true,
					)
				);
			}
		}
	}

	/**
	 * Add all menu items
	 *
	 * This callback function will add the Posten Bring Checkout menu
	 *
	 * @since 0.0.1
	 */
	public function add_posten_bring_checkout_menu() {
		wc_admin_register_page(
			array(
				'id'         => 'posten-bring-checkout',
				'title'      => 'Posten Bring',
				'path'       => '/posten-bring-checkout',
				'capability' => 'manage_woocommerce',
				'icon'       => 'data:image/svg+xml;base64, ',
				'position'   => 58,
			)
		);

		wc_admin_register_page(
			array(
				'id'         => 'posten-bring-checkout-settings',
				'parent'     => 'posten-bring-checkout',
				'title'      => __( 'Settings', 'posten-bring-checkout' ),
				'path'       => '/posten-bring-checkout/settings',
				'capability' => 'manage_options',
				'nav_args'   => array(
					'order'  => 10,
					'parent' => 'posten-bring-checkout',
				),
			)
		);

		wc_admin_register_page(
			array(
				'id'         => 'posten-bring-checkout-faq',
				'parent'     => 'posten-bring-checkout',
				'title'      => __( 'FAQ', 'posten-bring-checkout' ),
				'path'       => '/posten-bring-checkout/faq',
				'capability' => 'manage_woocommerce',
				'nav_args'   => array(
					'order'  => 20,
					'parent' => 'posten-bring-checkout',
				),
			)
		);
	}

	/**
	 * Add settings link to plugin tile
	 *
	 * This callback function will add a settings link to the Posten Bring Checkout plugin tile
	 *
	 * @param array  $links All links.
	 * @param string $plugin_file Plugin file name.
	 *
	 * @return array Links.
	 * @since 0.0.1
	 */
	public function add_plugin_links( array $links, string $plugin_file ): array {
		if ( basename( dirname( __DIR__ ) ) . "/$this->plugin_name.php" === $plugin_file ) {
			$settings_link = array( '<a href="' . admin_url( 'admin.php?page=wc-admin&path=%2Fposten-bring-checkout' ) . '">' . __( 'Settings', 'posten-bring-checkout' ) . '</a>' );
			$links         = array_merge( $settings_link, $links );

			return $links;
		}

		return $links;
	}

	/**
	 * Register API handlers
	 *
	 * This callback function will register all admin API endpoints
	 *
	 * @since 0.0.1
	 */
	public function register_api_endpoints() {
		$credentials_handler    = new CredentialsHandler();
		$booking_handler        = new BookingHandler();
		$feedback_handler       = new FeedbackHandler();
		$remote_log_api_handler = new RemoteLogApiHandler();
		$settings_handler       = new SettingsHandler();
		$address_handler        = new AddressHandler();

		register_rest_route(
			'posten-bring-checkout',
			'/credentials',
			array(
				'methods'             => 'GET',
				'callback'            => array( $credentials_handler, 'get_credentials' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_options' );
				},
			)
		);

		register_rest_route(
			'posten-bring-checkout',
			'/credentials',
			array(
				'methods'             => 'POST',
				'callback'            => array( $credentials_handler, 'store_credentials' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_options' );
				},
			)
		);

		register_rest_route(
			'posten-bring-checkout',
			'/customers',
			array(
				'methods'             => 'GET',
				'callback'            => array( $booking_handler, 'get_booking_customers_and_services' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_woocommerce');
				},
			)
		);

		register_rest_route(
			'posten-bring-checkout',
			'/services',
			array(
				'methods'             => 'GET',
				'callback'            => array( $booking_handler, 'get_shipping_options' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_woocommerce');
				},
			)
		);

		register_rest_route(
			'posten-bring-checkout',
			'/bookings',
			array(
				'methods'             => 'GET',
				'callback'            => array( $booking_handler, 'get_orders' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_woocommerce');
				},
			)
		);

		register_rest_route(
			'posten-bring-checkout',
			'/bookings',
			array(
				'methods'             => 'POST',
				'callback'            => array( $booking_handler, 'post_order' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_woocommerce');
				},
			)
		);

		register_rest_route(
			'posten-bring-checkout',
			'/orders/(?P<orderId>\d+)',
			array(
				'methods'             => 'GET',
				'callback'            => array( $booking_handler, 'get_order' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_woocommerce');
				},
			)
		);

		register_rest_route(
			'posten-bring-checkout',
			'/labels',
			array(
				'methods'             => 'GET',
				'callback'            => array( $booking_handler, 'get_labels' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_woocommerce');
				},
			)
		);

		register_rest_route(
			'posten-bring-checkout',
			'/waybills',
			array(
				'methods'             => 'GET',
				'callback'            => array( $booking_handler, 'get_waybills' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_woocommerce');
				},
			)
		);

		register_rest_route(
			'posten-bring-checkout',
			'/feedback',
			array(
				'methods'             => 'POST',
				'callback'            => array( $feedback_handler, 'send_feedback' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_woocommerce');
				},
			)
		);

		register_rest_route(
			'posten-bring-checkout',
			'/remote-log-toggle',
			array(
				'methods'             => 'POST',
				'callback'            => array( $remote_log_api_handler, 'update_remote_log' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_options' );
				},
			)
		);

		register_rest_route(
			'posten-bring-checkout',
			'/dark-mode',
			array(
				'methods'             => 'POST',
				'callback'            => array( $settings_handler, 'update_dark_mode' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_options' );
				},
			)
		);

		register_rest_route(
			'posten-bring-checkout',
			'/remote-log-toggle',
			array(
				'methods'             => 'GET',
				'callback'            => array( $remote_log_api_handler, 'get_remote_log' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_options' );
				},
			)
		);

		register_rest_route(
			'posten-bring-checkout',
			'/v1/address-search',
			array(
				'methods'             => 'GET',
				'callback'            => array( $address_handler, 'get_address_suggestions' ),
				'permission_callback' => function( $request ) {
					$wp_rest_nonce = $request->get_header( 'X-WP-Nonce' );
					if ( $wp_rest_nonce && wp_verify_nonce( $wp_rest_nonce, 'wp_rest' ) ) {
						return true;
					}

					return new WP_Error( 'rest_forbidden', 'Invalid nonce', array( 'status' => 403 ) );
				}
			)
		);

		register_rest_route(
			'posten-bring-checkout',
			'/deactivate',
			array(
				'methods'             => 'POST',
				'callback'            => array( $feedback_handler, 'deactivation_reason' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_options' );
				}
			)
		);

		register_rest_route(
			'posten-bring-checkout',
			'/v1/address-details',
			array(
				'methods'             => 'GET',
				'callback'            => array( $address_handler, 'get_address_details' ),
				'permission_callback' => function( $request ) {
					$wp_rest_nonce = $request->get_header( 'X-WP-Nonce' );
					if ( $wp_rest_nonce && wp_verify_nonce( $wp_rest_nonce, 'wp_rest' ) ) {
						return true;
					}

					return new WP_Error( 'rest_forbidden', 'Invalid nonce', array( 'status' => 403 ) );
				}
			)
		);
	}

	/**
	 * Register WooCommerce onboarding task
	 *
	 * This callback function will register a WooCommerce extended onboarding task
	 *
	 * @since 0.0.1
	 */
	public function register_woo_onboarding_tasks() {
		require_once plugin_dir_path( __DIR__ ) . 'includes/WooActivationTask.php';
		$task_lists = \Automattic\WooCommerce\Admin\Features\OnboardingTasks\TaskLists::instance();
		$task_lists::add_task(
			'extended',
			new WooActivationTask(
				$task_lists::get_list( 'extended' )
			)
		);
	}

	/**
	 * Always prefer bundled translations when loading text domain. This prevents missing or outdated translations.
	 *
	 * @since 1.1.39
	 */
	public function always_prefer_bundled_translations( $mofile, $domain ) {
		if ( 'posten-bring-checkout' !== $domain ) {
			return $mofile;
		}

		$locale      = determine_locale();
		$plugin_mo   = plugin_dir_path( __DIR__ ) . "languages/$domain-" . $locale . '.mo';

		if ( file_exists( $plugin_mo ) ) {
			return $plugin_mo;
		}

		return $mofile;
	}

	/**
	 * Register custom Posten Bring Checkout product meta data config fields
	 *
	 * @since 0.0.1
	 */
	public function add_custom_product_meta_data() {
		global $post;
		if ( ! empty( $post->ID ) ) {
			$product = wc_get_product( $post->ID );
			$product_type = $product->get_type();

			$too_large_for_parcel_locker = $product->get_meta( '_posten_bring_checkout_too_large_for_parcel_locker' );
			$too_large_for_mailbox       = $product->get_meta( '_posten_bring_checkout_too_large_for_mailbox' );
			$disable_all                 = $product->get_meta( '_posten_bring_checkout_disable_all' );
			$requires_groupage_pallet    = $product->get_meta( '_posten_bring_checkout_always_show_groupage_pallet' );

			echo '<div class="options_group">';
			echo '<h4 class="pbc-options_heading">' . esc_html(__( 'Posten Bring Checkout - Shipping settings', 'posten-bring-checkout' )) . '</h4>';
			if ( $product_type == 'variable') {
				?>
				<span style="padding-left: 12px; font-style: italic;"><?php echo esc_html(__('These settings must be applied to each individual product variation from the variations tab.', 'posten-bring-checkout') ) ?></span>
				<?php
			} else {
				woocommerce_wp_checkbox(
					array(
						'id' => '_posten_bring_checkout_too_large_for_parcel_locker',
						'wrapper_class' => '',
						'label' => __('Too large for parcel locker', 'posten-bring-checkout'),
						'description' => __('When checked, product is treated as too large for a parcel locker. This will make all parcel locker pickup points unavailable during checkout.', 'posten-bring-checkout'),
						'desc_tip' => true,
						'value' => $too_large_for_parcel_locker,
					)
				);
				woocommerce_wp_checkbox(
					array(
						'id' => '_posten_bring_checkout_too_large_for_mailbox',
						'wrapper_class' => '',
						'label' => __('Too large for mailbox', 'posten-bring-checkout'),
						'description' => __('When checked, product is treated as too large for a mailbox. This will make the Mailbox parcel shipping option unavailable during checkout.', 'posten-bring-checkout'),
						'desc_tip' => true,
						'value' => $too_large_for_mailbox,
					)
				);
				woocommerce_wp_checkbox(
					array(
						'id' => '_posten_bring_checkout_disable_all',
						'wrapper_class' => '',
						'label' => __("Disable Posten Bring's shipping options", 'posten-bring-checkout'),
						'description' => __('When checked, all shipping options provided via Posten Bring Checkout are unavailable for this product during checkout.', 'posten-bring-checkout'),
						'desc_tip' => true,
						'value' => $disable_all,
					)
				);
				woocommerce_wp_checkbox(
					array(
						'id' => '_posten_bring_checkout_always_show_groupage_pallet',
						'wrapper_class' => '',
						'label' => __("Must be shipped as groupage or pallet", 'posten-bring-checkout'),
						'description' => __('When checked, Posten Bring Checkout will always display "Delivery to address" or "Pallet" as shipping options for this product. The shipping options must be activated in Mybring.', 'posten-bring-checkout'),
						'desc_tip' => true,
						'value' => $requires_groupage_pallet,
					)
				);
			}
			echo '</div>';
		}
	}

	/**
	 * Register custom Posten Bring Checkout product meta data config fields for product bulk edit
	 *
	 * @since 1.1.43
	 */
	public function add_custom_product_meta_data_bulk_edit() {
		$options = array(
			'' => __('— No change —', 'woocommerce'),
			'yes' => __('Yes', 'woocommerce'),
			'no' => __('No', 'woocommerce'),
		);

		?>
			<div class="inline-edit-group">
				<h4><?php esc_html_e('Posten Bring Checkout - Shipping settings', 'posten-bring-checkout' )?></h4>
				<div style="display: flex; flex-direction: column;">
					<label style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
						<span class=""><?php esc_html_e( 'Too large for parcel locker', 'posten-bring-checkout' ); ?></span>
						<select name="_posten_bring_checkout_too_large_for_parcel_locker">
							<?php
							foreach ($options as $key => $value) {
								echo '<option value="' . esc_attr($key) . '">' . esc_html($value) . '</option>';
							}
							?>
						</select>
					</label>
					<label style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
						<span class=""><?php esc_html_e( 'Too large for mailbox', 'posten-bring-checkout' ); ?></span>
						<select name="_posten_bring_checkout_too_large_for_mailbox">
							<?php
							foreach ($options as $key => $value) {
								echo '<option value="' . esc_attr($key) . '">' . esc_html($value) . '</option>';
							}
							?>
						</select>
					</label>
					<label style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
						<span class=""><?php esc_html_e( "Disable Posten Bring's shipping options", 'posten-bring-checkout' ); ?></span>
						<select name="_posten_bring_checkout_disable_all">
							<?php
							foreach ($options as $key => $value) {
								echo '<option value="' . esc_attr($key) . '">' . esc_html($value) . '</option>';
							}
							?>
						</select>
					</label>
					<label style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
						<span class=""><?php esc_html_e( "Must be shipped as groupage or pallet", 'posten-bring-checkout' ); ?></span>
						<select name="_posten_bring_checkout_always_show_groupage_pallet">
							<?php
							foreach ($options as $key => $value) {
								echo '<option value="' . esc_attr($key) . '">' . esc_html($value) . '</option>';
							}
							?>
						</select>
					</label>
				</div>
			</div>
		<?php
	}

	/**
	 * Process custom Posten Bring Checkout product meta data changes during product bulk edit
	 *
	 * @param WC_Product $product Modified product.
	 *
	 * @since 1.1.43
	 */
	public function store_custom_product_meta_data_bulk_edit( $product ) {
		$too_large_for_parcel_locker = isset( $_REQUEST['_posten_bring_checkout_too_large_for_parcel_locker'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['_posten_bring_checkout_too_large_for_parcel_locker'] ) ) : '';
		$too_large_for_mailbox       = isset( $_REQUEST['_posten_bring_checkout_too_large_for_mailbox'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['_posten_bring_checkout_too_large_for_mailbox'] ) ) : '';
		$disable_all                 = isset( $_REQUEST['_posten_bring_checkout_disable_all'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['_posten_bring_checkout_disable_all'] ) ) : '';
		$requires_groupage_pallet    = isset( $_REQUEST['_posten_bring_checkout_always_show_groupage_pallet'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['_posten_bring_checkout_always_show_groupage_pallet'] ) ) : '';
		if ( $product->is_type( 'variable' ) ) {
			foreach ( $product->get_children() as $variation_id ) {
				$this->bulk_update_product_meta_data( $variation_id , $too_large_for_parcel_locker , $too_large_for_mailbox, $disable_all, $requires_groupage_pallet );
			}
		} else {
			$this->bulk_update_product_meta_data( $product->get_id() , $too_large_for_parcel_locker , $too_large_for_mailbox, $disable_all, $requires_groupage_pallet );
		}
	}

	/**
	 * Update product or product variant meta data during product bulk edit
	 *
	 * @param string $product_id Product id or product variant id.
	 * @param string $too_large_for_parcel_locker Too large for parcel locker value.
	 * @param string $too_large_for_mailbox Too large for mailbox value.
	 * @param string $disable_all Disable all shipping options value.
	 * @param string $requires_groupage_pallet Requires groupage/pallet services value.
	 *
	 * @since 1.1.43
	 */
	private function bulk_update_product_meta_data( $product_id, $too_large_for_parcel_locker, $too_large_for_mailbox, $disable_all, $requires_groupage_pallet ) {
		if ( in_array( $too_large_for_parcel_locker, array( 'yes', 'no' ), true ) ) {
			update_post_meta( $product_id, '_posten_bring_checkout_too_large_for_parcel_locker', $too_large_for_parcel_locker );
		}
		if ( in_array( $too_large_for_mailbox, array( 'yes', 'no' ), true ) ) {
			update_post_meta( $product_id, '_posten_bring_checkout_too_large_for_mailbox', $too_large_for_mailbox );
		}
		if ( in_array( $disable_all, array( 'yes', 'no' ), true ) ) {
			update_post_meta( $product_id, '_posten_bring_checkout_disable_all', $disable_all );
		}
		if ( in_array( $requires_groupage_pallet, array( 'yes', 'no' ), true ) ) {
			update_post_meta( $product_id, '_posten_bring_checkout_always_show_groupage_pallet', $requires_groupage_pallet );
		}
	}

	/**
	 * Register custom Posten Bring Checkout product meta data config fields
	 *
	 * @since 0.0.1
	 */
	public function add_custom_product_variant_meta_data( $index, $variation_data, $variation ) {
		$product_variation = wc_get_product( $variation->ID );
		if ($product_variation) {
			?>
			<div class="options_group">
				<h4 style="margin-bottom: 0;">
					<?php echo esc_html( __( 'Posten Bring Checkout - Shipping settings', 'posten-bring-checkout' ) ); ?>
				</h4>
				<div class="woocommerce_options_panel" style="padding: 0;">
					<?php
					woocommerce_wp_checkbox(
						array(
							'id'            => '_posten_bring_checkout_too_large_for_parcel_locker[' . $index . ']',
							'class'         => 'checkbox',
							'label'         => __( 'Too large for parcel locker', 'posten-bring-checkout' ),
							'description'   => __( 'When checked, product is treated as too large for a parcel locker. This will make all parcel locker pickup points unavailable during checkout.', 'posten-bring-checkout' ),
							'desc_tip'      => true,
							'value'         => $product_variation->get_meta( '_posten_bring_checkout_too_large_for_parcel_locker' ),
						)
					);
					woocommerce_wp_checkbox(
						array(
							'id'            => '_posten_bring_checkout_too_large_for_mailbox[' . $index . ']',
							'class'         => 'checkbox',
							'label'         => __( 'Too large for mailbox', 'posten-bring-checkout' ),
							'description'   => __( 'When checked, product is treated as too large for a mailbox. This will make the Mailbox parcel shipping option unavailable during checkout.', 'posten-bring-checkout' ),
							'desc_tip'      => true,
							'value'         => $product_variation->get_meta( '_posten_bring_checkout_too_large_for_mailbox' ),
						)
					);
					woocommerce_wp_checkbox(
						array(
							'id'            => '_posten_bring_checkout_disable_all[' . $index . ']',
							'class'         => 'checkbox',
							'label'         => __( "Disable Posten Bring's shipping options", 'posten-bring-checkout' ),
							'description'   => __( 'When checked, all shipping options provided via Posten Bring Checkout are unavailable for this product during checkout.', 'posten-bring-checkout' ),
							'desc_tip'      => true,
							'value'         => $product_variation->get_meta( '_posten_bring_checkout_disable_all' ),
						)
					);
					woocommerce_wp_checkbox(
						array(
							'id'            => '_posten_bring_checkout_always_show_groupage_pallet[' . $index . ']',
							'class'         => 'checkbox',
							'label'         => __( "Must be shipped as groupage or pallet", 'posten-bring-checkout' ),
							'description'   => __( 'Posten Bring Checkout will always display "Delivery to address" or "Pallet" as shipping options for this product. The shipping options must be activated in Mybring.', 'posten-bring-checkout' ),
							'desc_tip'      => true,
							'value'         => $product_variation->get_meta( '_posten_bring_checkout_always_show_groupage_pallet' ),
						)
					);
					?>
				</div>
			</div>
			<?php
		}
	}

	/**
	 * Store custom Posten Bring Checkout product meta data
	 *
	 * @param int $post_id Product id.
	 *
	 * @since 0.0.1
	 */
	public function store_custom_product_meta_data( $post_id ) {
		$product = wc_get_product( $post_id );
		if (!$product) {
			wc_get_logger()->warning( "Requested product $post_id was not found. Could not store meta data changes", array( 'source' => 'posten-bring-checkout' ) );
			return;
		}
		$this->update_product_meta_data( $product, null );
	}

	/**
	 * Store custom Posten Bring Checkout product variant meta data
	 *
	 * @param int $variant_id Product variant id.
	 * @param int $index Index of product variant.
	 *
	 * @since 0.0.1
	 */
	public function store_custom_product_variant_meta_data( $variant_id, $index ) {
		$product = wc_get_product( $variant_id );
		if (!$product) {
			wc_get_logger()->warning( "Requested product $variant_id was not found. Could not store meta data changes", array( 'source' => 'posten-bring-checkout' ) );
			return;
		}
		$this->update_product_meta_data( $product, $index );
	}

	/**
	 * Store custom Posten Bring Checkout product and product variant meta data
	 *
	 * @param WC_Product $product Product.
	 * @param ?int $index Index of product variant. Null for other products.
	 *
	 * @since 0.0.1
	 */
	private function update_product_meta_data( $product, ?int $index ) {
		if ( (isset( $_POST['security']) && wp_verify_nonce( sanitize_key($_POST['security']), 'save-variations')) ||
			(isset( $_POST['woocommerce_meta_nonce'] ) && wp_verify_nonce( sanitize_key($_POST['woocommerce_meta_nonce']), 'woocommerce_save_data'))
		) {
			if ( isset($index) ) {
				$too_large_for_parcel_locker = isset( $_POST['_posten_bring_checkout_too_large_for_parcel_locker'][$index] ) ? 'yes' : 'no';
				$too_large_for_mailbox = isset( $_POST['_posten_bring_checkout_too_large_for_mailbox'][$index] ) ? 'yes' : 'no';
				$disable_all = isset( $_POST['_posten_bring_checkout_disable_all'][$index] ) ? 'yes' : 'no';
				$requires_groupage_pallet = isset( $_POST['_posten_bring_checkout_always_show_groupage_pallet'][$index] ) ? 'yes' : 'no';
			} else {
				$too_large_for_parcel_locker = isset( $_POST['_posten_bring_checkout_too_large_for_parcel_locker'] ) ? 'yes' : 'no';
				$too_large_for_mailbox = isset( $_POST['_posten_bring_checkout_too_large_for_mailbox'] ) ? 'yes' : 'no';
				$disable_all = isset( $_POST['_posten_bring_checkout_disable_all'] ) ? 'yes' : 'no';
				$requires_groupage_pallet = isset( $_POST['_posten_bring_checkout_always_show_groupage_pallet'] ) ? 'yes' : 'no';
			}

			$product->update_meta_data( '_posten_bring_checkout_too_large_for_parcel_locker', $too_large_for_parcel_locker );
			$product->update_meta_data( '_posten_bring_checkout_too_large_for_mailbox', $too_large_for_mailbox );
			$product->update_meta_data( '_posten_bring_checkout_disable_all', $disable_all );
			$product->update_meta_data( '_posten_bring_checkout_always_show_groupage_pallet', $requires_groupage_pallet );
			$product->save();
		}
	}

	/**
	 * Register Posten Bring shipping options
	 *
	 * @since 0.0.1
	 */
	public function register_posten_bring_shipping_options() {
		require_once plugin_dir_path( __FILE__ ) . 'bring/shipping/PostenBringCheckoutShippingOption.php';
	}

	/**
	 * Add the Posten Bring Checkout shipping options
	 *
	 * @param array $methods Shipping methods.
	 *
	 * @return array Shipping methods.
	 * @since 0.0.1
	 */
	public function add_posten_bring_shipping_options( $methods ) {
		$methods['posten-bring-checkout-shipping-option'] = '\PostenBringCheckout\admin\bring\shipping\PostenBringCheckoutShippingOption';

		return $methods;
	}

	/**
	 * Sort the Posten Bring Checkout shipping options
	 *
	 * @param array $shipping_options Shipping options.
	 * @param array $package Package.
	 *
	 * @return array Sorted shipping options.
	 * @since 0.0.1
	 */
	public function sort_shipping_options( $shipping_options, $package ) {
		$posten_bring_rates = array();
		$other_rates        = array();

		foreach ( $shipping_options as $option_id => $shipping_option ) {
			if ( str_starts_with( $option_id, 'posten-bring-checkout' ) ) {
				$posten_bring_rates[ $option_id ] = $shipping_option;
			} else {
				$other_rates[ $option_id ] = $shipping_option;
			}
		}

		uasort(
			$posten_bring_rates,
			function ( $a, $b ) {
				return $a->cost - $b->cost;
			}
		);

		return array_merge( $posten_bring_rates, $other_rates );
	}

	/**
	 * Hides our shipping rate meta fields
	 *
	 * @param array $meta_data Shipping rate meta data.
	 *
	 * @return array Meta fields to hide.
	 * @since 0.0.1
	 */
	public function hide_shipping_method_meta_data( array $meta_data ) {
		return array_merge( $meta_data, array( 'brand', 'service_name', 'service_id', 'service_description' ) );
	}

	/**
	 * Display correct service name in order preview
	 *
	 * @param array    $data Template data.
	 * @param WC_Order $order order.
	 *
	 * @return array template data.
	 * @since 0.0.1
	 */
	public function display_selected_shipping_method_in_order_preview( $data, WC_Order $order ): array {
		$shipping_method = current( $order->get_shipping_methods() );
		$id              = $shipping_method->get_method_id();

		if ( str_starts_with( $id, 'posten-bring-checkout' ) ) {
			$service_name = $shipping_method->get_meta( 'service_name' );

			$data['shipping_via']            = $service_name;
			$data['shipping_provider_bring'] = true;
		}

		return $data;
	}

	/**
	 * Load bring section on order details page
	 *
	 * @param WC_Order_Item_Shipping | WC_Order_Item_Product $item Order item.
	 * @param string                                         $item_id Order item id.
	 *
	 * @since 0.0.1
	 */
	public function load_bring_section_on_order_details_meta( $something, $item, string $item_id ): void {
		if ( $item instanceof WC_Order_Item_Shipping ) {
			echo '<div id="posten-bring-checkout-section"></div>';
		}
	}

	/**
	 * Strip the Posten/Bring prefix added during checkout before presenting it in backoffice
	 *
	 * @param mixed                  $value Current value.
	 * @param WC_Order_Item_Shipping $item The shipping order item.
	 *
	 * @return mixed Name.
	 */
	public function rename_shipping_option_on_details_page( $value, WC_Order_Item_Shipping $item ) {
		if ( ! is_string( $value ) ) {
			return $value;
		}

		$prefixes = array( 'Posten - ', 'Bring - ' );
		foreach ( $prefixes as $prefix ) {
			if ( substr( $value, 0, strlen( $prefix ) ) == $prefix ) {
				return substr( $value, strlen( $prefix ) );
			}
		}

		return $value;
	}

	/**
	 * Validate the postal code provided in shipping address
	 *
	 * @param bool   $valid Current value.
	 * @param string $postal_code The provided postal code.
	 * @param string $country The country code.
	 *
	 * @return bool Valid.
	 */
	public function validate_postal_code( bool $valid, string $postal_code, string $country ): bool {
		if ( $valid ) {
			$without_whitespaces = preg_replace( '/\s+/', '', $postal_code );
			if ( ( in_array(
				$country,
				array(
					'NO',
					'DK',
				)
			) && strlen( $without_whitespaces ) === 4 ) || ( $country === 'SE' && strlen( $without_whitespaces ) === 5 ) ) {
				try {
					$postalCodeDetails = CheckoutApi::get_instance()->get_postal_code_details( $country, $postal_code );
				$valid = $postalCodeDetails['isValid'];
				} catch ( Exception $e ) {
					wc_get_logger()->warning( esc_html($e->getMessage()), array( 'source' => 'posten-bring-checkout' ) );
				}
			}
		}

		return $valid;
	}

	/**
	 * Get the file modified time as a cache buster if we're in dev mode.
	 *
	 * @param string $file Local path to the file.
	 *
	 * @return string The cache buster value to use for the given file.
	 */
	protected function get_file_version( string $file ): string {
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG && file_exists( $file ) ) {
			return filemtime( $file );
		}

		return POSTEN_BRING_CHECKOUT_VERSION;
	}

	/**
	 * Register Posten Bring Checkout bulk action
	 *
	 * This callback function will register a Posten Bring Checkout bulk action on the order list
	 *
	 * @param array $bulk_actions Bulk actions.
	 *
	 * @return array Bulk actions.
	 * @since 0.0.1
	 */
	public function posten_bring_checkout_add_bulk_action( array $bulk_actions ) {
		$bulk_actions['posten_bring_checkout_mass_booking_bulk_action'] = __( 'Posten Bring Checkout', 'posten-bring-checkout' );

		return $bulk_actions;
	}

	public function add_massbooking_modal() {
		$screen = get_current_screen();
		if ( $screen->id !== 'woocommerce_page_wc-orders' && $screen->id !== 'edit-shop_order') {
			return;
		}
		?>
		<div id="posten-bring-custom-modal" class="posten-bring-custom-modal-overlay" aria-hidden="true">
			<div class="posten-bring-custom-modal wide">
				<button class="close-posten-bring-modal">
					<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" aria-hidden="true" focusable="false">
						<path
							d="m13.06 12 6.47-6.47-1.06-1.06L12 10.94 5.53 4.47 4.47 5.53 10.94 12l-6.47 6.47 1.06 1.06L12 13.06l6.47 6.47 1.06-1.06L13.06 12Z"></path>
					</svg>
				</button>
				<div id="posten-bring-custom-modal-content">
					<!-- React component will be mounted here -->
				</div>
			</div>
		</div>
		<?php
	}

	public function add_deactivate_modal() {
		$screen = get_current_screen();
		if ( $screen->id !== 'plugins' ) {
			return;
		}
		?>
		<div id="posten-bring-deactivate-modal" class="posten-bring-custom-modal-overlay" aria-hidden="true">
			<div class="posten-bring-custom-modal">
				<button class="close-posten-bring-modal">
					<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" aria-hidden="true" focusable="false">
						<path
							d="m13.06 12 6.47-6.47-1.06-1.06L12 10.94 5.53 4.47 4.47 5.53 10.94 12l-6.47 6.47 1.06 1.06L12 13.06l6.47 6.47 1.06-1.06L13.06 12Z"></path>
					</svg>
				</button>
				<div id="posten-bring-deactivate-modal-content">
					<!-- React component will be mounted here -->
				</div>
			</div>
		</div>
		<?php
	}

	public function add_posten_bring_booking_status_column( $columns ) {
		$columns['posten_bring_checkout_status'] = __( 'Tracking', 'posten-bring-checkout' );

		return $columns;
	}

	/**
	 * Add Tracking column to order list table
	 *
	 * This callback function will register a tracking column in the ordet list containing Bring tracking URLs
	 *
	 * @param string $column Column name.
	 * @param mixed  $post_id WP post id.
	 *
	 * @since 0.0.1
	 */
	public function add_posten_bring_booking_status_data( string $column, $post_id ): void {
		if ( 'posten_bring_checkout_status' === $column ) {
			$order = wc_get_order( $post_id );

			$custom_info = $order->get_meta( 'mybring_bookings' );

			if ( ! empty( $custom_info ) ) {
				foreach ( $custom_info as $booking ) {
					$consignmentNumber = $booking->consignmentNumber;
					$trackingUrl       = $booking->trackingUrl;
					echo '<a href="' . esc_url($trackingUrl) . '" target="_blank">' . esc_html($consignmentNumber) . '</a>';
				}
			} else {
				echo '-';
			}
		}
	}

	/**
	 * Add Shipping company filter to order list
	 *
	 * This callback function will add a shipping company filter to the order list table.
	 *
	 * @param string $order_type Order type.
	 * @param string $location Location.
	 *
	 * @since 0.0.1
	 */
	public function add_shipping_provider_filter( string $order_type, string $location ): void {
		if ( apply_filters( 'posten_bring_checkout_disable_shipping_provider_filter', false ) ) {
			return;
		}

		try {
			$shipping_provider = isset( $_GET['shipping_provider'] ) ? sanitize_key($_GET['shipping_provider'] ) : null;

			echo '<select name="shipping_provider" id="filter-by-shipping-provider">';
			echo '<option ' . selected( $shipping_provider, 'all', false ) . ' value="all">' . esc_html__( 'All shipping companies', 'posten-bring-checkout' ) . '</option>';
			echo '<option ' . selected( $shipping_provider, 'Bring', false ) . ' value="Bring">Bring</option>';
			echo '</select>';
		} catch ( Exception $e ) {
			wc_get_logger()->error(
				'An error occurred while loading shipping company filter: ' . esc_html($e->getMessage()),
				array(
					'source'    => 'posten-bring-checkout',
					'backtrace' => true,
				)
			);
		}
	}

	/**
	 * Add Bring as shipping company to new orders
	 *
	 * This callback function will add "Bring" as shipping company if the selected shipping option originates from Posten Bring Checkout
	 *
	 * @param WC_Order $wc_order Order.
	 *
	 * @since 0.0.1
	 */
	public function add_bring_as_shipping_company( WC_Order $wc_order ): void {
		try {
			$shipping_method = current( $wc_order->get_shipping_methods() );

			if ( $shipping_method ) {
				$id = $shipping_method->get_method_id();

				if ( str_starts_with( $id, 'posten-bring-checkout' ) ) {
					$wc_order->update_meta_data( '_posten_bring_checkout', true );
					$wc_order->save();
				}
			}
		} catch ( Exception $e ) {
			wc_get_logger()->error(
				'Could not tag the order. ' . esc_html($e->getMessage()),
				array(
					'source'    => 'posten-bring-checkout',
					'backtrace' => true,
				)
			);
		}
	}

	/**
	 * Dismiss notices
	 *
	 * This callback function will dismiss notices from admin pages
	 *
	 * @since 1.1.32
	 */
	public function dismiss_notice() {
		check_ajax_referer('posten_bring_checkout_dismiss_notice', 'nonce');

		if ( ! is_user_logged_in() ) {
			wp_send_json_error(['message' => 'Not logged in'], 403);
		}

		$key = isset( $_POST[ 'key' ] ) ? sanitize_key( wp_unslash( $_POST[ 'key' ] ) ) : '';
		if ( ! $key ) {
			wp_send_json_error(['message' => 'Missing key'], 400);
		}

		$dismissed = get_user_meta( get_current_user_id(), 'posten_bring_checkout_dismissed_notifications', true );
		$dismissed = is_array( $dismissed ) ? $dismissed : [];
		$dismissed[ $key ] = time();
		update_user_meta( get_current_user_id(), 'posten_bring_checkout_dismissed_notifications', $dismissed );

		wp_send_json_success();
	}

	/**
	 * Add warning notices
	 *
	 * This callback function will add warning notices to the admin pages
	 *
	 * @since 1.1.21
	 */
	public function add_warnings() {
		$dismissed = get_user_meta( get_current_user_id(), 'posten_bring_checkout_dismissed_notifications', true );
		$dismissed = is_array( $dismissed ) ? $dismissed : [];

		$data = CredentialsService::get_instance()->get_credentials_and_webshop_id();
		if ( !isset( $dismissed[ 'not-initialized' ] ) && ( empty( $data->apikey ) || empty( $data->webshop_id ) ) ) {
			?>
			<div class="notice notice-warning is-dismissible" style="display: flex; gap: 20px" data-notice-id="not-initialized">
				<img src="<?php echo esc_url( plugin_dir_url(__DIR__) . 'assets/images/Bring_logo_secondary.svg' ); ?>" alt="" style="width: 45px; margin: 8px 0"/>
				<div>
					<h4 style="margin-bottom: 0"><?php echo esc_html( __( 'Posten Bring Checkout is not initialized', 'posten-bring-checkout' ) ) ?></h4>
					<p><?php echo esc_html( __( 'To be able to use Posten Bring Checkout you have to complete the ', 'posten-bring-checkout' ) ) ?>
						<a href="<?php echo esc_attr( admin_url( 'admin.php?page=wc-settings&tab=integration&section=posten-bring-checkout' ) ) ?>">
							<?php echo esc_html( __( 'configuration', 'posten-bring-checkout' ) ) ?>
						</a>.
					</p>
				</div>
			</div>
			<?php
		}

		$vippsSettings = get_option('woocommerce_vipps_settings');
		if ( !isset( $dismissed[ 'vipps-static-shipping' ] ) && (isset( $vippsSettings['enablestaticshipping'] ) && $vippsSettings['enablestaticshipping'] == 'yes') || isset( $vippsSettings['enablestaticshipping_checkout'] ) && $vippsSettings['enablestaticshipping_checkout'] == 'yes' ) {
			?>
				<div class="notice notice-warning is-dismissible" style="display: flex; gap: 20px" data-notice-id="vipps-static-shipping">
					<img src="<?php echo esc_url( plugin_dir_url(__DIR__) . 'assets/images/Bring_logo_secondary.svg' ); ?>" alt="" style="width: 45px; margin: 8px 0"/>
					<div>
						<h4 style="margin-bottom: 0"><?php echo esc_html( __( '"Static shipping" is enabled', 'posten-bring-checkout' ) ) ?></h4>
						<p><?php echo wp_kses_post( __( '<strong>Vipps/MobilePay</strong> has been configured with "static shipping" enabled. This means that the available shipping options do not vary based on the customer\'s address. For <strong>Posten Bring Checkout</strong> to be able to display shipping options and pickup points associated with the customers address, this setting must be disabled.', 'posten-bring-checkout' ) ) ?></p>
					</div>
				</div>
			<?php
		}

		$notifications = CheckoutApi::get_instance()->get_notifications();
		if ( !empty( $notifications->errors ) ) {
			foreach ( $notifications->errors as $error ) {
				if ( !isset( $dismissed[ $error[ 'id' ] ] ) ) {
					?>
					<div class="notice notice-warning is-dismissible" style="display: flex; gap: 20px" data-notice-id="<?php echo esc_attr( $error[ 'id' ] )?>">
						<img src="<?php echo esc_url( plugin_dir_url(__DIR__) . 'assets/images/Bring_logo_secondary.svg' ); ?>" alt="" style="width: 45px; margin: 8px 0"/>
						<div>
							<h4 style="margin-bottom: 0"><?php echo esc_html( $error['title'] ) ?></h4>
							<?php echo wp_kses_post( $error['message'] ) ?>
						</div>
					</div>
					<?php
				}
			}
		}
		if ( !empty( $notifications->news ) ) {
			foreach ( $notifications->news as $news ) {
				if ( !isset( $dismissed[ $news[ 'id' ] ] ) ) {
					?>
					<div class="notice notice-info is-dismissible" style="display: flex; gap: 20px" data-notice-id="<?php echo esc_attr( $news[ 'id' ] )?>">
						<img src="<?php echo esc_url( plugin_dir_url(__DIR__) . 'assets/images/Bring_logo_secondary.svg' ); ?>" alt="" style="width: 45px; margin: 8px 0"/>
						<div>
							<h4 style="margin-bottom: 0"><?php echo esc_html( $news['title'] ) ?></h4>
							<?php echo wp_kses_post( $news['message'] ) ?>
						</div>
					</div>
					<?php
				}
			}
		}
	}

	/**
	 * Add shipping_company to order list query
	 *
	 * This callback function will shipping_company as a filter to the order list query, when shipping company is selected
	 *
	 * @param WC_Order $wc_order Order.
	 *
	 * @since 0.0.1
	 */
	public function apply_shipping_company_filter( $request ) {
		$shipping_provider = isset($_GET['shipping_provider']) ? sanitize_key($_GET['shipping_provider']) : '';
		if (!empty($shipping_provider) && $shipping_provider !== 'all') {
			$request['meta_query'][] = array(
				'key'     => '_posten_bring_checkout',
				'value'   => $shipping_provider === 'Bring',
				'compare' => '=',
			);
		}

		return $request;
	}


	function add_posten_block_to_email( $order, $sent_to_admin, $plain_text, $email ) {
		if ( 'customer_completed_order' === $email->id ) {
			$this->renderPostenHtmlBlock( $order );
		}
	}

	/**
	 * @param $order
	 * @param string $posten_image
	 * @param string $bring_image
	 * @param string $pakkeboksImage
	 * @param string $pibImage
	 * @param string $pipImage
	 * @param string $homedeliveryImage
	 *
	 * @return void
	 */
	public function renderPostenHtmlBlock( $order ): void {
		$custom_info = $order->get_meta( 'mybring_bookings' );
		if ( ! empty( $custom_info ) ) {
			$firstBooking      = reset( $custom_info );
			$consignmentNumber = $firstBooking->consignmentNumber;
			$trackingUrl       = $firstBooking->trackingUrl;
			$shopLocale        = determine_locale();

			echo '<div style="margin: 30px 0 30px 0; position:relative; background-color: #f8f8f8; border: 1px solid #f1f1f1; border-radius: 5px">';
			echo '<table class="posten-main-table" style="width: 100%; border-collapse: collapse;">';
			echo '<tr>';
			echo '<td style="vertical-align: top;">';
			echo '<img width="500" height="180" id="brand" src="' . esc_url(POSTEN_BRING_CHECKOUT_MYBRING_API_URL . '/checkout/brand/' . $consignmentNumber . '?language=' . $shopLocale) . '" onerror="this.style.display=\'none\'"/>';
			echo '</td>';
			echo '</tr>';
			echo '<tr>';
			echo '<td style="padding:0;">';
			echo '<p style="color: #333; line-height: 150%; font-size: 16px; margin: 0; padding: 0 0 30px 30px;">';
			echo esc_html(__( 'You can track your parcel here:', 'posten-bring-checkout' ) . ' ');
			echo '<a style="color:#333; text-decoration:underline" href="' . esc_url($trackingUrl) . '" target="_blank">' . esc_html($consignmentNumber) . '</a>';
			echo '</p>';
			echo '</td>';
			echo '</tr>';
			echo '</table>';
			echo '</div>';
		}
	}

	/**
	 * Add Posten Bring Checkout log handler
	 *
	 * This callback function will register a custom log handler that will forward Posten Bring Checkout related log entries to a remote API
	 *
	 * @param array $handlers Log handlers.
	 *
	 * @return array Log handlers.
	 * @since 0.0.1
	 */
	public function add_posten_bring_checkout_log_handler( array $handlers ): array {
		$handlers['posten_bring_checkout_log_handler'] = new RemoteLogHandler();
		return $handlers;
	}

	/**
	 * Shipping rate posten or Bring logo
	 *
	 * This callback function will return a Posten/Bring logo for posten/bring shipping rates
	 *
	 * @param string $img_url Current logo url.
	 * @param string $carrier Name of carrier.
	 * @param array $shipping_rate Shipping rate.
	 *
	 * @return string Logo image url.
	 * @since 0.0.1
	 */
	public function add_posten_bring_shipping_icon( $img_url, $carrier, $shipping_rate ) {
		if ( $carrier == 'posten') {
			return plugin_dir_url(__DIR__) . 'assets/images/Posten_logo_secondary.svg';
		} elseif ( $carrier == 'bring' ) {
			return plugin_dir_url(__DIR__) . 'assets/images/Bring_logo_secondary.svg';
		}
		return $img_url;
	}
}
