<?php
use Woo_BG\File;

function woo_bg_assets_bundle( $path ) {
	static $manifest = null;

	if ( is_null( $manifest ) ) {
		$manifest_path = woo_bg()->plugin_dir_path() . 'dist/manifest.json';

		if ( file_exists( $manifest_path ) ) {
			$manifest = json_decode( File::get_file( $manifest_path ), true );
		} else {
			$manifest = array();
		}
	}

	$path = isset( $manifest[ $path ] ) ? $manifest[ $path ] : $path;

	return 'dist/' . $path;
}

function woo_bg_get_option( $group, $name ) {
	return get_option( 'woo_bg_settings_' . $group . '_' . $name );
}

function woo_bg_set_option( $group, $name, $value ) {
	return update_option( 'woo_bg_settings_' . $group . '_' . $name, $value );
}

function woo_bg_get_vat_groups() {
	return array(
		'a' => '0',
		'b' => '20',
		'g' => '9',
	);
}

function woo_bg_get_return_methods() {
	return array(
		1 => array(
			'id' => 1,
			'label' => __( 'On a payment account', 'bulgarisation-for-woocommerce' ),
		),
		2 => array(
			'id' => 2,
			'label' => __( 'Card', 'bulgarisation-for-woocommerce' ),
		),
		3 => array(
			'id' => 3,
			'label' => __( 'Cash', 'bulgarisation-for-woocommerce' ),
		),
		4 => array(
			'id' => 4,
			'label' => __( 'Other', 'bulgarisation-for-woocommerce' ),
		),
	);
}

function woo_bg_get_yes_no_options() {
	return array(
		'no' => array(
			'id' => 'no',
			'label' => __( 'No', 'bulgarisation-for-woocommerce' ),
		),
		'yes' => array(
			'id' => 'yes',
			'label' => __( 'Yes', 'bulgarisation-for-woocommerce' ),
		),
	);
}

function woo_bg_get_payment_types() {
	return array(
		1 => array(
			'id' => 1,
			'label' => __( 'Released under Art. 3 payment without PPP', 'bulgarisation-for-woocommerce' ),
		),
		2 => array(
			'id' => 2,
			'label' => __( 'Virtual POS terminal', 'bulgarisation-for-woocommerce' ),
		),
		3 => array(
			'id' => 3,
			'label' => __( 'Cash on delivery with PPP', 'bulgarisation-for-woocommerce' ),
		),
		4 => array(
			'id' => 4,
			'label' => __( 'Payment service provider', 'bulgarisation-for-woocommerce' ),
		),
		5 => array(
			'id' => 5,
			'label' => __( 'Other', 'bulgarisation-for-woocommerce' ),
		),
		6 => array(
			'id' => 6,
			'label' => __( 'Reflected with receipt', 'bulgarisation-for-woocommerce' ),
		),
	);
}

function woo_bg_get_payment_types_for_meta() {
	return array(
		'1' => 'WithoutPostPayment', //1
		'2' => 'VirtualPOSTerminal', //2
		'3' => 'WithPostPayment', //3
		'4' => 'PaymentService', //4
		'5' => 'Other', //5
		'6' => 'ReflectedWithReceipt', //6
	);
}

function woo_bg_get_tax_classes() {
	$tax_classes = WC_Tax::get_tax_classes();

	$classes_options = array(
		'standard' => array(
			'id' => 'standard',
			'label' => __( 'Standard', 'bulgarisation-for-woocommerce' ),
		),
	);

	foreach ( $tax_classes as $class ) {
		$slug = sanitize_title( $class );
		$classes_options[ $slug ] = array(
			'id' => $slug,
			'label' => esc_html( $class ),
		);
	}

	return $classes_options;
}


function woo_bg_get_vat_from_order( $order ) {
	if ( !$order ) {
		return '';
	}

	$vat = $order->get_meta( '_billing_vat_number', true ) ? $order->get_meta( '_billing_vat_number', true ) : '';

	if ( !$vat ) {
		$vat = $order->get_meta( '_vat_number', true ) ? $order->get_meta( '_vat_number', true ) : '';
	}

	return $vat;
}

