<?php
use Automattic\WooCommerce\Utilities\OrderUtil;
if ( ! defined('ABSPATH')) {
    exit;
}
if (class_exists('WC_MP_Shipping_Method')) {
    /**
     * Class WC_MP_Venipak_Courier_Shipping
     */
    class WC_MP_Shipping_Helper
    {
        const CARRIER_DPD = 'dpd';
        const CARRIER_LP_EXPRESS = 'lp_express';
        const CARRIER_VENIPAK = 'venipak';
        const CARRIER_VENIPAK_3PL = 'venipak_3pl';
        const CARRIER_POST_LT = 'post_lt';
        const CARRIER_POST_LV = 'post_lv';
        const CARRIER_POST_LV_POST = 'post_lv_post';
        const CARRIER_OMNIVA_LT = 'omniva_lt';
        const CARRIER_SMARTPOST = 'smartpost';
        const CARRIER_ZITICITY = 'ziticity';
        const CARRIER_SIUNTOS_AUTOBUSAIS = 'siuntos_autobusais';
        public function __construct()
        {
            // Display the selected location on the emails near custom details
            add_action('woocommerce_email_customer_details', [$this, 'email'], 15, 1); // email
            // Display the selected location on admin order page
            if (is_admin()) {
                add_action('woocommerce_admin_order_data_after_shipping_address', [$this, 'admin_order_page']);
                add_action('woocommerce_admin_shipping_fields', [$this, 'woocommerce_admin_shipping_fields']);
            }
            // Display the selected location after checkout
            add_action('woocommerce_order_details_after_order_table', [$this, 'after_checkout'], 10);
            add_action('woocommerce_after_checkout_validation', [$this, 'check_for_selected_location'], 10, 1);
            add_action('woocommerce_after_checkout_validation', [$this, 'check_for_ziticity_city'], 10, 1);


            add_action('woocommerce_checkout_update_order_meta', [$this, 'checkout_save_order_terminal_id_meta'], 10, 2);
            add_action('wp_ajax_multiparcels_order_pickup_points', [$this, 'multiparcels_order_pickup_points_callback']);
            add_action('wp_ajax_nopriv_multiparcels_checkout_get_pickup_points', [$this, 'checkout_get_pickup_points']);
            add_action('wp_ajax_multiparcels_checkout_get_pickup_points', [$this, 'checkout_get_pickup_points']);
            add_action('wp_ajax_nopriv_multiparcels_checkout_get_pickup_points_classic', [$this, 'checkout_get_pickup_points_classic']);
            add_action('wp_ajax_multiparcels_checkout_get_pickup_points_classic', [$this, 'checkout_get_pickup_points_classic']);
            add_action('wp_ajax_nopriv_multiparcels_set_terminal_value', [$this, 'checkout_save_terminal_value_theme_divi']);
            add_action('wp_ajax_multiparcels_set_terminal_value', [$this, 'checkout_save_terminal_value_theme_divi']);
            add_action('wp_ajax_nopriv_multiparcels_checkout_get_pickup_points_blocks', [$this, 'checkout_get_pickup_points_blocks']);
            add_action('wp_ajax_multiparcels_checkout_get_pickup_points_blocks', [$this, 'checkout_get_pickup_points_blocks']);
            add_action('wp_ajax_nopriv_multiparcels_checkout_get_pickup_points_siuntos_autobusais_blocks', [$this, 'checkout_get_pickup_points_siuntos_autobusais_blocks']);
            add_action('wp_ajax_multiparcels_checkout_get_pickup_points_siuntos_autobusais_blocks', [$this, 'checkout_get_pickup_points_siuntos_autobusais_blocks']);
//            add_action('wp_ajax_nopriv_multiparcels_checkout_address_autocomplete', [$this, 'address_autocomplete']);
//
//            add_action('wp_ajax_multiparcels_checkout_address_autocomplete', [$this, 'address_autocomplete']);
            add_action('wp_ajax_nopriv_multiparcels_is_preferred_delivery_time_available',
                [$this, 'is_preferred_delivery_time_available']);
            add_action('wp_ajax_multiparcels_is_preferred_delivery_time_available',
                [$this, 'is_preferred_delivery_time_available']);
            add_action('wp_ajax_nopriv_multiparcels_venipak_door_code',
                [$this, 'venipak_door_code']);
            add_action('wp_ajax_multiparcels_venipak_door_code',
                [$this, 'venipak_door_code']);
            add_action('woocommerce_email_before_order_table', [$this, 'email_instructions'], 0, 4);
            add_action('woocommerce_email', [$this, 'disable_woocommerce_completed_email_trigger']);
        }
        public function disable_woocommerce_completed_email_trigger($email_class) {
            // Remove the automatic trigger for completed order email
            remove_action(
                'woocommerce_order_status_completed_notification',
                [$email_class->emails['WC_Email_Customer_Completed_Order'], 'trigger']
            );
        }
        public function multiparcels_order_pickup_points_callback() {
            if (! wp_verify_nonce( $_POST['nonce'], 'order_box_content_label' )) {
                return;
            }
            // Get parameters
            $courier = isset($_POST['courier']) ? sanitize_text_field($_POST['courier']) : '';
            $country_code = isset($_POST['country_code']) ? sanitize_text_field($_POST['country_code']) : '';
            $search = isset($_POST['q']) ? sanitize_text_field($_POST['q']) : '';
            $page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
            $per_page = 20; // number of items per page
            // Fetch all locations
            $all_locations = MultiParcels()->locations->all($courier, $country_code);
            // Optional: remove post offices if needed
            foreach ($all_locations as $key => $location) {
                if ($location['type'] === 'post_office') {
                    unset($all_locations[$key]);
                }
            }
            // Filter by search term
            if (!empty($search)) {
                $all_locations = array_filter($all_locations, function($location) use ($search) {
                    $haystack = $location['name'] . ' ' . $location['address'] . ' ' . $location['city'];
                    return stripos($haystack, $search) !== false;
                });
            }
            // Total count
            $total_count = count($all_locations);
            // Pagination
            $offset = ($page - 1) * $per_page;
            $locations_page = array_slice($all_locations, $offset, $per_page);
            // Format results for Select2
            $items = [];
            foreach ($locations_page as $location) {
                $items[] = [
                    'identifier'  => $location['identifier'],
                    'name'        => $location['name'],
                    'address'     => $location['address'],
                    'city'        => $location['city'],
                    'postal_code' => $location['postal_code'],
                ];
            }
            // Send JSON response
            wp_send_json([
                'items' => $items,
                'total_count' => $total_count,
            ]);
        }
//        public function address_autocomplete()
//        {
//
//            $query = $_POST['query'];
//
//
//
////            $response = MultiParcels()->api_client->request('api/v1/address/autocomplete',
////
////                'POST', [
////
////                    'query'        => $query,
////
////                    'country_code' => strtolower($_POST['country']),
////
////                ]);
//
//            $response = MultiParcels()->api_client->request('api/translate/mp/address/autocomplete',
//
//                'POST', [
//
//                    'query'        => $query,
//
//                    'country_code' => strtolower($_POST['country']),
//
//                ]);
//
//
//
//            if ($response->was_successful()) {
//
//                echo json_encode($response->get_data());
//
//            } else {
//
//                echo json_encode(['results' => []]);
//
//            }
//
//
//
//            wp_die();
//
//        }
        public function is_preferred_delivery_time_available()
        {
            if ( ! wp_verify_nonce( $_POST['nonce'], 'wc_store_api' ) ) {
                return;
            }
            $response = [
                'success' => false,
                'times'   => [],
            ];
            $shipping = WC()->session->get('chosen_shipping_methods')[0];
            $instance_id = 0;
            $explode     = explode(':', $shipping);
            $shipping_id = $explode[0];
            if (count($explode) == 2) {
                $instance_id = $explode[1];
            }
            $methods = WC()->shipping()->get_shipping_methods();
            if (array_key_exists($shipping_id, $methods)) {
                $class_name = get_class(WC()->shipping()->get_shipping_methods()[$shipping_id]);
                /** @var WC_MP_Shipping_Method $shipping_class */
                $shipping_class = new $class_name($instance_id);
                if ($shipping_class->get_option('allow_preferred_delivery_time') == 1) {
                    $carrier = MultiParcels()->carriers->extract_from_method($shipping);
                    $preferred_delivery_time_frames = [];
                    if ( $carrier ) {
                        $carrier_settings = MultiParcels()->carriers->get( $carrier );
                        if ( array_key_exists( 'preferred_delivery_time_frames', $carrier_settings ) ) {
                            $preferred_delivery_time_frames = [
                                0 => _x( 'Any time', 'Preferred delivery time', 'multiparcels-shipping-for-woocommerce' ),
                            ];
                            $preferred_delivery_time_frames += $carrier_settings['preferred_delivery_time_frames'];
                        }
                    }
                    $response = [
                        'success' => true,
                        'times'   => $preferred_delivery_time_frames,
                    ];
                }
            }
            echo json_encode($response);
            wp_die();
        }
        public function venipak_door_code()
        {
            if ( ! wp_verify_nonce( $_POST['nonce'], 'wc_store_api' ) ) {
                return;
            }
            $response = [
                'success' => false,
            ];
            $shipping = WC()->session->get('chosen_shipping_methods')[0];
            $instance_id = 0;
            $explode     = explode(':', $shipping);
            $shipping_id = $explode[0];
            if (count($explode) == 2) {
                $instance_id = $explode[1];
            }
            $methods = WC()->shipping()->get_shipping_methods();
            if (array_key_exists($shipping_id, $methods)) {
                $class_name = get_class(WC()->shipping()->get_shipping_methods()[$shipping_id]);
                /** @var WC_MP_Shipping_Method $shipping_class */
                $shipping_class = new $class_name($instance_id);
                $value = $shipping_class->get_option(WC_MP_Shipping_Method::OPTION_VENIPAK_DOOR_CODE);
                // default value is empty or yes from admin
                if ($value == '' || $value == 'yes') {
                    $response = [
                        'success' => true,
                    ];
                }
            }
            echo json_encode($response);
            wp_die();
        }
        private function get_storage_shipping_method_settings($shipping_method)
        {
            if (!$shipping_method) {
                return false;
            }
            $parts = explode(':', $shipping_method);
            $method_id = $parts[0] ?? '';
            $instance_id = $parts[1] ?? '';
            if ($method_id !== 'multiparcels_lp_express_pickup_point') {
                return false;
            }
            if (!$instance_id) {
                return false;
            }
            $settings = get_option('woocommerce_' . $method_id . '_' . $instance_id . '_settings', []);
            if (!is_array($settings)) {
                return false;
            }
            $services = $settings['default_services'] ?? [];
            if (!is_array($services)) {
                $services = [];
            }
            if (!in_array('storage', $services, true)) {
                return false;
            }
            $storage_location_identifier = $settings['storage_location_identifier'] ?? '';
            if (!$storage_location_identifier) {
                return false;
            }
            return [
                'method_id'                   => $method_id,
                'instance_id'                 => $instance_id,
                'storage_location_identifier' => $storage_location_identifier,
            ];
        }
        private function save_storage_location_for_order($order_id, $shipping_method)
        {
            $settings = $this->get_storage_shipping_method_settings($shipping_method);
            if (!$settings) {
                return false;
            }
            $identifier = sanitize_text_field($settings['storage_location_identifier']);
            if (!$identifier) {
                return false;
            }
            $location = MultiParcels()->locations->get(
                $identifier,
                WC_MP_Shipping_Helper::CARRIER_LP_EXPRESS
            );
            $text = '';
            if ($location) {
                $text = trim(sprintf(
                    '%s %s %s',
                    $location['name'] ?? '',
                    $location['address'] ?? '',
                    $location['country_code'] ?? ''
                ));
            }
            if (class_exists(\Automattic\WooCommerce\Utilities\OrderUtil::class)) {
                if (\Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled()) {
                    $order = wc_get_order($order_id);
                    if (!$order) {
                        return false;
                    }
                    if ($text !== '') {
                        $order->update_meta_data('multiparcels_location_identifier_name', $text);
                    }
                    $order->update_meta_data('multiparcels_location_identifier', $identifier);
                    $order->save();
                    return true;
                }
            }
            if ($text !== '') {
                update_post_meta($order_id, 'multiparcels_location_identifier_name', $text);
            }
            update_post_meta($order_id, 'multiparcels_location_identifier', $identifier);
            return true;
        }
        /**
         * @param  int  $order_id
         * @param $posted
         */
        function checkout_save_order_terminal_id_meta($order_id, $posted)
        {
            $set_nonce = wp_create_nonce('_wpnonce2');
            if ( ! wp_verify_nonce( $set_nonce, '_wpnonce2' ) ) {
                return;
            }
            $shipping_method = '';
            if (isset($_POST['shipping_method']) && is_array($_POST['shipping_method'])) {
                $shipping_methods = array_values(wp_unslash($_POST['shipping_method']));
                $shipping_method = isset($shipping_methods[0]) ? sanitize_text_field($shipping_methods[0]) : '';
            }
            if (!$shipping_method && WC()->session) {
                $chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');
                if (is_array($chosen_shipping_methods) && !empty($chosen_shipping_methods[0])) {
                    $shipping_method = sanitize_text_field($chosen_shipping_methods[0]);
                }
            }
            if (!$shipping_method) {
                return;
            }
            $storage_location_saved = false;
            if ($shipping_method) {
                $storage_location_saved = $this->save_storage_location_for_order($order_id, $shipping_method);
            }
            if ($storage_location_saved) {
                return;
            }
            if($shipping_method) {
                if (str_contains($shipping_method, 'siuntos_autobusais_courier')) {
                    $order = wc_get_order( $order_id );
                    $carrier = MultiParcels()->carriers->extract_from_method($order);
                    $input = sanitize_text_field($_POST[WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME]);
                    if($carrier == 'siuntos_autobusais') {
                        $location = MultiParcels()->locations->get($input, $carrier);
                        $text = $location['name'] . ' ' . $location['address'] . ' ' . $location['country_code'];
                        if (class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )) {
                            if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
                                $order->update_meta_data('multiparcels_location_identifier_name', $text);
                                $order->update_meta_data( WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME, $input );
                                $order->save();
                            } else {
                                update_post_meta($order_id, 'multiparcels_location_identifier_name', $text);
                                update_post_meta($order_id, WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME, $input);
                            }
                        }else {
                            update_post_meta($order_id, 'multiparcels_location_identifier_name', $text);
                            update_post_meta($order_id, WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME, $input);
                        }
                    }
                }
                if (str_contains($shipping_method, 'siuntos_autobusais_bus_station')) {
                    $order = wc_get_order( $order_id );
                    $carrier = MultiParcels()->carriers->extract_from_method($order);
                    $input = sanitize_text_field($_POST[WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME]);
                    if($carrier == 'siuntos_autobusais') {
                        $location = MultiParcels()->locations->get($input, $carrier);
                        $text = $location['name'] . ' ' . $location['address'] . ' ' . $location['country_code'];
                        if (class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )) {
                            if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
                                $order->update_meta_data('multiparcels_location_identifier_name', $text);
                                $order->update_meta_data( WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME, $input );
                                $order->save();
                            } else {
                                update_post_meta($order_id, 'multiparcels_location_identifier_name', $text);
                                update_post_meta($order_id, WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME, $input);
                            }
                        }else {
                            update_post_meta($order_id, 'multiparcels_location_identifier_name', $text);
                            update_post_meta($order_id, WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME, $input);
                        }
                    }
                }
            }
            if (
                !$storage_location_saved
                && defined('WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME')
                && isset($_POST[WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME])
                && MultiParcels()->locations->is_delivery_to_pickup_point($order_id, true)
            ) {
                $input = sanitize_text_field($_POST[WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME]);
                if (class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )) {
                    if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
                        // HPOS usage is enabled.
                        $order = wc_get_order( $order_id );
                        $carrier = MultiParcels()->carriers->extract_from_method($order);
                        if ($carrier == 'siuntos_autobusais') {
                            $location = MultiParcels()->locations->get($input, $carrier);
                            $text = $location['name'] . ' ' . $location['address'] . ' ' . $location['country_code'];
                            $order->update_meta_data('multiparcels_location_identifier_name', $text);
                        }
                        $order->update_meta_data( WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME, $input );
                        $order->save();
                    } else {
                        // Traditional CPT-based orders are in use.
                        $order = wc_get_order( $order_id );
                        $carrier = MultiParcels()->carriers->extract_from_method($order);
                        if ($carrier == 'siuntos_autobusais') {
                            $location = MultiParcels()->locations->get($input, $carrier);
                            $text = $location['name'] . ' ' . $location['address'] . ' ' . $location['country_code'];
                            update_post_meta($order_id, 'multiparcels_location_identifier_name', $text);
                        }
                        update_post_meta($order_id, WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME, $input);
                    }
                } else {
                    // Traditional CPT-based orders are in use.
                    $order = wc_get_order( $order_id );
                    $carrier = MultiParcels()->carriers->extract_from_method($order);
                    if ($carrier == 'siuntos_autobusais') {
                        $location = MultiParcels()->locations->get($input, $carrier);
                        $text = $location['name'] . ' ' . $location['address'] . ' ' . $location['country_code'];
                        update_post_meta($order_id, 'multiparcels_location_identifier_name', $text);
                    }
                    update_post_meta($order_id, WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME, $input);
                }
            }
            if (isset($_POST[WC_MP_Shipping_Method::INPUT_DOOR_CODE])) {
                $input = sanitize_text_field($_POST[WC_MP_Shipping_Method::INPUT_DOOR_CODE]);
                if (class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )) {
                    if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
                        // HPOS usage is enabled.
                        $order = wc_get_order( $order_id );
                        $order->update_meta_data( WC_MP_Shipping_Method::INPUT_DOOR_CODE, $input );
                        $order->save();
                    }else {
                        // Traditional CPT-based orders are in use.
                        update_post_meta($order_id, WC_MP_Shipping_Method::INPUT_DOOR_CODE, $input);
                    }
                } else {
                    // Traditional CPT-based orders are in use.
                    update_post_meta($order_id, WC_MP_Shipping_Method::INPUT_DOOR_CODE, $input);
                }
            }
            if (isset($_POST[WC_MP_Shipping_Method::INPUT_PREFERRED_DELIVERY_TIME])) {
                $input = sanitize_text_field($_POST[WC_MP_Shipping_Method::INPUT_PREFERRED_DELIVERY_TIME]);
                if (class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )) {
                    if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
                        // HPOS usage is enabled.
                        $order = wc_get_order( $order_id );
                        $order->update_meta_data( WC_MP_Shipping_Method::INPUT_PREFERRED_DELIVERY_TIME, $input );
                        $order->save();
                    }else {
                        // Traditional CPT-based orders are in use.
                        update_post_meta($order_id, WC_MP_Shipping_Method::INPUT_PREFERRED_DELIVERY_TIME, $input);
                    }
                } else {
                    // Traditional CPT-based orders are in use.
                    update_post_meta($order_id, WC_MP_Shipping_Method::INPUT_PREFERRED_DELIVERY_TIME, $input);
                }
            }
            if ( WC()->session->get('multiparcels_pickup_location_value_divi') !== null ) {
                $input = sanitize_text_field(WC()->session->get('multiparcels_pickup_location_value_divi'));
                if (class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )) {
                    if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
                        // HPOS usage is enabled.
                        $order = wc_get_order( $order_id );
                        $carrier = MultiParcels()->carriers->extract_from_method($order);
                        if ($carrier == 'siuntos_autobusais') {
                            $location = MultiParcels()->locations->get($input, $carrier);
                            $text = $location['name'] . ' ' . $location['address'] . ' ' . $location['country_code'];
                            $order->update_meta_data('multiparcels_location_identifier_name', $text);
                        }
                        $order->update_meta_data( WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME, $input );
                        $order->save();
                    } else {
                        // Traditional CPT-based orders are in use.
                        $order = wc_get_order( $order_id );
                        $carrier = MultiParcels()->carriers->extract_from_method($order);
                        if ($carrier == 'siuntos_autobusais') {
                            $location = MultiParcels()->locations->get($input, $carrier);
                            $text = $location['name'] . ' ' . $location['address'] . ' ' . $location['country_code'];
                            update_post_meta($order_id, 'multiparcels_location_identifier_name', $text);
                        }
                        update_post_meta($order_id, WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME, $input);
                    }
                } else {
                    // Traditional CPT-based orders are in use.
                    $order = wc_get_order( $order_id );
                    $carrier = MultiParcels()->carriers->extract_from_method($order);
                    if ($carrier == 'siuntos_autobusais') {
                        $location = MultiParcels()->locations->get($input, $carrier);
                        $text = $location['name'] . ' ' . $location['address'] . ' ' . $location['country_code'];
                        update_post_meta($order_id, 'multiparcels_location_identifier_name', $text);
                    }
                    update_post_meta($order_id, WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME, $input);
                }
            }
        }
        public function email($order)
        {
            if ($location = MultiParcels()->locations->get_location_for_order($order)) {
                $selected_text = MultiParcels()->locations->selected_text($location);
                wc_get_template('emails/email-selected-pickup-location.php', [
                    'selected_text' => $selected_text,
                    'location'      => $location['name'],
                    'address'       => sprintf("%s, %s, %s", $location['address'],
                        $location['city'],
                        $location['postal_code']),
                ], '', MultiParcels()->plugin_path().'/woocommerce/');
            }
        }
        /**
         * @param WC_Order|int $order
         */
        function admin_order_page($order)
        {
            $button_displayed = false;
            $button_html = sprintf('<div style="%s"><a class="button button-primary" href="%s">%s</a></div>',
                'margin-bottom:5px;clear: both;',
                esc_attr('#multiparcels-shipping-pickup-point-box'),
                __('Pickup location', 'multiparcels-shipping-for-woocommerce'));
            if ($location = MultiParcels()->locations->get_location_for_order($order)) {
                $selected_text = MultiParcels()->locations->selected_text($location);
                $output = '<div style="clear: both;">';
                $output .= sprintf('<div><strong>%s:</strong></div>', esc_html($selected_text));
                $output .= $location['name'] . '<br/>';
                $output .= esc_html(sprintf("%s, %s, %s", $location['address'], $location['city'],
                    $location['postal_code']));
                $output .= '</div>';
                $output .= '<br/>';
                $button_displayed = true;
                $output .= $button_html;
                // Suppress PHPCS warning for unescaped output (base64-encoded binary data)
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                echo $output;
            }
            if ( ! $button_displayed && MultiParcels()->locations->is_delivery_to_pickup_point( $order ) ) {
                // Suppress PHPCS warning for unescaped output (base64-encoded binary data)
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                echo $button_html;
            }
        }
        public function woocommerce_admin_shipping_fields($fields)
        {
            $fields['phone'] = [
                'label' => __("Phone", "woocommerce"),
                'show' => true
            ];
            return $fields;
        }
        public function after_checkout($order)
        {
            if ($location = MultiParcels()->locations->get_location_for_order($order)) {
                $selected_text = MultiParcels()->locations->selected_text($location);
                echo '<h2>' .esc_html(__( 'Shipment Details', 'multiparcels-shipping-for-woocommerce' )) . '</h2>';
                $courier_name = MultiParcels()->carriers->method_name($order);
                if (class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )) {
                    if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
                        $shipment_statuses = $order->get_meta('multiparcels_carrier_shipment_status', true);
                    } else {
                        $shipment_statuses = get_post_meta( $order->get_id(), 'multiparcels_carrier_shipment_status', true );
                    }
                }else {
                    $shipment_statuses = get_post_meta( $order->get_id(), 'multiparcels_carrier_shipment_status', true );
                }
                if ($shipment_statuses) {
                    echo '<h2>' .esc_html(__( 'Shipment Details', 'multiparcels-shipping-for-woocommerce' )) . '</h2>';
                    echo '<table>';
                    echo '<thead>';
                    echo '<tr>';
                    echo '<td>' .esc_html(__( 'Status', 'multiparcels-shipping-for-woocommerce' )). '</td>';
                    echo '<td>' .esc_html(__( 'Courier', 'multiparcels-shipping-for-woocommerce' )). '</td>';
                    echo '<td>' .esc_html(__( 'Date', 'multiparcels-shipping-for-woocommerce' )). '</td>';
                    echo '</tr>';
                    echo '</thead>';
                    echo '<tbody>';
                    foreach ($shipment_statuses as $shipment_status) {
                        if ($shipment_status['status'] == 'in_warehouse') {
                            $shipment_status_title = esc_html(__( 'The shipment is at the distribution terminal', 'multiparcels-shipping-for-woocommerce' ));
                        }
                        if ($shipment_status['status'] == 'put_for_sending') {
                            $shipment_status_title = esc_html(__( 'The shipment has been placed in a parcel locker', 'multiparcels-shipping-for-woocommerce' ));
                        }
                        if ($shipment_status['status'] == 'picked_up') {
                            $shipment_status_title = esc_html(__( 'The shipment has been collected', 'multiparcels-shipping-for-woocommerce' ));
                        }
                        if ($shipment_status['status'] == 'waiting_for_sending') {
                            $shipment_status_title = esc_html(__( 'Awaiting dispatch', 'multiparcels-shipping-for-woocommerce' ));
                        }
                        if ($shipment_status['status'] == 'in_terminal') {
                            $shipment_status_title = esc_html(__( 'Delivered to the parcel locker', 'multiparcels-shipping-for-woocommerce' ));
                        }
                        if ($shipment_status['status'] == 'in_transit' || $shipment_status['status'] == 'delivering') {
                            $shipment_status_title = esc_html(__( 'In transit', 'multiparcels-shipping-for-woocommerce' ));
                        }
                        if ($shipment_status['status'] == 'delivered') {
                            $shipment_status_title = esc_html(__( 'Delivered', 'multiparcels-shipping-for-woocommerce' ));
                        }
                        echo '<tr>';
                        echo '<td>' . $shipment_status_title . '</td>';
                        echo '<td>' . $courier_name . '</td>';
                        echo '<td>' . date('Y-m-d H:i:s', strtotime($shipment_status['created_at'])) . '</td>';
                        echo '</tr>';
                    }
                    echo '</tbody>';
                    echo '</table>';
                }
                wc_get_template('order/order-details-after-customer-v3.php', [
                    'selected_text' => $selected_text,
                    'location'      => $location['name'],
                    'address'       => sprintf("%s, %s, %s", $location['address'],
                        $location['city'],
                        $location['postal_code']),
                ], '', MultiParcels()->plugin_path().'/woocommerce/');
            }
        }
        /**
         * @param  array  $posted
         */
        function check_for_selected_location($posted)
        {
            //OLD
            $set_nonce = wp_create_nonce('_wpnonce2');
            if ( ! wp_verify_nonce( $set_nonce, '_wpnonce2' ) ) {
                return;
            }
//            if (defined('DOING_AJAX') && DOING_AJAX) {
//                return;
//            }
            // Checking for shipping method existing
            if (empty($posted['shipping_method']) || !is_array($posted['shipping_method'])) {
                return;
            }
            if (isset($posted['shipping_method']) && is_array($posted['shipping_method'])) {
                $shipping_method = array_values($posted['shipping_method'])[0];
                $check = 'multiparcels_';
                if (substr($shipping_method, 0, strlen($check)) == $check) {
                    $pickup_point = strpos($shipping_method, WC_MP_Shipping_Method::SUFFIX_PICKUP_POINT) !== false;
                    $terminal = strpos($shipping_method, WC_MP_Shipping_Method::SUFFIX_TERMINAL) !== false;
                    $post_lv_post_delivery = MultiParcels()->locations->is_delivery_to_latvian_post_office($shipping_method);
                    $bus_station = strpos($shipping_method, WC_MP_Shipping_Method::SUFFIX_BUS_STATION) !== false;
                    $bus_station_courier = strpos($shipping_method, WC_MP_Shipping_Method::SUFFIX_BUS_STATION_COURIER) !== false;
                    if ($pickup_point || $terminal || $post_lv_post_delivery || $bus_station || $bus_station_courier) {
                        if ( ! isset($_POST[WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME]) || $_POST[WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME] == '') {
                            if ($this->get_storage_shipping_method_settings($shipping_method)) {
                                return;
                            }
                            if(!MultiParcels()->options->get( 'show_pickup_points_notice') || MultiParcels()->options->get( 'show_pickup_points_notice') == 'yes') {
                                wc_add_notice(__('Please select the pickup location.',
                                    'multiparcels-shipping-for-woocommerce'),
                                    'error');
                            }
                        } else {
                            $location_identifier = $_POST[WC_MP_Pickup_Point_Shipping_Method::INPUT_NAME];
                            $carrier = MultiParcels()->carriers->extract_from_method($shipping_method);
//                            $location = MultiParcels()->locations->get($location_identifier, $carrier, $post_lv_post_delivery);
                            if ($carrier == 'post_lv') {
                                $location = MultiParcels()->locations->get_latvian_post_location($location_identifier, $carrier, $shipping_method, $post_lv_post_delivery);
                            } else {
                                $location = MultiParcels()->locations->get($location_identifier, $carrier, $post_lv_post_delivery);
                            }
                            if (!$location) {
                                if(!MultiParcels()->options->get( 'show_pickup_points_notice') || MultiParcels()->options->get( 'show_pickup_points_notice') == 'yes') {
                                    wc_add_notice(__('Please select the pickup location.',
                                        'multiparcels-shipping-for-woocommerce'),
                                        'error');
                                }
                            }
                        }
                    }
                }
            }
        }
        function check_for_ziticity_city($data) {
            if (isset($data['shipping_method']) && is_array($data['shipping_method'])) {
                $shipping_method = array_values($data['shipping_method'])[0];
                $check = 'multiparcels_';
                if (substr($shipping_method, 0, strlen($check)) == $check) {
                    $carrier = MultiParcels()->carriers->extract_from_method($shipping_method);
                    if ($carrier == WC_MP_Shipping_Helper::CARRIER_ZITICITY) {
                        $city = trim(MultiParcels()->helper->latin_characters(WC()->customer->get_shipping_city()));
                        $methods = WC()->shipping()->get_shipping_methods();
                        $explode     = explode(':', $shipping_method);
                        $shipping_id = $explode[0];
                        if (count($explode) == 2) {
                            $instance_id = $explode[1];
                        }
                        if (array_key_exists($shipping_id, $methods)) {
                            $class_name = get_class(WC()->shipping()->get_shipping_methods()[$shipping_id]);
                            /** @var WC_MP_Shipping_Method $shipping_class */
                            $shipping_class = new $class_name($instance_id);
                            $allowed_city = trim(MultiParcels()->helper->latin_characters($shipping_class->get_option(WC_MP_Shipping_Method::OPTION_ZITICITY_ONLY_CITY)));
                            if ($allowed_city == 'all') {
                                return;
                            }
                            if ($allowed_city != $city) {
                                $notice = sprintf(__('This shipping method is not allowed to your city. Allowed city: %s', 'multiparcels-shipping-for-woocommerce'), $shipping_class->get_option(WC_MP_Shipping_Method::OPTION_ZITICITY_ONLY_CITY));
                                wc_add_notice($notice, 'error');
                            }
                        }
                    }
                }
            }
        }
        public function checkout_get_pickup_points_siuntos_autobusais_blocks()
        {
            if ( ! wp_verify_nonce( $_POST['nonce'], 'wc_store_api' ) ) {
                return;
            }
            $city_option = MultiParcels()->options->get('extra_cities_siuntos_autobusais', true);
            $shipping_method = $_REQUEST['selected_value'];
            $carrier_code = MultiParcels()->carriers->extract_from_method($shipping_method, false);
            $siuntos_autobusais_pickup_city_option = MultiParcels()->options->get('extra_siuntos_autobusais_pickup_cities_siuntos_autobusais', true);
            foreach ($city_option as $key => $city) {
                $search = [];
                $search[] = 'courier_code:'.$carrier_code;
                $search[] = 'method:'.$city;
//                $response = MultiParcels()->api_client->request('locations_for_shops', 'GET', [
//
//                    'limit' => 99999,
//
//                    'search' => implode(';', $search),
//
//                    'searchJoin' => 'and',
//
//                ]);
                $response = MultiParcels()->api_client->request('api/translate/mp/locations', 'GET', [
                    'limit' => 99999,
                    'search' => implode(';', $search),
                    'searchJoin' => 'and',
                ]);
                if ($response->was_successful()) {
                    $locations = $response->get_data();
//                    $city_to = $locations[0]['custom_fields']['from'];
//
//                    $city_explode_array = explode(",", $city_to);
                    $optionsForSelect2 = [];
                    $optionsForSelect2[] = [
                        'id'          => '',
                        'first_line'  => __('Please select the pickup location', 'multiparcels-shipping-for-woocommerce'),
                        'second_line' => '',
                        'text'        => __('Please select the pickup location', 'multiparcels-shipping-for-woocommerce'),
                    ];
                    foreach ($locations as $key => $location) {
                        if ($siuntos_autobusais_pickup_city_option) {
//                            $siuntos_autobusais_pickup_point_key = array_search($location['city'], $siuntos_autobusais_pickup_city_option);
                            $siuntos_autobusais_pickup_city_option= array_map(function($word) { return MultiParcels()->helper->latin_characters($word) ;},$siuntos_autobusais_pickup_city_option);
                            $siuntos_autobusais_pickup_point_key = array_search(MultiParcels()->helper->latin_characters($location['city']),$siuntos_autobusais_pickup_city_option);
                            if ($siuntos_autobusais_pickup_point_key) {
                                if (str_contains($shipping_method, 'courier')) {
                                    if ($location['custom_fields']['kr']) {
                                        $preparedItem        = [
                                            'id'          => $location['identifier'],
                                            'first_line'  => $location['name'],
                                            'second_line' => sprintf("%s, %s, %s", $location['address'], $location['city'],
                                                $location['postal_code']),
//                            'text'        => sprintf("%s, %s, %s, %s", $location['name'], $location['address'],
//
//                                $location['city'], $location['postal_code']),
                                            'text'        => sprintf("%s, %s, %s", $location['name'], $location['address'],
                                                $location['city']),
                                            'location'    => $location,
                                        ];
                                        $optionsForSelect2[] = $preparedItem;
                                    }
                                }else {
                                    $preparedItem        = [
                                        'id'          => $location['identifier'],
                                        'first_line'  => $location['name'],
                                        'second_line' => sprintf("%s, %s, %s", $location['address'], $location['city'],
                                            $location['postal_code']),
//                            'text'        => sprintf("%s, %s, %s, %s", $location['name'], $location['address'],
//
//                                $location['city'], $location['postal_code']),
                                        'text'        => sprintf("%s, %s, %s", $location['name'], $location['address'],
                                            $location['city']),
                                        'location'    => $location,
                                    ];
                                    $optionsForSelect2[] = $preparedItem;
                                }
                            }
                        }else {
                            if (str_contains($shipping_method, 'courier')) {
                                if ($location['custom_fields']['kr']) {
                                    $preparedItem        = [
                                        'id'          => $location['identifier'],
                                        'first_line'  => $location['name'],
                                        'second_line' => sprintf("%s, %s, %s", $location['address'], $location['city'],
                                            $location['postal_code']),
//                            'text'        => sprintf("%s, %s, %s, %s", $location['name'], $location['address'],
//
//                                $location['city'], $location['postal_code']),
                                        'text'        => sprintf("%s, %s, %s", $location['name'], $location['address'],
                                            $location['city']),
                                        'location'    => $location,
                                    ];
                                    $optionsForSelect2[] = $preparedItem;
                                }
                            } else {
                                $preparedItem        = [
                                    'id'          => $location['identifier'],
                                    'first_line'  => $location['name'],
                                    'second_line' => sprintf("%s, %s, %s", $location['address'], $location['city'],
                                        $location['postal_code']),
//                            'text'        => sprintf("%s, %s, %s, %s", $location['name'], $location['address'],
//
//                                $location['city'], $location['postal_code']),
                                    'text'        => sprintf("%s, %s, %s", $location['name'], $location['address'],
                                        $location['city']),
                                    'location'    => $location,
                                ];
                                $optionsForSelect2[] = $preparedItem;
                            }
                        }
                    }
//                    foreach ($options as $city => $group) {
//
//                        $locations = [];
//
//                        foreach ($group as $item) {
//
//                            $preparedItem        = [
//
//                                'id'          => $item['identifier'],
//
//                                'first_line'  => $item['name'],
//
//                                'second_line' => sprintf("%s, %s, %s", $item['address'], $item['city'],
//
//                                    $item['postal_code']),
//
//                                'text'        => sprintf("%s, %s, %s, %s", $item['name'], $item['address'],
//
//                                    $item['city'], $item['postal_code']),
//
//                                'location'    => $item,
//
//                            ];
//
//
//
//                            if (MultiParcels()->options->get('show_all_cities') === "2" || MultiParcels()->options->get('show_all_cities') === 2) {
//
//                                $locations[] = $preparedItem;
//
//                            } else {
//
//                                $optionsForSelect2[] = $preparedItem;
//
//                            }
//
//
//
//                            $optionsForSelect2ByIdentifier[$item['identifier']] = $preparedItem;
//
//                        }
//                    foreach ($city_explode_array as $key => $one_city) {
//                        $preparedItem        = [
//
//                            'id'          => 'siuntos-autobusais_' .$locations[0]['identifier']. '_' . $one_city,
//
//                            'first_line'  => $locations[0]['name'],
//
//                            'second_line' => sprintf("%s, %s, %s", $locations[0]['address'], $locations[0]['city'],
//
//                                $locations[0]['postal_code']),
//
//                            'text'        => $one_city,
//
//                            'location'    => $locations[0],
//
//                        ];
//
//                        $optionsForSelect2[] = $preparedItem;
//                    }
//                    echo json_encode([
//
//                        'all'           => $optionsForSelect2,
//
//                    ]);
//
//
//
//                    wp_die();
                    /**
                     * --- Pagination + Search ---
                     */
                    $page     = isset($_POST['page']) ? (int) $_POST['page'] : 1;
                    $per_page = 50;
                    $offset   = ($page - 1) * $per_page;
                    $search   = isset($_POST['q']) ? sanitize_text_field($_POST['q']) : '';
                    // Searching
                    if ($search) {
                        $optionsForSelect2 = array_filter($optionsForSelect2, function($item) use ($search) {
                            return stripos($item['first_line'], $search) !== false
                                || stripos($item['second_line'], $search) !== false
                                || stripos($item['text'], $search) !== false;
                        });
                        $optionsForSelect2 = array_values($optionsForSelect2);
                    }
                    $total    = count($optionsForSelect2);
                    $paged    = array_slice($optionsForSelect2, $offset, $per_page);
                    $response = [
                        'results' => $paged,
                        'pagination' => [
                            'more' => ($offset + $per_page) < $total
                        ]
                    ];
                    echo json_encode($response);
                    wp_die();
                }
            }
        }
        public function checkout_get_pickup_points_blocks()
        {
            if ( ! wp_verify_nonce( $_POST['nonce'], 'wc_store_api' ) ) {
                return;
            }
            $country = null;
            $city    = null;
//            $shipping_method = array_values(WC()->session->get('chosen_shipping_methods'))[0];
//            if ($shipping_method == NULL) {
//                $shipping_method = $_REQUEST['selected_value'];
//            }
            $shipping_method = $_REQUEST['selected_value'];
            $carrier = MultiParcels()->carriers->extract_from_method($shipping_method, true);
            if (WC()->customer->get_shipping_city()) {
                $city = WC()->customer->get_shipping_city();
            }
            if (WC()->customer->get_billing_country()) {
                $country = WC()->customer->get_billing_country();
            }
            if (WC()->customer->get_shipping_country()) {
                $country = WC()->customer->get_shipping_country();
            }
            if (isset($_POST['city'])) {
                $city = $_POST['city'];
            }
            if (isset($_POST['country'])) {
                $country = $_POST['country'];
            }
            $city    = sanitize_text_field($city);
            $country = sanitize_text_field($country);
            if (isset($_POST['s_country']) && $_POST['s_country'] != $country) {
                $country = $_POST['s_country'];
            }
            $type = null;
            if (strpos($shipping_method, '_'.WC_MP_Shipping_Method::SUFFIX_TERMINAL) !== false) {
                $type = WC_MP_Shipping_Method::SUFFIX_TERMINAL;
            }
            if (MultiParcels()->locations->is_delivery_to_latvian_post_office($shipping_method)) {
                $type = 'post_office';
            }
            if (strpos($shipping_method, '_'.WC_MP_Shipping_Helper::CARRIER_POST_LV_POST) !== false) {
                $type = 'post_office';
            }
            if ($carrier == WC_MP_Shipping_Helper::CARRIER_VENIPAK) {
                $instance_id = 0;
                $explode     = explode(':', $shipping_method);
                $shipping_id = $explode[0];
                if (count($explode) == 2) {
                    $instance_id = $explode[1];
                }
                $methods = WC()->shipping()->get_shipping_methods();
                if (array_key_exists($shipping_id, $methods)) {
                    $class_name = get_class(WC()->shipping()->get_shipping_methods()[$shipping_id]);
                    /** @var WC_MP_Shipping_Method $shipping_class */
                    $shipping_class = new $class_name($instance_id);
                    $only = $shipping_class->get_option(WC_MP_Shipping_Method::OPTION_VENIPAK_DISPLAYED_PICKUP_POINTS);
                    if ($only) {
                        if ($only == 'terminals') {
                            $type = WC_MP_Shipping_Method::SUFFIX_TERMINAL;
                        }
                        if ($only == 'pickup_points') {
                            $type = WC_MP_Shipping_Method::SUFFIX_PICKUP_POINT;
                        }
                    }
                }
            }
            if ($carrier == 'siuntos_autobusais') {
                $search = [];
                $search[] = 'courier_code:'.$carrier;
                $search[] = 'method:'.$city;
//                $response = MultiParcels()->api_client->request('locations_for_shops', 'GET', [
//
//                    'limit' => 99999,
//
//                    'search' => implode(';', $search),
//
//                    'searchJoin' => 'and',
//
//                ]);
                $response = MultiParcels()->api_client->request('api/translate/mp/locations', 'GET', [
                    'limit' => 99999,
                    'search' => implode(';', $search),
                    'searchJoin' => 'and',
                ]);
                if ($response->was_successful()) {
                    $options = $response->get_data();
                }
            } else {
                $options = MultiParcels()->locations->get_for_city($carrier, $city, $country, $type);
            }
            if ($type != 'post_office') {
                // remove post_offices because we only need them when it is post_lv
                foreach ($options as $city => $locations) {
                    foreach ($locations as $key => $location) {
                        if ($location['type'] == 'post_office') {
                            unset($options[$city][$key]);
                        }
                    }
                }
            }
            $optionsForSelect2 = [];
            $optionsForSelect2ByIdentifier = [];
            $optionsForSelect2[] = [
                'id'          => '',
                'first_line'  => __('Please select the pickup location', 'multiparcels-shipping-for-woocommerce'),
                'second_line' => '',
                'text'        => __('Please select the pickup location', 'multiparcels-shipping-for-woocommerce'),
            ];
            if ($carrier != 'siuntos_autobusais') {
//                foreach ($options as $city => $group) {
//                    $locations = [];
//
//                    foreach ($group as $item) {
//                        if ($carrier == 'itella') {
//                            // Remove everything up to and including the first space
//                            $result = preg_replace('/^[^ ]* /', '', $item['name']);
//                        } else {
//                            $result = $item['name'];
//                        }
//
//                        $preparedItem        = [
//
//                            'id'          => $item['identifier'],
//
//                            'first_line'  => $result,
//
//                            'second_line' => sprintf("%s, %s, %s", $item['address'], $item['city'],
//
//                                $item['postal_code']),
//
//                            'text'        => sprintf("%s, %s, %s, %s", $result, $item['address'],
//
//                                $item['city'], $item['postal_code']),
//
//                            'location'    => $item,
//
//                        ];
//
//
//
//                        if (MultiParcels()->options->get('show_all_cities') === "2" || MultiParcels()->options->get('show_all_cities') === 2) {
//
//                            $locations[] = $preparedItem;
//
//                        } else {
//
//                            $optionsForSelect2[] = $preparedItem;
//
//                        }
//
//
//
//                        $optionsForSelect2ByIdentifier[$item['identifier']] = $preparedItem;
//
//                    }
//
//                    if (count($locations)) {
//
//                        // group by city
//
//                        $optionsForSelect2[] = [
//
//                            'text'     => $city,
//
//                            'children' => $locations,
//
//                        ];
//
//                    }
//
//                }
                //New functionality with group by city
                $optionsForSelect2 = [];
                foreach ($options as $city => $group) {
                    $locations = [];
                    foreach ($group as $item) {
                        if ($carrier == 'itella') {
                            $result = preg_replace('/^[^ ]* /', '', $item['name']);
                        } else {
                            $result = $item['name'];
                        }
                        $locations[] = [
                            'id' => $item['identifier'], // unique ID
//                            'first_line' => $result,
                            'first_line' => MultiParcels()->locations->latin_only($result),
                            //'second_line' => sprintf("%s, %s, %s", $item['address'], $item['city'], $item['postal_code']),
                            'second_line' => sprintf("%s, %s, %s", MultiParcels()->locations->latin_only($item['address']), MultiParcels()->locations->latin_only($item['city']), $item['postal_code']),
                            'text' => sprintf("%s, %s, %s, %s", $result, $item['address'], $item['city'], $item['postal_code']),
                            'location' => $item, // keep original for reference
                        ];
                    }
                    if (count($locations)) {
                        // group by city
                        $optionsForSelect2[] = [
                            'text'     => ucfirst($city),
                            'children' => $locations,
                        ];
                    }
                }
            } else {
                $siuntos_autobusais_pickup_city_option = MultiParcels()->options->get('extra_siuntos_autobusais_pickup_cities_siuntos_autobusais', true);
                foreach ($options as $key => $option) {
                    if ($siuntos_autobusais_pickup_city_option) {
//                        $siuntos_autobusais_pickup_point_key = array_search($option['city'], $siuntos_autobusais_pickup_city_option);
                        $siuntos_autobusais_pickup_city_option= array_map(function($word) { return MultiParcels()->helper->latin_characters($word) ;},$siuntos_autobusais_pickup_city_option);
                        $siuntos_autobusais_pickup_point_key = array_search(MultiParcels()->helper->latin_characters($option['city']),$siuntos_autobusais_pickup_city_option);
                        if ($siuntos_autobusais_pickup_point_key) {
                            $preparedItem        = [
                                'id'          => $option['identifier'],
                                'first_line'  => $option['name'],
                                'second_line' => sprintf("%s, %s, %s", $option['address'], $option['city'],
                                    $option['postal_code']),
                                'text'        => sprintf("%s, %s, %s, %s", $option['name'], $option['address'],
                                    $option['city'], $option['postal_code']),
                                'location'    => $option,
                            ];
                            $optionsForSelect2[] = $preparedItem;
                            $optionsForSelect2ByIdentifier[$option['identifier']] = $preparedItem;
                        }
                    }else {
                        $preparedItem        = [
                            'id'          => $option['identifier'],
                            'first_line'  => $option['name'],
                            'second_line' => sprintf("%s, %s, %s", $option['address'], $option['city'],
                                $option['postal_code']),
                            'text'        => sprintf("%s, %s, %s, %s", $option['name'], $option['address'],
                                $option['city'], $option['postal_code']),
                            'location'    => $option,
                        ];
                        $optionsForSelect2[] = $preparedItem;
                        $optionsForSelect2ByIdentifier[$option['identifier']] = $preparedItem;
                    }
                }
            }
            // OLD functionality
//            echo json_encode([
//
//                'all'           => $optionsForSelect2,
//
//                'by_identifier' => $optionsForSelect2ByIdentifier,
//
//            ]);
//
//            wp_die();
            /**
             * --- Pagination + Search ---
             */
            //Old functionality with pagination
//            $page = isset($_POST['page']) ? (int)$_POST['page'] : 1;
//            $per_page = 50;
//            $offset = ($page - 1) * $per_page;
//            $search = isset($_POST['q']) ? sanitize_text_field($_POST['q']) : '';
//
//            // Searching
//            if ($search) {
//                $optionsForSelect2 = array_filter($optionsForSelect2, function ($item) use ($search) {
//                    return stripos($item['first_line'], $search) !== false
//                        || stripos($item['second_line'], $search) !== false
//                        || stripos($item['text'], $search) !== false;
//                });
//                $optionsForSelect2 = array_values($optionsForSelect2);
//            }
//
//            $total = count($optionsForSelect2);
//            $paged = array_slice($optionsForSelect2, $offset, $per_page);
//
//            $response = [
//                'results' => $paged,
//                'pagination' => [
//                    'more' => ($offset + $per_page) < $total
//                ]
//            ];
//
//            echo json_encode($response);
//            wp_die();
            //New functionality
            $all_pickups = [];
            foreach ($optionsForSelect2 as $city_group) {
                if (!empty($city_group['children'])) {
                    foreach ($city_group['children'] as $pickup) {
                        // Add city info if needed
                        $pickup['city'] = $city_group['text'];
                        $all_pickups[] = $pickup;
                    }
                }
            }
            // Filter by search term
            $search = isset($_POST['q']) ? sanitize_text_field($_POST['q']) : '';
            if (!empty($search)) {
                $search = mb_strtolower($search); // normalize search term
                $all_pickups = array_filter($all_pickups, function($pickup) use ($search) {
                    $haystack = strtolower($pickup['text'] . ' ' . ($pickup['first_line'] ?? '') . ' ' . ($pickup['second_line'] ?? '') . ' ' . ($pickup['city'] ?? ''));
                    return strpos($haystack, $search) !== false;
                });
            }
            // Pagination
            $per_page = 20;        // items per page
            $page = isset($_POST['page']) ? (int) $_POST['page'] : 1;
            $total_items = count($all_pickups);
            $total_pages = ceil($total_items / $per_page);
            $offset = ($page - 1) * $per_page;
            $paginated_items = array_slice($all_pickups, $offset, $per_page);
            // Group by city
            $grouped = [];
            foreach ($paginated_items as $pickup) {
                $city = $pickup['city'] ?? 'Other';
                if (!isset($grouped[$city])) {
                    $grouped[$city] = [
                        'text' => $city,
                        'children' => []
                    ];
                }
                $grouped[$city]['children'][] = [
                    'id' => $pickup['id'] ?? ($pickup['identifier'] ?? ''),
                    'text' => $pickup['text'] ?? sprintf("%s, %s, %s", $pickup['name'] ?? '', $pickup['address'] ?? '', $pickup['city'] ?? ''),
                    'first_line' => $pickup['first_line'] ?? '',
                    'second_line' => $pickup['second_line'] ?? '',
                    'location' => $pickup['location'] ?? $pickup,
                ];
            }
            // Convert to indexed array for Select2
            $results = array_values($grouped);
            $response = [
                'results' => $results,
                'pagination' => [
                    'more' => $page < $total_pages
                ]
            ];
            wp_send_json($response);
        }
        public function checkout_save_terminal_value_theme_divi()
        {
            if ( ! wp_verify_nonce( $_POST['nonce'], 'wc_store_api' ) ) {
                return;
            }
            $selected_terminal_value = sanitize_text_field($_REQUEST['selected_value']);
            WC()->session->set( 'multiparcels_pickup_location_value', $selected_terminal_value );
        }
        public function checkout_get_pickup_points_classic()
        {
//            if ( ! wp_verify_nonce( $_POST['nonce'], 'wc_store_api' ) ) {
//                return;
//            }
            $country = WC()->customer->get_shipping_country() ?: WC()->customer->get_billing_country();
            $city    = WC()->customer->get_shipping_city() ?: '';
            if (isset($_POST['country'])) $country = sanitize_text_field($_POST['country']);
            if (isset($_POST['city']))    $city = sanitize_text_field($_POST['city']);
            if (isset($_POST['s_country']) && $_POST['s_country'] != $country) {
                $country = sanitize_text_field($_POST['s_country']);
            }
            $shipping_method = array_values(WC()->session->get('chosen_shipping_methods'))[0];
            $carrier = strpos($shipping_method, 'bus') ?
                MultiParcels()->carriers->extract_from_method($shipping_method, false) :
                MultiParcels()->carriers->extract_from_method($shipping_method, true);
            // Determine pickup type
            $type = null;
            if (strpos($shipping_method, '_' . WC_MP_Shipping_Method::SUFFIX_TERMINAL) !== false) $type = WC_MP_Shipping_Method::SUFFIX_TERMINAL;
            if (strpos($shipping_method, '_' . WC_MP_Shipping_Helper::CARRIER_POST_LV_POST) !== false) $type = 'post_office';
            if (MultiParcels()->locations->is_delivery_to_latvian_post_office($shipping_method)) $type = 'post_office';
            // Fetch all pickup points
            $options = MultiParcels()->locations->get_for_city($carrier, $city, $country, $type);
            //Old before update
//            // Flatten all options for Select2
//            $all_options = [];
//            foreach ($options as $city_group) {
//                if (isset($city_group['children'])) {
//                    foreach ($city_group['children'] as $item) {
//                        $all_options[] = $item;
//                    }
//                } else {
//                    $all_options[] = $city_group;
//                }
//            }
//
//            $all_options_mapped = [];
//
//            foreach ($all_options as $item) {
//                foreach ($item as $key => $loc) {
//                    // Remove everything up to and including the first space
//                    if ($carrier == 'itella') {
//                        $result = preg_replace('/^[^ ]* /', '', $loc['name']);
//                    } else {
//                        $result = $loc['name'];
//                    }
//
//                    $all_options_mapped[] = [
//                        'id' => $loc['identifier'], // unique ID
//                        'first_line' => $result, // main name
//                        'second_line' => sprintf("%s, %s, %s", $loc['address'], $loc['city'], $loc['postal_code']),
//                        'text' => sprintf("%s, %s, %s, %s", $result, $loc['address'], $loc['city'], $loc['postal_code']),
//                        'location' => $loc, // keep original for reference
//                    ];
//
//                }
//            }
//
//            // Filter by search term
//
//            $search = isset($_POST['q']) ? sanitize_text_field($_POST['q']) : '';
//            if (!empty($search)) {
//                $search = mb_strtolower($search); // normalize search term
//                $all_options_mapped = array_values(array_filter($all_options_mapped, function ($item) use ($search) {
//                    $first = isset($item['first_line']) ? mb_strtolower($item['first_line']) : '';
//                    $second = isset($item['second_line']) ? mb_strtolower($item['second_line']) : '';
//                    // partial match anywhere in the string
//                    return mb_strpos($first, $search) !== false || mb_strpos($second, $search) !== false;
//                }));
//            }
//
//            // Pagination
//            $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
//            $per_page = 20;
//            $total_count = count($all_options_mapped);
//            $offset = ($page - 1) * $per_page;
//            $paged_options = array_slice($all_options_mapped, $offset, $per_page);
//
//            // Prepare Select2 items
//            $items = [];
//            // Add first placeholder option
//            $items[] = [
//                'id' => '', // empty value
//                'first_line' => __('Please select pickup point', 'multiparcels-shipping-for-woocommerce'),
//                'second_line' => '',
//                'text' => __('Please select pickup point', 'multiparcels-shipping-for-woocommerce'),
//                'location' => null,
//            ];
//            foreach ($paged_options as $item) {
//                $items[] = [
//                    'id' => $item['id'] ?? $item['identifier'],
//                    'first_line' => $item['first_line'] ?? $item['name'],
//                    'second_line' => $item['second_line'] ?? sprintf("%s, %s, %s", $item['address'], $item['city'], $item['postal_code'] ?? ''),
//                    'text' => $item['text'] ?? sprintf("%s, %s, %s", $item['name'], $item['address'], $item['city']),
//                    'location' => $item['location'] ?? $item,
//                ];
//            }
//
//            // Return JSON for SelectWoo
//            wp_send_json([
//                'items' => $items,
//                'total_count' => $total_count,
//            ]);
            //New functionality with group by city
//            $optionsForSelect2 = [];
//            foreach ($options as $city => $group) {
//                $locations = [];
//                foreach ($group as $item) {
//                    if ($carrier == 'itella') {
//                        $result = preg_replace('/^[^ ]* /', '', $item['name']);
//                    } else {
//                        $result = $item['name'];
//                    }
//
//                    $locations[] = [
//                        'id' => $item['identifier'], // unique ID
//                        'first_line_search' => MultiParcels()->locations->latin_only($result),
//                        'first_line' => $result, // main name
//                        'second_line_search' => sprintf("%s, %s, %s", MultiParcels()->locations->latin_only($item['address']), MultiParcels()->locations->latin_only($item['city']), $item['postal_code']),
//                        'second_line' => sprintf("%s, %s, %s", $item['address'], $item['city'], $item['postal_code']),
//                        'text' => sprintf("%s, %s, %s, %s", $result, $item['address'], $item['city'], $item['postal_code']),
//                        'text_search' => sprintf("%s, %s, %s, %s", MultiParcels()->locations->latin_only($result), MultiParcels()->locations->latin_only($item['address']), MultiParcels()->locations->latin_only($item['city']), $item['postal_code']),
//                        'location' => $item, // keep original for reference
//                    ];
//                }
//
//                if (count($locations)) {
//
//                    // group by city
//
//                    $optionsForSelect2[] = [
//
////                        'text'     => $city,
//                        'text'     => ucfirst($city),
//
//                        'children' => $locations,
//
//                    ];
//
//                }
//            }
            if ($carrier == 'siuntos_autobusais') {
                $city_option = MultiParcels()->options->get('extra_cities_siuntos_autobusais', true);
                $siuntos_autobusais_pickup_city_option = MultiParcels()->options->get('extra_siuntos_autobusais_pickup_cities_siuntos_autobusais', true);
                if($siuntos_autobusais_pickup_city_option) {
                    foreach ($city_option as $key => $city) {
                        $search = [];
                        $search[] = 'courier_code:'.$carrier;
                        $search[] = 'method:'.$city;
                        $response = MultiParcels()->api_client->request('api/translate/mp/locations', 'GET', [
                            'limit' => 99999,
                            'search' => implode(';', $search),
                            'searchJoin' => 'and',
                        ]);
                        if ($response->was_successful()) {
                            $locations = $response->get_data();
                            $options = [];
                            foreach ($locations as $key => $location) {
                                if ($siuntos_autobusais_pickup_city_option) {
                                    $siuntos_autobusais_pickup_city_option= array_map(function($word) { return MultiParcels()->helper->latin_characters($word) ;},$siuntos_autobusais_pickup_city_option);
                                    $siuntos_autobusais_pickup_point_key = array_search(MultiParcels()->helper->latin_characters($location['city']),$siuntos_autobusais_pickup_city_option);
                                    if ($siuntos_autobusais_pickup_point_key) {
                                        if (str_contains($shipping_method, 'siuntos_autobusais_courier')) {
                                            if ($location['custom_fields']['kr']) {
                                                $preparedItem        = [
                                                    'id'          => $location['identifier'],
                                                    'city'        => $location['city'],
                                                    'first_line_search' => MultiParcels()->locations->latin_only($location['name']),
                                                    'first_line'  => $location['name'],
                                                    'second_line_search' => sprintf("%s, %s, %s", MultiParcels()->locations->latin_only($location['address']), MultiParcels()->locations->latin_only($location['city']),
                                                        $location['postal_code']),
                                                    'second_line' => sprintf("%s, %s, %s", $location['address'], $location['city'],
                                                        $location['postal_code']),
                                                    'text'        => sprintf("%s, %s, %s", $location['name'], $location['address'],
                                                        $location['city']),
                                                    'text_search'        => sprintf("%s, %s, %s", MultiParcels()->locations->latin_only($location['name']), MultiParcels()->locations->latin_only($location['address']),
                                                        MultiParcels()->locations->latin_only($location['city'])),
                                                    'location'    => $location,
                                                ];
                                                $options[] = $preparedItem;
                                            }
                                        }else {
                                            $preparedItem        = [
                                                'id'          => $location['identifier'],
                                                'city'        => $location['city'],
                                                'first_line_search' => MultiParcels()->locations->latin_only($location['name']),
                                                'first_line'  => $location['name'],
                                                'second_line_search' => sprintf("%s, %s, %s", MultiParcels()->locations->latin_only($location['address']), MultiParcels()->locations->latin_only($location['city']),
                                                    $location['postal_code']),
                                                'second_line' => sprintf("%s, %s, %s", $location['address'], $location['city'],
                                                    $location['postal_code']),
                                                'text'        => sprintf("%s, %s, %s", $location['name'], $location['address'],
                                                    $location['city']),
                                                'text_search'        => sprintf("%s, %s, %s", MultiParcels()->locations->latin_only($location['name']), MultiParcels()->locations->latin_only($location['address']),
                                                    MultiParcels()->locations->latin_only($location['city'])),
                                                'location'    => $location,
                                            ];
                                            $options[] = $preparedItem;
                                        }
                                    }
                                }else {
                                    if (str_contains($shipping_method, 'siuntos_autobusais_courier')) {
                                        if ($location['custom_fields']['kr']) {
                                            $preparedItem        = [
                                                'id'          => $location['identifier'],
                                                'city'        => $location['city'],
                                                'first_line'  => $location['name'],
                                                'first_line_search'  => MultiParcels()->locations->latin_only($location['name']),
                                                'second_line' => sprintf("%s, %s, %s", $location['address'], $location['city'],
                                                    $location['postal_code']),
                                                'second_line_search' => sprintf("%s, %s, %s", MultiParcels()->locations->latin_only($location['address']), MultiParcels()->locations->latin_only($location['city']),
                                                    $location['postal_code']),
                                                'text'        => sprintf("%s, %s, %s", $location['name'], $location['address'],
                                                    $location['city']),
                                                'text_search'        => sprintf("%s, %s, %s", MultiParcels()->locations->latin_only($location['name']), MultiParcels()->locations->latin_only($location['address']),
                                                    MultiParcels()->locations->latin_only($location['city'])),
                                                'location'    => $location,
                                            ];
                                        }
                                    }else {
                                        $preparedItem        = [
                                            'id'          => $location['identifier'],
                                            'city'        => $location['city'],
                                            'first_line'  => $location['name'],
                                            'first_line_search'  => MultiParcels()->locations->latin_only($location['name']),
                                            'second_line' => sprintf("%s, %s, %s", $location['address'], $location['city'],
                                                $location['postal_code']),
                                            'second_line_search' => sprintf("%s, %s, %s", MultiParcels()->locations->latin_only($location['address']), MultiParcels()->locations->latin_only($location['city']),
                                                $location['postal_code']),
                                            'text'        => sprintf("%s, %s, %s", $location['name'], $location['address'],
                                                $location['city']),
                                            'text_search'        => sprintf("%s, %s, %s", MultiParcels()->locations->latin_only($location['name']), MultiParcels()->locations->latin_only($location['address']),
                                                MultiParcels()->locations->latin_only($location['city'])),
                                            'location'    => $location,
                                        ];
                                    }
                                    $options[] = $preparedItem;
                                }
                            }
                        }
                    }
                }
                $grouped = [];
                foreach ($options as $option) {
                    $city = $option['city'];
                    $grouped[$city][] = $option;
                }
                $optionsForSelect2 = [];
                foreach ($grouped as $grouped_key => $grouped_option) {
                    $optionsForSelect2[] = [
                        'text'     => ucfirst($grouped_key),
                        'children' => $grouped_option,
                    ];
                }
            } else {
                $optionsForSelect2 = [];
                foreach ($options as $city => $group) {
                    $locations = [];
                    foreach ($group as $item) {
                        if ($carrier == 'itella') {
                            $result = preg_replace('/^[^ ]* /', '', $item['name']);
                        } else {
                            $result = $item['name'];
                        }
                        if ($carrier == 'post_lv') {
                            $locations[] = [
                                'id' => $item['id'], // unique ID
                                'first_line_search' => MultiParcels()->locations->latin_only($result),
                                'first_line' => $result, // main name
                                'second_line_search' => sprintf("%s, %s, %s", MultiParcels()->locations->latin_only($item['address']), MultiParcels()->locations->latin_only($item['city']), $item['postal_code']),
                                'second_line' => sprintf("%s, %s, %s", $item['address'], $item['city'], $item['postal_code']),
                                'text' => sprintf("%s, %s, %s, %s", $result, $item['address'], $item['city'], $item['postal_code']),
                                'text_search' => sprintf("%s, %s, %s, %s", MultiParcels()->locations->latin_only($result), MultiParcels()->locations->latin_only($item['address']), MultiParcels()->locations->latin_only($item['city']), $item['postal_code']),
                                'location' => $item, // keep original for reference
                            ];
                        } else {
                            $locations[] = [
                                'id' => $item['identifier'], // unique ID
                                'first_line_search' => MultiParcels()->locations->latin_only($result),
                                'first_line' => $result, // main name
                                'second_line_search' => sprintf("%s, %s, %s", MultiParcels()->locations->latin_only($item['address']), MultiParcels()->locations->latin_only($item['city']), $item['postal_code']),
                                'second_line' => sprintf("%s, %s, %s", $item['address'], $item['city'], $item['postal_code']),
                                'text' => sprintf("%s, %s, %s, %s", $result, $item['address'], $item['city'], $item['postal_code']),
                                'text_search' => sprintf("%s, %s, %s, %s", MultiParcels()->locations->latin_only($result), MultiParcels()->locations->latin_only($item['address']), MultiParcels()->locations->latin_only($item['city']), $item['postal_code']),
                                'location' => $item, // keep original for reference
                            ];
                        }
                    }
                    if (count($locations)) {
                        // group by city
                        $optionsForSelect2[] = [
//                        'text'     => $city,
                            'text'     => ucfirst($city),
                            'children' => $locations,
                        ];
                    }
                }
            }
            $all_pickups = [];
            foreach ($optionsForSelect2 as $city_group) {
                if (!empty($city_group['children'])) {
                    foreach ($city_group['children'] as $pickup) {
                        // Add city info if needed
                        $pickup['city'] = $city_group['text'];
                        $pickup['city_search'] = MultiParcels()->locations->latin_only($city_group['text']);
                        $all_pickups[] = $pickup;
                    }
                }
            }
            // Filter by search term
            $search = isset($_POST['q']) ? sanitize_text_field($_POST['q']) : '';
            if (!empty($search)) {
                $search = Multiparcels()->locations->latin_only(mb_strtolower($search)); // normalize search term
                $all_pickups = array_filter($all_pickups, function($pickup) use ($search) {
                    $haystack = strtolower($pickup['text_search'] . ' ' . ($pickup['first_line_search'] ?? '') . ' ' . ($pickup['second_line_search'] ?? '') . ' ' . ($pickup['city_search'] ?? ''));
                    return strpos($haystack, $search) !== false;
                });
            }
            // Pagination
            $per_page = 20;        // items per page
            $page = isset($_POST['page']) ? (int) $_POST['page'] : 1;
            $total_items = count($all_pickups);
            $total_pages = ceil($total_items / $per_page);
            $offset = ($page - 1) * $per_page;
            $paginated_items = array_slice($all_pickups, $offset, $per_page);
            // Group by city
            $grouped = [];
            foreach ($paginated_items as $pickup) {
                $city = $pickup['city'] ?? 'Other';
                if (!isset($grouped[$city])) {
                    $grouped[$city] = [
                        'text' => $city,
                        'children' => []
                    ];
                }
                $grouped[$city]['children'][] = [
                    'id' => $pickup['id'] ?? ($pickup['identifier'] ?? ''),
                    'text' => $pickup['text'] ?? sprintf("%s, %s, %s", $pickup['name'] ?? '', $pickup['address'] ?? '', $pickup['city'] ?? ''),
                    'first_line' => $pickup['first_line'] ?? '',
                    'second_line' => $pickup['second_line'] ?? '',
                    'location' => $pickup['location'] ?? $pickup,
                ];
            }
            // Convert to indexed array for Select2
            $results = array_values($grouped);
            $response = [
                'results' => $results,
                'pagination' => [
                    'more' => $page < $total_pages
                ]
            ];
            wp_send_json($response);
        }
        public function checkout_get_pickup_points()
        {
            if ( ! wp_verify_nonce( $_POST['nonce'], 'wc_store_api' ) ) {
                return;
            }
            $country = null;
            $city    = null;
            $shipping_method = array_values(WC()->session->get('chosen_shipping_methods'))[0];
            if(strpos($shipping_method, 'bus')) {
                $carrier = MultiParcels()->carriers->extract_from_method($shipping_method, false);
            } else {
                $carrier = MultiParcels()->carriers->extract_from_method($shipping_method, true);
            }
            if (WC()->customer->get_shipping_city()) {
                $city = WC()->customer->get_shipping_city();
            }
            if (WC()->customer->get_billing_country()) {
                $country = WC()->customer->get_billing_country();
            }
            if (WC()->customer->get_shipping_country()) {
                $country = WC()->customer->get_shipping_country();
            }
            if (isset($_POST['city'])) {
                $city = $_POST['city'];
            }
            if (isset($_POST['country'])) {
                $country = $_POST['country'];
            }
            $city    = sanitize_text_field($city);
            $country = sanitize_text_field($country);
            if (isset($_POST['s_country']) && $_POST['s_country'] != $country) {
                $country = $_POST['s_country'];
            }
            $type = null;
            if (strpos($shipping_method, '_'.WC_MP_Shipping_Method::SUFFIX_TERMINAL) !== false) {
                $type = WC_MP_Shipping_Method::SUFFIX_TERMINAL;
            }
            if (strpos($shipping_method, '_'.WC_MP_Shipping_Helper::CARRIER_POST_LV_POST) !== false) {
                $type = 'post_office';
            }
            if (MultiParcels()->locations->is_delivery_to_latvian_post_office($shipping_method)) {
                $type = 'post_office';
            }
            if ($carrier == WC_MP_Shipping_Helper::CARRIER_VENIPAK) {
                $instance_id = 0;
                $explode     = explode(':', $shipping_method);
                $shipping_id = $explode[0];
                if (count($explode) == 2) {
                    $instance_id = $explode[1];
                }
                $methods = WC()->shipping()->get_shipping_methods();
                if (array_key_exists($shipping_id, $methods)) {
                    $class_name = get_class(WC()->shipping()->get_shipping_methods()[$shipping_id]);
                    /** @var WC_MP_Shipping_Method $shipping_class */
                    $shipping_class = new $class_name($instance_id);
                    $only = $shipping_class->get_option(WC_MP_Shipping_Method::OPTION_VENIPAK_DISPLAYED_PICKUP_POINTS);
                    if ($only) {
                        if ($only == 'terminals') {
                            $type = WC_MP_Shipping_Method::SUFFIX_TERMINAL;
                        }
                        if ($only == 'pickup_points') {
                            $type = WC_MP_Shipping_Method::SUFFIX_PICKUP_POINT;
                        }
                    }
                }
            }
            $options = MultiParcels()->locations->get_for_city($carrier, $city, $country, $type);
            if ($carrier == 'siuntos_autobusais') {
                $city_option = MultiParcels()->options->get('extra_cities_siuntos_autobusais', true);
                $siuntos_autobusais_pickup_city_option = MultiParcels()->options->get('extra_siuntos_autobusais_pickup_cities_siuntos_autobusais', true);
                if($siuntos_autobusais_pickup_city_option) {
                    foreach ($city_option as $key => $city) {
                        $search = [];
                        $search[] = 'courier_code:'.$carrier;
                        $search[] = 'method:'.$city;
//                        $response = MultiParcels()->api_client->request('locations_for_shops', 'GET', [
//
//                            'limit' => 99999,
//
//                            'search' => implode(';', $search),
//
//                            'searchJoin' => 'and',
//
//                        ]);
                        $response = MultiParcels()->api_client->request('api/translate/mp/locations', 'GET', [
                            'limit' => 99999,
                            'search' => implode(';', $search),
                            'searchJoin' => 'and',
                        ]);
                        if ($response->was_successful()) {
                            $locations = $response->get_data();
                            $options = [];
                            foreach ($locations as $key => $location) {
                                if ($siuntos_autobusais_pickup_city_option) {
//                            $siuntos_autobusais_pickup_point_key = array_search($location['city'], $siuntos_autobusais_pickup_city_option);
                                    $siuntos_autobusais_pickup_city_option= array_map(function($word) { return MultiParcels()->helper->latin_characters($word) ;},$siuntos_autobusais_pickup_city_option);
                                    $siuntos_autobusais_pickup_point_key = array_search(MultiParcels()->helper->latin_characters($location['city']),$siuntos_autobusais_pickup_city_option);
                                    if ($siuntos_autobusais_pickup_point_key) {
                                        if (str_contains($shipping_method, 'siuntos_autobusais_courier')) {
                                            if ($location['custom_fields']['kr']) {
                                                $preparedItem        = [
                                                    'id'          => $location['identifier'],
                                                    'first_line'  => $location['name'],
                                                    'second_line' => sprintf("%s, %s, %s", $location['address'], $location['city'],
                                                        $item['postal_code']),
//                            'text'        => sprintf("%s, %s, %s, %s", $location['name'], $location['address'],
//
//                                $location['city'], $location['postal_code']),
                                                    'text'        => sprintf("%s, %s, %s", $location['name'], $location['address'],
                                                        $location['city']),
                                                    'location'    => $location,
                                                ];
                                                $options[] = $preparedItem;
                                            }
                                        }else {
                                            $preparedItem        = [
                                                'id'          => $location['identifier'],
                                                'first_line'  => $location['name'],
                                                'second_line' => sprintf("%s, %s, %s", $location['address'], $location['city'],
                                                    $item['postal_code']),
//                            'text'        => sprintf("%s, %s, %s, %s", $location['name'], $location['address'],
//
//                                $location['city'], $location['postal_code']),
                                                'text'        => sprintf("%s, %s, %s", $location['name'], $location['address'],
                                                    $location['city']),
                                                'location'    => $location,
                                            ];
                                            $options[] = $preparedItem;
                                        }
                                    }
                                }else {
                                    if (str_contains($shipping_method, 'siuntos_autobusais_courier')) {
                                        if ($location['custom_fields']['kr']) {
                                            $preparedItem        = [
                                                'id'          => $location['identifier'],
                                                'first_line'  => $location['name'],
                                                'second_line' => sprintf("%s, %s, %s", $location['address'], $location['city'],
                                                    $item['postal_code']),
//                            'text'        => sprintf("%s, %s, %s, %s", $location['name'], $location['address'],
//
//                                $location['city'], $location['postal_code']),
                                                'text'        => sprintf("%s, %s, %s", $location['name'], $location['address'],
                                                    $location['city']),
                                                'location'    => $location,
                                            ];
                                        }
                                    }else {
                                        $preparedItem        = [
                                            'id'          => $location['identifier'],
                                            'first_line'  => $location['name'],
                                            'second_line' => sprintf("%s, %s, %s", $location['address'], $location['city'],
                                                $item['postal_code']),
//                            'text'        => sprintf("%s, %s, %s, %s", $location['name'], $location['address'],
//
//                                $location['city'], $location['postal_code']),
                                            'text'        => sprintf("%s, %s, %s", $location['name'], $location['address'],
                                                $location['city']),
                                            'location'    => $location,
                                        ];
                                    }
                                    $options[] = $preparedItem;
                                }
                            }
                        }
                    }
                }else {
                    $search = [];
                    $search[] = 'courier_code:'.$carrier;
//                    $response = MultiParcels()->api_client->request('locations_for_shops', 'GET', [
//
//                        'limit' => 99999,
//
//                        'search' => implode(';', $search),
//
//                        'searchJoin' => 'and',
//
//                    ]);
                    $response = MultiParcels()->api_client->request('api/translate/mp/locations', 'GET', [
                        'limit' => 99999,
                        'search' => implode(';', $search),
                        'searchJoin' => 'and',
                    ]);
                    if ($response->was_successful()) {
                        $options = $response->get_data();
                    }
                }
//                $search = [];
//
//                $search[] = 'courier_code:'.$carrier;
//
//                $search[] = 'method:'.$city;
//
//
//
//                $response = MultiParcels()->api_client->request('locations_for_shops', 'GET', [
//
//                    'limit' => 99999,
//
//                    'search' => implode(';', $search),
//
//                    'searchJoin' => 'and',
//
//                ]);
//
//
//                if ($response->was_successful()) {
//                    $options = $response->get_data();
//                }
            } else {
                $options = MultiParcels()->locations->get_for_city($carrier, $city, $country, $type);
            }
//            if ($carrier != 'siuntos_autobusais') {
//
//            }
            if ($carrier != 'siuntos_autobusais') {
                if ($type != 'post_office') {
                    // remove post_offices because we only need them when it is post_lv
                    foreach ($options as $city => $locations) {
                        foreach ($locations as $key => $location) {
                            if ($location['type'] == 'post_office') {
                                unset($options[$city][$key]);
                            }
                        }
                    }
                }
            }
            $optionsForSelect2 = [];
            $optionsForSelect2ByIdentifier = [];
            $optionsForSelect2[] = [
                'id'          => '',
                'first_line'  => __('Please select the pickup location', 'multiparcels-shipping-for-woocommerce'),
                'second_line' => '',
                'text'        => __('Please select the pickup location', 'multiparcels-shipping-for-woocommerce'),
            ];
            if ($carrier != 'siuntos_autobusais') {
                foreach ($options as $city => $group) {
                    $locations = [];
                    foreach ($group as $item) {
                        if($carrier == 'post_lv') {
                            $preparedItem        = [
                                'id'          => $item['id'],
                                'first_line'  => $item['name'],
                                'second_line' => sprintf("%s, %s, %s", $item['address'], $item['city'],
                                    $item['postal_code']),
                                'text'        => sprintf("%s, %s, %s, %s", $item['name'], $item['address'],
                                    $item['city'], $item['postal_code']),
                                'location'    => $item,
                            ];
                        } else {
                            $preparedItem        = [
                                'id'          => $item['identifier'],
                                'first_line'  => $item['name'],
                                'second_line' => sprintf("%s, %s, %s", $item['address'], $item['city'],
                                    $item['postal_code']),
                                'text'        => sprintf("%s, %s, %s, %s", $item['name'], $item['address'],
                                    $item['city'], $item['postal_code']),
                                'location'    => $item,
                            ];
                        }
                        if (MultiParcels()->options->get('show_all_cities') === "2" || MultiParcels()->options->get('show_all_cities') === 2) {
                            $locations[] = $preparedItem;
                        } else {
                            $optionsForSelect2[] = $preparedItem;
                        }
                        $optionsForSelect2ByIdentifier[$item['identifier']] = $preparedItem;
                    }
                    if (count($locations)) {
                        // group by city
                        $optionsForSelect2[] = [
                            'text'     => $city,
                            'children' => $locations,
                        ];
                    }
                }
            } else {
                $siuntos_autobusais_pickup_city_option = MultiParcels()->options->get('extra_siuntos_autobusais_pickup_cities_siuntos_autobusais', true);
                foreach ($options as $key => $option) {
                    if ($siuntos_autobusais_pickup_city_option) {
//                        $siuntos_autobusais_pickup_point_key = array_search($option['city'], $siuntos_autobusais_pickup_city_option);
                        $siuntos_autobusais_pickup_city_option= array_map(function($word) { return MultiParcels()->helper->latin_characters($word) ;},$siuntos_autobusais_pickup_city_option);
                        $siuntos_autobusais_pickup_point_key = array_search(MultiParcels()->helper->latin_characters($option['location']['city']),$siuntos_autobusais_pickup_city_option);
                        if ($siuntos_autobusais_pickup_point_key) {
                            if (str_contains($shipping_method, 'siuntos_autobusais_courier')) {
                                if ($option['location']['custom_fields']['kr']) {
                                    $preparedItem        = [
                                        'id'          => $option['location']['identifier'],
                                        'first_line'  => $option['location']['name'],
                                        'second_line' => sprintf("%s, %s, %s", $option['location']['address'], $option['location']['city'],
                                            $option['location']['postal_code']),
                                        'text'        => sprintf("%s, %s, %s, %s", $option['location']['name'], $option['location']['address'],
                                            $option['location']['city'], $option['postal_code']),
                                        'location'    => $option,
                                    ];
                                }
                            }else {
                                $preparedItem        = [
                                    'id'          => $option['location']['identifier'],
                                    'first_line'  => $option['location']['name'],
                                    'second_line' => sprintf("%s, %s, %s", $option['location']['address'], $option['location']['city'],
                                        $option['location']['postal_code']),
                                    'text'        => sprintf("%s, %s, %s, %s", $option['location']['name'], $option['location']['address'],
                                        $option['location']['city'], $option['postal_code']),
                                    'location'    => $option,
                                ];
                            }
                            $optionsForSelect2[] = $preparedItem;
                            $optionsForSelect2ByIdentifier[$option['location']['identifier']] = $preparedItem;
                        }
                    }else {
                        if (str_contains($shipping_method, 'siuntos_autobusais_courier')) {
                            if ($option['location']['custom_fields']['kr']) {
                                $preparedItem        = [
                                    'id'          => $option['identifier'],
                                    'first_line'  => $option['name'],
                                    'second_line' => sprintf("%s, %s, %s", $option['address'], $option['city'],
                                        $option['postal_code']),
                                    'text'        => sprintf("%s, %s, %s, %s", $option['name'], $option['address'],
                                        $option['city'], $option['postal_code']),
                                    'location'    => $option,
                                ];
                                $optionsForSelect2[] = $preparedItem;
                                $optionsForSelect2ByIdentifier[$option['location']['identifier']] = $preparedItem;
                            }
                        }else {
                            $preparedItem        = [
                                'id'          => $option['identifier'],
                                'first_line'  => $option['name'],
                                'second_line' => sprintf("%s, %s, %s", $option['address'], $option['city'],
                                    $option['postal_code']),
                                'text'        => sprintf("%s, %s, %s, %s", $option['name'], $option['address'],
                                    $option['city'], $option['postal_code']),
                                'location'    => $option,
                            ];
                            $optionsForSelect2[] = $preparedItem;
                            $optionsForSelect2ByIdentifier[$option['identifier']] = $preparedItem;
                        }
                    }
                }
            }
            echo json_encode([
                'all'           => $optionsForSelect2,
                'by_identifier' => $optionsForSelect2ByIdentifier,
            ]);
            wp_die();
        }
        /**
         * @param WC_Order $order
         * @param $sent_to_admin
         * @param bool $plain_text
         * @param WC_Email $email
         */
        public function email_instructions( $order, $sent_to_admin, $plain_text = false, $email = false ) {
            if (class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )) {
                if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
                    // HPOS usage is enabled.
                    $tracking_code = $order->get_meta(MP_Woocommerce_Order_Shipping::TRACKING_CODE_KEY, true);
                }else {
                    // Traditional CPT-based orders are in use.
                    $tracking_code = get_post_meta( $order->get_id(), MP_Woocommerce_Order_Shipping::TRACKING_CODE_KEY, true );
                }
            } else {
                // Traditional CPT-based orders are in use.
                $tracking_code = get_post_meta( $order->get_id(), MP_Woocommerce_Order_Shipping::TRACKING_CODE_KEY, true );
            }
            if ( $tracking_code ) {
                if ( ! $plain_text ) {
                    $tracking_code = sprintf( "<strong>%s</strong>", $tracking_code );
                    if (class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )) {
                        if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
                            // HPOS usage is enabled.
                            $tracking_link = $order->get_meta(MP_Woocommerce_Order_Shipping::TRACKING_LINK_KEY, true);
                        }else {
                            // Traditional CPT-based orders are in use.
                            $tracking_link = get_post_meta( $order->get_id(), MP_Woocommerce_Order_Shipping::TRACKING_LINK_KEY, true);
                        }
                    } else {
                        // Traditional CPT-based orders are in use.
                        $tracking_link = get_post_meta( $order->get_id(), MP_Woocommerce_Order_Shipping::TRACKING_LINK_KEY, true);
                    }
                    if ( $tracking_link ) {
                        $tracking_code = sprintf( "<a href='%s' target='_blank'>%s</a>",
                            $tracking_link,
                            $tracking_code
                        );
                    }
                }
                $text = __( 'Your order tracking number: %s', 'multiparcels-shipping-for-woocommerce' );
                // Suppress PHPCS warning for unescaped output (base64-encoded binary data)
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                echo wpautop( wptexturize( sprintf( $text, $tracking_code ) ) ) . PHP_EOL;
            }
        }


    }
    new WC_MP_Shipping_Helper();
}