function woo_bg_return_array_for_select( $array, $user_value_for_id = false, $additional_attributes = array() ) {
	$new_array = [];

	if ( !empty( $array ) ) {
		foreach ( $array as $key => $value ) {
			$id = $key;

			if ( $user_value_for_id ) {
				$id = $value;
			}

			$item = array(
				'id' => $id,
				'orig_key' => $key,
				'label' => $value,
			);

			if ( !empty( $additional_attributes ) ) {
				$item = array_merge( $item, $additional_attributes );
			}

			$new_array[] = $item;
		}
	}

	return $new_array;
}

function woo_bg_return_bg_states() {
	return array(
		'' => '',
		'BG-01' => 'Благоевград',
		'BG-02' => 'Бургас',
		'BG-03' => 'Варна',
		'BG-04' => 'Велико Търново',
		'BG-05' => 'Видин',
		'BG-06' => 'Враца',
		'BG-07' => 'Габрово',
		'BG-08' => 'Добрич',
		'BG-09' => 'Кърджали',
		'BG-10' => 'Кюстендил',
		'BG-11' => 'Ловеч',
		'BG-12' => 'Монтана',
		'BG-13' => 'Пазарджик',
		'BG-14' => 'Перник',
		'BG-15' => 'Плевен',
		'BG-16' => 'Пловдив',
		'BG-17' => 'Разград',
		'BG-18' => 'Русе',
		'BG-19' => 'Силистра',
		'BG-20' => 'Сливен',
		'BG-21' => 'Смолян',
		'BG-22' => 'София',
		'BG-23' => 'София Област',
		'BG-24' => 'Стара Загора',
		'BG-25' => 'Търговище',
		'BG-26' => 'Хасково',
		'BG-27' => 'Шумен',
		'BG-28' => 'Ямбол',
	);
}

function woo_bg_support_text() {
	?> 
	<div class="notice notice-info">
		<h3><?php esc_html_e( 'Supporting the development', 'bulgarisation-for-woocommerce' ) ?></h3> 
		
		<?php echo wp_kses_post( wpautop( esc_html__( 'For single donation as development support you can send at ', 'bulgarisation-for-woocommerce' ) . '<a target="_blank" href="https://revolut.me/tihomi9gj5">Revolut</a>' ) ); ?>
	</div>
	<?php
}

function woo_bg_get_shipping_tests_options() {
	return array(
		'no' => __( 'No', 'bulgarisation-for-woocommerce' ),
		'review' => __( 'Review only', 'bulgarisation-for-woocommerce' ),
		'test' => __( 'Review and test', 'bulgarisation-for-woocommerce' ),
	);
}

function woo_bg_get_order_shipping_vat( $order, $show_group = false ) {
	$shipping_vat = 0;

	if ( wc_tax_enabled() && !empty( $order->get_items( 'tax' ) ) ) {
		foreach ( $order->get_items( 'tax' ) as $tax_item ) {
			if ( $tax_item->get_shipping_tax_total() ) {
				$shipping_vat = $tax_item->get_rate_percent();
				break;
			}
		}
	}

	if ( $show_group ) {
		$shipping_vat = woo_bg_maybe_add_rate_group( $shipping_vat );
	}

	return apply_filters( 'woo_bg/order_item/shipping_vat_rate', $shipping_vat, $order );
}

function woo_bg_get_order_item_vat_rate( $item, $order, $show_group = false, $default_rate = false ) {
	$tax_data = wc_tax_enabled() ? $item->get_taxes() : false;

	if ( $default_rate !== false ) {
		$rate = $default_rate;
	} else {
		$vat_group           = woo_bg_get_option( 'shop', 'vat_group' );
		$vat_percentages     = woo_bg_get_vat_groups();
		$rate = ( isset( $vat_percentages[ $vat_group ] ) ) ? $vat_percentages[ $vat_group ] : 0;
	}
	
	if ( $tax_data ) {
		$founded = false;
		$order_taxes = $order->get_taxes();

		foreach ( $order_taxes as $tax_item ) {
			$tax_item_id       = $tax_item->get_rate_id();
			$tax_item_total    = isset( $tax_data['total'][ $tax_item_id ] ) ? $tax_data['total'][ $tax_item_id ] : '';
				
			if ( '' !== $tax_item_total && $tax_item_total > 0 ) {
				$rate = $tax_item->get_rate_percent();
				$founded = true;
				break;
			}
		}

		if ( !$founded ) {
			$rate = 0;
		}
	}

	if ( $show_group ) {
		$rate = woo_bg_maybe_add_rate_group( $rate );
	}

	return apply_filters( 'woo_bg/order_item/vat_rate', $rate, $item, $order );
}

function woo_bg_maybe_add_rate_group( $rate ) {
	$group = woo_bg_get_vat_group_from_rate( $rate );

	if ( $group ) {
		$rate = $group . " - " . $rate;
	}

	return $rate;
}

function woo_bg_get_vat_group_from_rate( $rate ) {
	switch ( $rate ) {
		case '0':
			$group = "А";
			break;
		case '9':
			$group = "Г";
			break;
		case '20':
			$group = "Б";
			break;
		default:
			$group = "";
			break;
	}

	return $group;
}

function woo_bg_tax_based_price( $price, $rate = 20, $force = false ) {
	if ( wc_tax_enabled() || $force ) {
		$price = $price - woo_bg_calculate_vat_from_price( $price, $rate );
	}

	return number_format( round($price, 2), 2, '.', '' );
}

function woo_bg_calculate_vat_from_price( $price, $rate = 20 ) {
	$vat = (new \WC_Tax)::calc_tax( $price, array( array('compound' => 'yes', 'rate' => $rate ) ), true )[0];
    $vat = round( $vat, 3, PHP_ROUND_HALF_UP );
    $vat = number_format( $vat, 2, '.', '');
    
    return $vat;
}

function woo_bg_maybe_remove_shipping( $order ) {
	$remove_shipping = woo_bg_get_option( 'invoice', 'remove_shipping' );

	if ( 
		is_a( $order, 'Automattic\WooCommerce\Admin\Overrides\OrderRefund' ) || 
		is_a( $order, 'WC_Order_Refund' ) 
	) {
		$order = wc_get_order( $order->get_parent_id() );
	}

	if ( !empty( $order->get_shipping_methods() ) ) {
		$shipping_method = @array_shift( $order->get_shipping_methods() );
		$shipping_method_id = $shipping_method['method_id'];

		if ( $order->get_payment_method() === 'cod' && woo_bg_get_option('shippings', $shipping_method_id . '_is_courier' ) === 'yes' ) {
			$remove_shipping = 'yes';
		}
	}

	return $remove_shipping;
}

function woo_bg_has_free_shipping_coupon_in_cart() {
	$has_coupon = false;
	$coupons = WC()->cart->get_coupons();

	if ( $coupons ) {
		foreach ( $coupons as $code => $coupon ) {
			if ( $coupon->is_valid() && $coupon->get_free_shipping() ) {
				$has_coupon = true;
				break;
			}
		}
	}

	return $has_coupon;
}

function woo_bg_format_phone( $phone, $country = 'BG' ) {
	if ( $country !== 'BG' ) {
		return $phone;
	}
	
	$phone = str_replace( [ ' ', '+' ], '', $phone );

	if ( substr( $phone, 0, 3 ) === '359' ) {
		$phone = str_pad( substr( $phone, 3 ), 10, '0', STR_PAD_LEFT );
	}

	$phone = str_pad( $phone, 10, '0', STR_PAD_LEFT );

	return $phone;
}

function woo_bg_check_admin_label_actions() {
	$errors = [];
		
	if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash ( $_REQUEST['nonce'] ) ), 'woo_bg_admin_label' ) ) {
		$errors[] = __( 'Nonce was not provided!', 'bulgarisation-for-woocommerce' );
	}

	if ( ! current_user_can( 'manage_woocommerce' ) ) {
		$errors[] = __( 'You cannot create labels.', 'bulgarisation-for-woocommerce' );
	}

	if ( !empty( $errors ) ) {
		wp_send_json_error( [
			'message' => implode( ' ', $errors ),
		] );
		wp_die();
	}
}

function woo_bg_prime_cart_fee_totals( WC_Cart $cart ) {
	static $is_calculating = false;

	if ( $is_calculating ) {
		return;
	}

	$is_calculating = true;

	try {
		$fees_api      = $cart->fees_api();
		$customer      = $cart->get_customer();
		$calculate_tax = wc_tax_enabled() && ( ! $customer || ! $customer->get_is_vat_exempt() );

		$fees_api->remove_all_fees();
		$cart->calculate_fees();

		$fee_total     = 0.0;
		$fee_tax_total = 0.0;
		$fee_taxes     = array();

		foreach ( $cart->get_fees() as $fee ) {
			$amount    = isset( $fee->amount ) ? (float) $fee->amount : 0.0;
			$taxes     = array();
			$tax_total = 0.0;

			$fee_total += $amount;

			if ( $calculate_tax && 0 < $amount && ! empty( $fee->taxable ) ) {
				$tax_class = isset( $fee->tax_class ) ? (string) $fee->tax_class : '';
				$taxes     = WC_Tax::calc_tax( $amount, WC_Tax::get_rates( $tax_class, $customer ), false );

				foreach ( $taxes as $rate_id => $tax_amount ) {
					$taxes[ $rate_id ] = wc_round_tax_total( $tax_amount );
				}

				$tax_total     = array_sum( $taxes );
				$fee_tax_total += $tax_total;
				$fee_taxes     = wc_array_merge_recursive_numeric( $fee_taxes, $taxes );
			}

			$fee->total    = wc_format_decimal( $amount );
			$fee->tax      = wc_format_decimal( $tax_total );
			$fee->tax_data = $taxes;
		}

		$cart->set_fee_total( $fee_total );
		$cart->set_fee_tax( $fee_tax_total );
		$cart->set_fee_taxes( $fee_taxes );
	} finally {
		$is_calculating = false;
	}
}

function woo_bg_get_package_total() {
	$includes_fees = apply_filters( 'woo_bg/shipping/package_total_includes_fees', true );
	$total = (float) WC()->cart->get_cart_contents_total() + (float) WC()->cart->get_cart_contents_tax();

	if ( $includes_fees ) {
		woo_bg_prime_cart_fee_totals( WC()->cart );

		$total += (float) WC()->cart->get_fee_total() + (float) WC()->cart->get_fee_tax();
	}

	$total = wc_format_decimal( $total, wc_get_price_decimals() );

	return apply_filters( 'woo_bg/shipping/package_total', $total );
}

function woo_bg_is_shipping_enabled() {
	$enabled = false;

	if ( 
		woo_bg_get_option( 'apis', 'enable_econt' ) === 'yes' || 
		woo_bg_get_option( 'apis', 'enable_cvc' ) === 'yes' || 
		woo_bg_get_option( 'apis', 'enable_boxnow' ) === 'yes' || 
		woo_bg_get_option( 'apis', 'enable_pigeon' ) === 'yes' || 
		woo_bg_get_option( 'apis', 'enable_speedy' ) === 'yes' 
	) {
		$enabled = true;
	}

	return $enabled;
}

function woo_bg_get_order_label( $order_id ) {
	$order = wc_get_order( $order_id );
	$data = [];
	$label_data = [];
	$method = '';

	if ( !empty( $order->get_items( 'shipping' ) ) ) {
		$items = $order->get_items( 'shipping' );
		$method_object = array_shift( $items );
		$method = $method_object['method_id'];

		$label_data = woo_bg_get_label_data_for_shipping_method( $method_object, $order );
		
		foreach ( $order->get_items( 'shipping' ) as $shipping ) {
			$method = $shipping['method_id'];
		}
	}

	if ( !empty( $label_data ) ) {
		switch ( $method ) {
			case 'woo_bg_speedy':
				$shipment_status = $order->get_meta( 'woo_bg_speedy_shipment_status' );

				if ( $shipment_status && $label_data['id'] ) {
					$data['number'] = $label_data['id'];
					$data['link'] = admin_url( 'admin-ajax.php' ) . '?cache-buster=' . rand() . '&action=woo_bg_speedy_print_labels&parcels=' . implode('|', wp_list_pluck( $shipment_status['parcels'], 'id' ) ) . "&size=A6";
				}
				break;
			case 'woo_bg_econt':
				$shipment_status = $order->get_meta( 'woo_bg_econt_shipment_status' );

				if ( $shipment_status && !empty( $label_data['label'] ) && !empty( $label_data['label']['shipmentNumber'] ) && !empty( $shipment_status['label']['pdfURL'] ) ) {
					$data = [
						'number' => $label_data['label']['shipmentNumber'],
						'link' => $shipment_status['label']['pdfURL'] . '&label=10x9',
					];
				}
				break;
			case 'woo_bg_cvc':
				$shipment_status = $order->get_meta( 'woo_bg_cvc_shipment_status' );
				if ( $shipment_status && !empty( $shipment_status['pdf'] ) ) {
					$data = [
						'courier' => __( 'CVC', 'bulgarisation-for-woocommerce' ),
						'number' => $label_data['wb'],
						'link' => $shipment_status['pdf'],
					];
				}
				
				break;
			case 'woo_bg_boxnow':
				if ( isset( $label_data['parcels'] ) && is_array( $label_data['parcels'] ) ) {
					foreach ( $label_data['parcels'] as $parcel ) {
						$data['items'][] = [
							'number' => $parcel['id'],
							'link' => admin_url( 'admin-ajax.php' ) . '?cache-buster=' . rand() . '&action=woo_bg_boxnow_print_label&parcel=' . $parcel['id'],
						];
					}
				}

				if ( $other_labels = $order->get_meta( 'woo_bg_boxnow_other_labels_data' ) ) {
					$data['other_labels'] = $other_labels;
					
					foreach ( $other_labels as $other_label ) {
						foreach ( $other_label['shipmentStatus']['parcels'] as $parcel ) {
							$data['items'][] = [
								'number' => $parcel['id'],
								'link' => admin_url( 'admin-ajax.php' ) . '?cache-buster=' . rand() . '&action=woo_bg_boxnow_print_label&parcel=' . $parcel['id'],
							];
						}
					}
				}
				
				break;
			case 'woo_bg_pigeon':
				$shipment_status = $order->get_meta( 'woo_bg_pigeon_shipment_status' );
				if ( $shipment_status && !empty( $label_data['data']['reference_number'] ) ) {
					$data = [
						'number' => $label_data['data']['reference_number'],
						'link' => admin_url( 'admin-ajax.php' ) . '?cache-buster=' . rand() . '&action=woo_bg_pigeon_print_labels&order-id=' . $order->get_id(),
					];
				}
				
				break;
		}
	}

	if ( $method ) {
		$data['method'] = $method;

		switch ( $method ) {
			case 'woo_bg_speedy':
				$data['courier'] = __( 'Speedy', 'bulgarisation-for-woocommerce' );

				break;
			case 'woo_bg_econt':
				$data['courier'] = __( 'Econt', 'bulgarisation-for-woocommerce' );

				break;
			case 'woo_bg_cvc':
				$data['courier'] = __( 'CVC', 'bulgarisation-for-woocommerce' );

				break;
			case 'woo_bg_boxnow':
				$data['courier'] = __( 'BOX NOW', 'bulgarisation-for-woocommerce' );
				
				break;
			case 'woo_bg_pigeon':
				$data['courier'] = __( 'Pigeon Express', 'bulgarisation-for-woocommerce' );
				
				break;
		}
	}

	return apply_filters( 'woo_bg/column/order/shipment_status_data', $data, $order );
}

function woo_bg_get_label_data_for_shipping_method( $shipping ) {
	$order = $shipping->get_order();
	$label_data = null;
	
	if ( $shipping['method_id'] === 'woo_bg_speedy' ) {
		if ( $label = $order->get_meta( 'woo_bg_speedy_label' ) ) {
			$label_data = $label;
		}
	} elseif ( $shipping['method_id'] === 'woo_bg_econt' ) {
		if ( $label = $order->get_meta( 'woo_bg_econt_label' ) ) {
			$label_data = $label;
		}
	} elseif ( $shipping['method_id'] === 'woo_bg_cvc' ) {
		if ( $label = $order->get_meta( 'woo_bg_cvc_label' ) ) {
			$label_data = $label;
		}
	} elseif ( $shipping['method_id'] === 'woo_bg_boxnow' ) {
		if ( $label = $order->get_meta( 'woo_bg_boxnow_shipment_status' ) ) {
			$label_data = $label;
		}
	} elseif ( $shipping['method_id'] === 'woo_bg_pigeon' ) {
		if ( $label = $order->get_meta( 'woo_bg_pigeon_shipment_status' ) ) {
			$label_data = $label;
		}
	}

	return $label_data;
}

function woo_bg_is_pro_activated() {
	return class_exists( 'Woo_BG_Pro\Checkout' );
}

function woo_bg_get_shipping_rate_taxes( $price, $country = 'BG' ) {
	if ( !wc_tax_enabled() ) {
		return [];
	}

	$tax_rates = \WC_Tax::find_shipping_rates( ['country' => $country ] );

	if ( empty( $tax_rates ) ) {
		$tax_rates = [ ['rate' => 20, 'compound' => 'yes' ] ];
	}

	return \WC_Tax::calc_tax( $price, $tax_rates, false );
}

function woo_bg_is_different_shipping_address( $order ) {
    $billing_address  = $order->get_address();
    $shipping_address = $order->get_address( 'shipping' );

    if ( ! empty( $billing_address ) && ! empty( $shipping_address ) ) {
        foreach ( $billing_address as $billing_address_key => $billing_address_value ) {
            if ( isset( $shipping_address[ $billing_address_key ] ) ) {
                $shipping_address_value = $shipping_address[ $billing_address_key ];

                if ( ! empty( $billing_address_value ) && ! empty( $shipping_address_value ) && strcmp( $billing_address_value, $shipping_address_value ) !== 0 ) {
                    return true;
                }
            }
        }
    }

    return false;
}

function woo_bg_check_if_order_with_that_doc_number_exists( $document_number, $document_number_meta ) {
	$orders = wc_get_orders( array(
		'meta_key'      => $document_number_meta,
		'meta_value'    => $document_number, 
		'meta_compare'  => '=', 
		'return'        => 'ids',
		'limit' => 1,
	) );

	return ( !empty( $orders ) );
}

function woo_bg_get_next_document_number( $meta_field ) {
	$orders = wc_get_orders( array(
		'meta_key'      => $meta_field,
		'meta_compare'  => 'exists', 
		'orderby' => 'meta_value',
		'return'        => 'ids',
		'limit' => 1,
	) );

	$latest_order = wc_get_order( $orders[0] );
	$largest_number = $latest_order->get_meta( $meta_field );

	return $largest_number + 1;
}

function woo_bg_strip_street_prefix( $street ) {
    $prefixes = [
        // Cyrillic prefixes
        'ул.',
        'бул.',
        'пл.',
        'пр.',
        'кв.',
        'ж.к.',
        'ж.к',
        'жк.',
        'жк',
        // Latin prefixes (stripped before transliteration)
        'ul.',
        'ul ',
        'bul.',
        'bul ',
        'pl.',
        'pl ',
        'pr.',
        'pr ',
        'kv.',
        'kv ',
        'zh.k.',
        'zh.k',
        'zhk.',
        'zhk',
        'j.k.',
        'j.k',
        'jk.',
        'jk',
    ];

    $street = preg_replace( '/\.(?=\S)/u', '. ', $street );

    foreach ( $prefixes as $prefix ) {
        if ( mb_stripos( $street, $prefix ) === 0 ) {
            $street = mb_substr( $street, mb_strlen( $prefix ) );
            $street = ltrim( $street );
            break;
        }
    }

    return $street;
}

function woo_bg_title_case_bg(string $string, string $encoding = 'UTF-8') {
    $smallWords = [
        'и', 'или', 'а', 'но', 'че',
        'в', 'във', 'с', 'със', 'у', 'към',
        'на', 'за', 'от', 'до', 'по', 'под', 'над', 'пред', 'при', 'през',
        'без', 'след', 'преди', 'между', 'сред', 'чрез'
    ];

    $string = trim(preg_replace('/\s+/u', ' ', $string));
    $string = mb_strtolower($string, $encoding);

    $parts = preg_split('/(\s+)/u', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
    $result = [];
    $wordIndex = 0;

    foreach ($parts as $part) {
        if (preg_match('/^\s+$/u', $part)) {
            $result[] = $part;
            continue;
        }

        $word = $part;
        $word = preg_replace_callback('/^\p{L}/u', function ($m) use ($encoding) {
            return mb_strtoupper($m[0], $encoding);
        }, $word);

        $word = preg_replace_callback('/(\.)(\p{L})/u', function ($m) use ($encoding) {
            return $m[1] . mb_strtoupper($m[2], $encoding);
        }, $word);

        if ($wordIndex > 0 && in_array($part, $smallWords, true)) {
            $word = $part;
        }

        $result[] = $word;
        $wordIndex++;
    }

    return implode('', $result);
}

function woo_bg_impossible_prices_get_tax_classes_data() {
	if ( ! function_exists( 'WC' ) ) {
		return array();
	}

	$data = array();

	$standard_rates = WC_Tax::get_rates( '' );
	$standard_total = 0.0;

	if ( ! empty( $standard_rates ) ) {
		foreach ( $standard_rates as $rate ) {
			if ( isset( $rate['rate'] ) ) {
				$standard_total += (float) $rate['rate'];
			}
		}
	}

	$data[''] = $standard_total / 100;

	if ( method_exists( 'WC_Tax', 'get_tax_class_slugs' ) ) {
		$tax_class_slugs = WC_Tax::get_tax_class_slugs();
	} else {
		$tax_class_slugs = array();
	}

	foreach ( $tax_class_slugs as $tax_class_slug ) {
		$rates = WC_Tax::get_rates( $tax_class_slug );
		$total = 0.0;

		if ( ! empty( $rates ) ) {
			foreach ( $rates as $rate ) {
				if ( isset( $rate['rate'] ) ) {
					$total += (float) $rate['rate'];
				}
			}
		}

		$data[ (string) $tax_class_slug ] = $total / 100;
	}

	return $data;
}

function woo_bg_impossible_prices_get_product_tax_rate() {
	global $post;

	if ( ! $post || 'product' !== get_post_type( $post ) ) {
		return 0.0;
	}

	$product = wc_get_product( $post->ID );

	if ( ! $product instanceof WC_Product ) {
		return 0.0;
	}

	if ( 'taxable' !== $product->get_tax_status() ) {
		return 0.0;
	}

	$tax_class = $product->get_tax_class();
	$rates     = WC_Tax::get_rates( $tax_class );
	$total     = 0.0;

	if ( ! empty( $rates ) ) {
		foreach ( $rates as $rate ) {
			if ( isset( $rate['rate'] ) ) {
				$total += (float) $rate['rate'];
			}
		}
	}

	return $total / 100;
}

function woo_bg_api_filter_hooks() {
	return array(
		'http_request_args',
		'pre_http_request',
		'http_api_curl',
		'requests-curl.before_send',
	);
}

function woo_bg_remove_api_filters() {
	global $wp_filter;

	$removed_filters = array();

	foreach ( woo_bg_api_filter_hooks() as $hook ) {
		$removed_filters[ $hook ] = null;

		if ( isset( $wp_filter[ $hook ] ) ) {
			$removed_filters[ $hook ] = is_object( $wp_filter[ $hook ] ) ? clone $wp_filter[ $hook ] : $wp_filter[ $hook ];
		}

		remove_all_filters( $hook );
	}

	return $removed_filters;
}

function woo_bg_restore_api_filters( $removed_filters ) {
	global $wp_filter;

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

	foreach ( woo_bg_api_filter_hooks() as $hook ) {
		if ( ! array_key_exists( $hook, $removed_filters ) ) {
			continue;
		}

		if ( null === $removed_filters[ $hook ] ) {
			unset( $wp_filter[ $hook ] );
			continue;
		}

		$wp_filter[ $hook ] = $removed_filters[ $hook ];
	}
}

function woo_bg_normalize_text_for_label( $text, $max_length = 200 ) {
	$text = preg_replace( '/[^\p{Cyrillic}a-zA-Z0-9 ]/u', '', htmlspecialchars( $text, ENT_XML1 ) );

	return mb_substr( $text, 0, $max_length, 'UTF-8' );
}
