<?php

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

require_once 'db.php';
$DEFAULT_RESPONSE = array();

add_action( 'woocommerce_init', function(){
	if ( isset(WC()->session) && ! WC()->session->has_session() )
		WC()->session->set_customer_session_cookie( true );
} );

function nele_db_is_empty(): bool {
    global $nele_offices_table, $nele_places_table, $nele_countries_table;
    return nele_db_amount($nele_offices_table) === 0
           or nele_db_amount($nele_places_table) === 0
           or nele_db_amount($nele_countries_table);
}

function nele_before_checkout_form() {
//	if (nele_db_is_empty() && nele_get_db_errors()) {
//		foreach (nele_get_db_errors() as $error) {
//			wc_add_notice($error, 'error');
//		}
//	}
//    if (nele_db_is_empty() || get_transient('nele_upgrade_running')) {
//        wc_add_notice(__('Only original checkout is available while data is not fully loaded from the NextLevel API.', 'nextlevel_delivery' ));
//    }
}
add_action('woocommerce_before_checkout_form', 'nele_before_checkout_form');


function nele_resolve_ajax_post_vars() : array {
	$result = array();
    $keys = array('csm', 'ship_to', 'country', 'postcode', 'state_name', 'city', 'city_name', 'office', 'office_name',
	    'street', 'street_num', 'district', 'block', 'entrance', 'floor', 'apt');
    foreach ($keys as $key) {
		if ( isset($_POST[$key]) ) {
			$value = wc_clean($_POST[$key]);
			$result[$key] = $value;
		} else {
			$value = "";
		}
		if (! isset(WC()->session)) {
			write_log("nele_resolve_ajax_post_vars: session is not initialised");
			break;
		}
		if (WC()->session->get("_$key", "") !== $value) {
			WC()->session->set("_$key", $value);
			write_log("nele_resolve_ajax_post_vars: setting $key to '$value'");
		}
    }
    if (isset($result['csm'])) {
	    $shipping_method_id = $result['csm'];
        $result['courier'] = nele_courier_by_shipping_method($shipping_method_id);
	    WC()->session->set("chosen_shipping_methods", array($shipping_method_id));
    }
    if (isset($result['country'])) {
        $countries = nele_db_countries($result['country']);
        if (! empty($countries)) {
            $result['country_id'] = $countries[0]->id;
        }
    }
    return $result;
}

add_action("change_locale", "nele_resolve_ajax_post_vars");

function nele_ajax_has_streets() {
    global $DEFAULT_RESPONSE;
    if (! isset($_POST['country']) || ! isset($_POST['city_name'])) {
        wp_send_json($DEFAULT_RESPONSE);
    }
    wp_send_json(array('result' => nele_db_has_streets($_POST['country'], $_POST['city_name'])[0]->amt));
}
add_action('wp_ajax_nele_ajax_has_streets', 'nele_ajax_has_streets' );
add_action('wp_ajax_nopriv_nele_ajax_has_streets', 'nele_ajax_has_streets' );

function nele_ajax_get_states() {
	global $DEFAULT_RESPONSE;
	$vars = nele_resolve_ajax_post_vars();
	if (! isset($vars['country_id']) || ! isset($vars['state_name'])) {
		write_log("nele_ajax_get_states: country_id or state_name not set");
		wp_send_json($DEFAULT_RESPONSE);
	}
	$country_id = $vars['country_id'];
	$courier = $vars['courier'] ?? null;
	$state_name = $vars['state_name'];
	global $nele_to_office_key;
	if ( $vars['ship_to'] == $nele_to_office_key) {
		if (empty($courier)) {
			write_log("nele_ajax_get_states: courier not set");
			wp_send_json($DEFAULT_RESPONSE);
			return;
		}
		wp_send_json(nele_db_to_array(nele_db_states($country_id, $courier, $state_name)));
		return;
	} # else do not do any filtering by courier
	wp_send_json(nele_db_to_array(nele_db_states($country_id, null, $state_name)));
}
add_action('wp_ajax_nele_ajax_get_states', 'nele_ajax_get_states' );
add_action('wp_ajax_nopriv_nele_ajax_get_states', 'nele_ajax_get_states' );

function nele_ajax_get_cities() {
    global $DEFAULT_RESPONSE;
    $vars = nele_resolve_ajax_post_vars();
	$parent_obj = nele_parent_obj();
    if (! isset($vars['country_id']) || ! isset($vars['city_name'])) {
        write_log("nele_ajax_get_cities: country_id or city_name not set");
        wp_send_json($DEFAULT_RESPONSE);
    }
    $country_id = $vars['country_id'];
    $courier = $vars['courier'] ?? null;
    $city_name = $vars['city_name'];
    $state_name = $vars['state_name'] ?? null;
	$show_state_field = wc_string_to_bool($parent_obj->get_option("show_state_field", false));
    global $nele_to_office_key;
    if ( $vars['ship_to'] == $nele_to_office_key) {
        if (empty($courier)) {
            write_log("nele_ajax_get_cities: courier not set");
            wp_send_json($DEFAULT_RESPONSE);
            return;
        }
        wp_send_json(nele_db_to_array(nele_db_cities($country_id, $courier, $city_name)));
        return;
    } # else do not do any filtering by courier
	if ($show_state_field) {
		wp_send_json(nele_db_to_array(nele_db_cities($country_id, null, $city_name, $state_name)));
	} else {
		wp_send_json(nele_db_to_array(nele_db_cities($country_id, null, $city_name)));
	}
}
add_action('wp_ajax_nele_ajax_get_cities', 'nele_ajax_get_cities' );
add_action('wp_ajax_nopriv_nele_ajax_get_cities', 'nele_ajax_get_cities' );

function nele_ajax_get_offices() {
    $vars = nele_resolve_ajax_post_vars();
    $is_error = false;
    if (! isset($vars['country_id'])) {
	    write_log("nele_ajax_get_offices: country_id was not set");
        $is_error = true;
    }
    if (! isset($vars['courier'])) {
        write_log("nele_ajax_get_offices: courier was not set");
        $is_error = true;
    }
    if (! isset($vars['city'])) {
        write_log("nele_ajax_get_offices: city was not set");
        $is_error = true;
    }
    if ($is_error) {
        global $DEFAULT_RESPONSE;
        wp_send_json($DEFAULT_RESPONSE);
    }
    $country_id = $vars['country_id'];
    $courier = $vars['courier'];
    $city_id = $vars['city'];
    $office_name = $vars['office_name'];
    wp_send_json(nele_db_to_array(nele_db_offices($country_id, $city_id, $courier, $office_name)));
}
add_action('wp_ajax_nele_ajax_get_offices', 'nele_ajax_get_offices' );
add_action('wp_ajax_nopriv_nele_ajax_get_offices', 'nele_ajax_get_offices' );

function nele_ajax_get_streets() {
    $vars = nele_resolve_ajax_post_vars();
    if (! isset($vars['country_id']) || ! isset($vars['city_name']) || ! isset($vars['street'])) {
	    write_log("nele_ajax_get_streets: country_id or city_name or street not set");
        global $DEFAULT_RESPONSE;
        wp_send_json($DEFAULT_RESPONSE);
    }
    $country_id = $vars['country_id'];
    $city = $vars['city_name'];
    $street = $vars['street'];
    wp_send_json(nele_db_to_array(nele_db_streets($country_id, $city, $street)));
}
add_action('wp_ajax_nele_ajax_get_streets', 'nele_ajax_get_streets' );
add_action('wp_ajax_nopriv_nele_ajax_get_streets', 'nele_ajax_get_streets' );

function nele_ajax_update_price() {
    nele_resolve_ajax_post_vars(); // we just store the vars to the current user's session
    global $DEFAULT_RESPONSE;
	wp_send_json($DEFAULT_RESPONSE);
}
add_action('wp_ajax_nele_ajax_update_price', 'nele_ajax_update_price' );
add_action('wp_ajax_nopriv_nele_ajax_update_price', 'nele_ajax_update_price' );

add_action('wp_enqueue_scripts', 'nele_custom_checkout_scripts');
function nele_custom_checkout_scripts() {
	if ((! is_checkout() || is_wc_endpoint_url('order-received'))) {  //  || nele_db_is_empty()
        return;
	}
    $template_val = "<section class=\"delivery-to\">
    <h3>".__("Delivery to", "nextlevel_delivery")." </h3>
    <ul class=\"delivery-to--content\">
        <li class=\"to-office\">
            <label for=\"toOffice\">
                <input id=\"toOffice\" type=\"radio\" name=\"radAnswer\" />
                <div class=\"headings\">
                    <span>{to_office_caption}</span>
                    {to_office_description}
                </div>
            </label>
            <div id=\"to-office-fields\">
            </div>
        </li>
        <li class=\"to-address\">
            <label for=\"toAddress\">
                <input id=\"toAddress\" type=\"radio\" name=\"radAnswer\" />
                <div class=\"headings\">
                    <span>{to_address_caption}</span>
                    {to_address_description}
                </div>
            </label>
            <div id=\"to-address-fields\">
            </div>
        </li>
    </ul>
</section>";
    $translations = array();
    nele_shipping_method_init();
    $shipping_methods = get_option("shipping_methods_defined");
    foreach ($shipping_methods as $shipping_method) {  # add translations for all known NextLevel shipping methods
        $translations[$shipping_method] = nele_resolve_address_fields_translation($shipping_method);
    }
    if ( ! wp_script_is( 'jquery-ui-core', 'done' ) ) {
        wp_enqueue_script( 'jquery-ui-core' );
    }
    if ( ! wp_script_is( 'jquery-ui-autocomplete', 'done' ) ) {
        wp_enqueue_script( 'jquery-ui-autocomplete' );
    }
    wp_register_style( 'jquery-ui-styles','https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css' );
    wp_enqueue_style( 'jquery-ui-styles' );
	$inline_js = "const neleTranslations = " . json_encode($translations) . ";
        const neleCheckoutInlineHtml = `" . $template_val . "`; const IS_WP_DEBUG = `" . WP_DEBUG . "`;
    ";
    wp_add_inline_script('jquery', $inline_js);
	wp_enqueue_style('nele-checkout-css', NELE_PLUGIN_URL . 'css/checkout.min.css', array(), '1.0.21');
	wp_enqueue_style('nele-spinner-css', NELE_PLUGIN_URL . 'css/spinner.css', array(), '1.0.7');
    wp_enqueue_style( 'select2-css', 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css', array(), '4.1.0-rc.0');
    wp_enqueue_script( 'select2-js', 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js', 'jquery', '4.1.0-rc.0');
    wp_register_script( 'nele-checkout-js', NELE_PLUGIN_URL . 'js/checkout.js', array( 'jquery-ui-autocomplete', 'select2-js'), '1.0.156');
	// this was commented-out since WPML doesn't support this fancy new translation method
	//    wp_set_script_translations( 'nele-checkout-js', 'nextlevel_delivery', NELE_PLUGIN_ROOT_DIR . 'languages' );
	$translation_array = array(
		'delivery_method' => __('Delivery method', 'nextlevel_delivery'),
		'required' => __('required', 'nextlevel_delivery'),
		'select_a_shipping_method' => __('Select a shipping method', 'nextlevel_delivery'),
		'no_shipping_methods' => __('No shipping methods defined', 'nextlevel_delivery')
    );
    wp_localize_script( 'nele-checkout-js', 'neleLoc', $translation_array );
	wp_enqueue_script( 'nele-checkout-js' );
	wp_enqueue_script('nele-spinner-js', NELE_PLUGIN_URL . 'js/spinner.js', array('jquery', 'nele-checkout-js'), '1.0.29', true);
}

function nele_resolve_address_fields_translation($shipping_method): array
{
    global $nele_to_office_key, $nele_to_address_key, $DELIVERY_OPTS;
    if (! empty($shipping_method)) {
        $to_office_caption = nele_shipping_option_value("subject_bg", $shipping_method, $nele_to_office_key);
        $to_office_description = nele_shipping_option_value("description_bg", $shipping_method, $nele_to_office_key);
        $to_address_caption = nele_shipping_option_value("subject_bg", $shipping_method, $nele_to_address_key);
        $to_address_description = nele_shipping_option_value("description_bg", $shipping_method, $nele_to_address_key);
    }
    $to_office_caption = empty($to_office_caption) ? $DELIVERY_OPTS[$nele_to_office_key] : $to_office_caption;
    $to_office_description = empty($to_office_description) ? '' : $to_office_description;
    $to_address_caption = empty($to_address_caption) ? $DELIVERY_OPTS[$nele_to_address_key] : $to_address_caption;
    $to_address_description = empty($to_address_description) ? '' : $to_address_description;
    return array(
		"delivery_to" => __('Delivery to', 'nextlevel_delivery'),
        "to_office" => $to_office_caption,
        "to_office_description" => $to_office_description,
        "to_address" => $to_address_caption,
        "to_address_description" => $to_address_description,
    );
}

add_filter( 'woocommerce_checkout_fields' , 'nele_override_checkout_fields');
function nele_override_checkout_fields($fields): array
{
//    if (nele_db_is_empty()) {
//        return $fields;
//    }
	$fields['billing']['billing_email']['required'] = true;
	$fields['billing']['billing_email']['priority'] = '22';
	$fields['billing']['billing_phone']['priority'] = '30';

	unset($fields['billing']['billing_company']);
	unset($fields['billing']['billing_state']);
	unset($fields['billing']['billing_city']);
	unset($fields['billing']['billing_address_1']);
	unset($fields['billing']['billing_address_2']);

    $placeholder = __('Start typing...', 'nextlevel_delivery');

	global $nele_to_office_key, $nele_ship_to_key, $nele_place_key, $nele_place_id_key, $nele_office_key, $nele_office_id_key, $nele_street_key,
	       $nele_street_num_key, $nele_block_key, $nele_entrance_key, $nele_floor_key, $nele_apt_key, $DELIVERY_OPTS, $nele_state_key;

	$fields['billing'][$nele_ship_to_key] = array(
		'priority' => '110',
		'type' => 'radio',
		'class' => array('form-row-wide', 'address-field'),
		'label' => __('Delivery to', 'nextlevel_delivery'),
		'required' => true,
		'options' => $DELIVERY_OPTS,
        'default' => $nele_to_office_key
	);
	$parent_obj = nele_parent_obj();
	$show_state_field = wc_string_to_bool($parent_obj->get_option("show_state_field", false));
	if ($show_state_field) {
		$fields['billing'][$nele_state_key] = array(
			'priority' => '114',
			'type' => 'text',
			'class' => array('form-row-wide', 'address-field'),
			'label' => __('State', 'nextlevel_delivery'),
			'required'  => false,
			'placeholder' => $placeholder
		);
	}
	$fields['billing'][$nele_place_key] = array(
		'priority' => '116',
		'type' => 'text',
		'class' => array('form-row-wide', 'address-field'),
		'label' => __('City', 'nextlevel_delivery'),
		'required'  => false,
		'placeholder' => $placeholder
	);
    $fields['billing'][$nele_place_id_key] = array(
        'priority' => '117',
        'type' => 'text',
        'class' => array('form-row-wide', 'address-field'),
        'label' => __('City ID', 'nextlevel_delivery'),
        'required'  => false
    );
	$fields['billing'][$nele_office_key] = array(
		'priority' => '120',
		'type' => 'text',
		'class' => array('form-row-wide', 'address-field'),
		'label' => __('Office', 'nextlevel_delivery'),
		'placeholder' => $placeholder
	);
    $fields['billing'][$nele_office_id_key] = array(
        'priority' => '121',
        'type' => 'text',
        'class' => array('form-row-wide', 'address-field'),
        'label' => __('Office ID', 'nextlevel_delivery'),
        'required'  => false
    );
	$fields['billing'][$nele_street_key] = array(
		'priority' => '130',
		'type' => 'text',
		'class' => array('form-row-first', 'address-field'),
		'label' => __('Street', 'nextlevel_delivery'),
		'placeholder' => $placeholder
	);
	$fields['billing'][$nele_street_num_key] = array(
		'priority' => '140',
		'type' => 'number',
		'class' => array('form-row-last', 'address-field'),
		'label' => __('Street number', 'nextlevel_delivery')
	);
//	$fields['billing'][$nele_district_key] = array(
//		'priority' => '150',
//		'type' => 'text',
//		'class' => array('form-row-first', 'address-field'),
//		'label' => __('District', 'nextlevel_delivery')
//	);
	$fields['billing'][$nele_block_key] = array(
		'priority' => '160',
		'type' => 'text',
		'class' => array('address-field'),
		'label' => __('Block #', 'nextlevel_delivery')
	);
	$fields['billing'][$nele_entrance_key] = array(
		'priority' => '170',
		'type' => 'text',
		'class' => array('address-field'),
		'label' => __('Entrance', 'nextlevel_delivery')
	);
	$fields['billing'][$nele_floor_key] = array(
		'priority' => '180',
		'type' => 'text',
		'class' => array('address-field'),
		'label' => __('Floor', 'nextlevel_delivery')
	);
	$fields['billing'][$nele_apt_key] = array(
		'priority' => '190',
		'type' => 'text',
		'class' => array('address-field'),
		'label' => __('Apartment', 'nextlevel_delivery')
	);
	return $fields;
}

add_action( 'woocommerce_checkout_process', 'nele_custom_checkout_field_process' );
function nele_custom_checkout_field_process() {
//    if (nele_db_is_empty()) {
//        return;
//    }
	global $nele_ship_to_key, $nele_office_key, $nele_street_key, $nele_place_key, $nele_to_office_key, $nele_to_address_key,
	       $nele_postcode, $nele_street_num_key, $nele_district_key, $nele_block_key, $nele_state_key;
	$shippingMethod = sanitize_text_field($_POST[$nele_ship_to_key]);
	if (! $shippingMethod) {
		wc_add_notice( __( 'Delivery method was not chosen. Please choose one.', 'nextlevel_delivery' ), 'error' );
	}
    if (! sanitize_text_field($_POST[$nele_place_key])) {
        wc_add_notice( __( 'City was not selected. Please fill it in.', 'nextlevel_delivery' ), 'error' );
    }
	if ($shippingMethod === $nele_to_office_key) {
		if (! sanitize_text_field($_POST[$nele_postcode])) {
			wc_add_notice( __( 'City should be selected from the dropdown list.', 'nextlevel_delivery' ), 'error' );
		}
		if (! sanitize_text_field($_POST[$nele_office_key])) {
			wc_add_notice( __( 'Office was not selected. Please fill it in.', 'nextlevel_delivery' ), 'error' );
		}
	} else if ($shippingMethod === $nele_to_address_key) {
		$parent_obj = nele_parent_obj();
		$show_state_field = wc_string_to_bool($parent_obj->get_option("show_state_field", false));
		if ($show_state_field && ! sanitize_text_field($_POST[$nele_state_key])) {
			wc_add_notice( __( 'State was not populated. Please fill it in.', 'nextlevel_delivery' ), 'error' );
		}
		if (! sanitize_text_field($_POST[$nele_postcode])) {
			wc_add_notice( __( 'Postcode was not specified. Please fill it in.', 'nextlevel_delivery' ), 'error' );
		}
		if ((! sanitize_text_field($_POST[$nele_district_key]) && ! sanitize_text_field($_POST[$nele_block_key])) &&
		    (! sanitize_text_field($_POST[$nele_street_key]) || ! sanitize_text_field($_POST[$nele_street_num_key]))){
			wc_add_notice( __( 'Street address was not populated. Please fill it in.', 'nextlevel_delivery' ), 'error' );
		} else
		if ((! sanitize_text_field($_POST[$nele_district_key]) || ! sanitize_text_field($_POST[$nele_block_key])) &&
		    (! sanitize_text_field($_POST[$nele_street_key]) && ! sanitize_text_field($_POST[$nele_street_num_key]))){
			wc_add_notice( __( 'District address was not populated. Please fill it in.', 'nextlevel_delivery' ), 'error' );
		}
	}
}

add_action('woocommerce_checkout_update_order_meta', 'nele_save_checkout_field_data');
function nele_save_checkout_field_data($order_id) {
    write_log("nele_save_checkout_field_data:");
    write_log($_POST);
    global $nele_place_id_key, $nele_office_id_key, $nele_street_key, $nele_street_num_key, $nele_place_key, $nele_state_key,
    $nele_block_key, $nele_entrance_key, $nele_floor_key, $nele_apt_key, $nele_ship_to_key, $nele_to_office_key, $nele_district_key;
	$shipping_methods = $_POST['shipping_method'];
	$shipping_method = $shipping_methods[array_key_first($shipping_methods)];  // this is the data sent on click to [Place order] button
	write_log("nele_save_checkout_field_data: shipping_method='$shipping_method'");
    $order = wc_get_order($order_id);
    $order->update_meta_data( 'nele_shipping_method', $shipping_method);
    $order->update_meta_data( 'nele_state', wc_clean($_POST[$nele_state_key]));
    $city_id = wc_clean($_POST[$nele_place_id_key]);
	$city = wc_clean($_POST[$nele_place_key]);
	if (! empty($city_id)) {
        $places = nele_db_cities_by_id($city_id);
        if (! empty($places)) {
            $order->update_meta_data( 'nele_place', $places[0]->name);
            $order->update_meta_data( 'nele_place_id', $places[0]->id);
        } else {
            $order->update_meta_data( 'nele_place', $city);
            $order->delete_meta_data( 'nele_place_id');
        }
	} else if (! empty($city)) {
        $order->update_meta_data( 'nele_place', $city);
        $order->delete_meta_data( 'nele_place_id');
	}
	$ship_to = isset($_POST[$nele_ship_to_key]) ? wc_clean($_POST[$nele_ship_to_key]) : '';
	if (! empty($ship_to)) {
        $order->update_meta_data( 'nele_ship_to', $ship_to);
	}
	$ship_to_office = $ship_to === $nele_to_office_key;
    $order->update_meta_data( 'nele_ship_to_office', $ship_to_office);
    $office_id = isset($_POST[$nele_office_id_key]) ? wc_clean($_POST[$nele_office_id_key]) : '';
	if ($ship_to_office && ! empty($office_id)) {
        $offices = nele_db_offices_by_id($office_id);
        if (! empty($offices)) {
            $order->update_meta_data( 'nele_office', $offices[0]->name);
            $order->update_meta_data( 'nele_office_id', $offices[0]->id);
        }
	}
    $street = isset($_POST[$nele_street_key]) ? wc_clean($_POST[$nele_street_key]) : '';
    $district = isset($_POST[$nele_district_key]) ? wc_clean($_POST[$nele_district_key]) : '';
	// this is to address related logic
    if (! $ship_to_office && (! empty($street) || ! empty($district))) {
	    if ( ! empty( $street ) ) {
            $order->update_meta_data( 'nele_street', $street );
	    }
	    if ( ! empty( $district ) ) {
            $order->update_meta_data( 'nele_district', $district );
	    }
	    $addr_fields = array(
		    $nele_street_num_key,
		    $nele_block_key,
		    $nele_entrance_key,
		    $nele_floor_key,
		    $nele_apt_key
	    );
	    foreach ( $addr_fields as $addr_field ) {
		    $field_val = isset( $_POST[ $addr_field ] ) ? wc_clean( $_POST[ $addr_field ] ) : '';
		    if ( ! empty( $field_val ) ) {
                $order->update_meta_data( $addr_field, $field_val );
		    }
	    }
    }
	// make shipping details match the billing details
	$order->set_shipping_first_name($order->get_billing_first_name());
	$order->set_shipping_last_name($order->get_billing_last_name());
	$order->set_shipping_postcode($order->get_billing_postcode());
	$custom_address = nele_custom_order_address(array(), $order);
	$order->set_shipping_city($custom_address['city']);
	$order->set_shipping_state($custom_address['state']);
	$order->set_shipping_address_1($custom_address['address_1']);
	$order->save();
}

function nele_order_items_names($order): string
{
    $product_names = array();
    foreach ($order->get_items() as $item_id => $item) {
        $product = $item->get_product();
        if ($product) {
            $product_names[] = $product->get_name();
        }
    }
    return implode(', ', $product_names);
}

function nele_order_items_sku_quantity($order): string
{
    $product_names = array();
    foreach ($order->get_items() as $item_id => $item) {
        $product = $item->get_product();
        if ($product) {
            $sku = $product->get_sku();
            $product_names[] = (empty($sku) ? $item->get_name() : $sku) . ' x ' . $item->get_quantity();
        }
    }
    return implode(', ', $product_names);
}

function nele_custom_order_address($address, $order) {
    $address_details = nele_resolve_order_address_details($order);
	if (! empty($address_details->place)) {
		$address['city'] = $address_details->place;
		$address['state'] = '';
	}
	$parent_obj = nele_parent_obj();
	$show_state_field = wc_string_to_bool($parent_obj->get_option("show_state_field", false));
	if ($show_state_field) {
		$address['state'] = $address_details->state;
	}
	if (! empty($address_details->office_id)) {
		$address['address_1'] = $address_details->office;
	} else if (! empty($address_details->street)) {
        $street = $address_details->street;
        $street_num = $address_details->street_no;
        $district = $address_details->complex;
        $block = $address_details->block_no;
        $entrance = $address_details->entrance_no;
        $floor = $address_details->floor_no;
        $apt = $address_details->apartment_no;
		$addr_parts = array();
		if (! empty($street)) {
			$addr_parts[] = __("str.", "nextlevel_delivery") . " " . $street . " №" . $street_num;
		}
		if (! empty($district)) {
			$addr_parts[] = __("district", "nextlevel_delivery") . " " . $district;
		}
		if (! empty($block)) {
			$addr_parts[] = __("block", "nextlevel_delivery") . " " . $block;
		}
		if (! empty($entrance)) {
			$addr_parts[] = __("entrance", "nextlevel_delivery") . " " . $entrance;
		}
		if (! empty($floor)) {
			$addr_parts[] = __("floor", "nextlevel_delivery") . " " . $floor;
		}
		if (! empty($apt)) {
			$addr_parts[] = __("apt.", "nextlevel_delivery") . " " . $apt;
		}
		$address['address_1'] = implode( " ", $addr_parts );
	}
	return $address;
}
add_filter('woocommerce_order_formatted_billing_address', 'nele_custom_order_address', 10, 2);

add_action( 'woocommerce_checkout_create_order_shipping_item', 'nele_action_wc_checkout_create_order_shipping_item', 10, 4 );
function nele_action_wc_checkout_create_order_shipping_item( $item, $package_key, $package, $order ) {
    $shipping_price = WC()->session->get('shipping_price');
    if (empty($shipping_price)) {
		$item->set_total( 0 );
    } else {
	    $item->set_total( $shipping_price );
    }
	$item->calculate_taxes();
    $order->calculate_totals();
}

add_action( 'woocommerce_checkout_order_created', 'nele_order_created_disable_fees' );
function nele_order_created_disable_fees( $order ) {
    foreach( $order->get_items( 'fee' ) as $item_id => $item ) {
        if( nele_cart_shipping_price_title() === $item['name'] ) {
            $order->remove_item($item_id);
        }
    }
    $order->calculate_totals();
    $auto_create_waybill = wc_string_to_bool(nele_parent_obj()->get_option("auto_gen_waybill", false));
	write_log("nele_order_created_disable_fees: auto_create_waybill = $auto_create_waybill");
    if ($auto_create_waybill === true) {
        nele_generate_pdf_callback(false, $order->get_id());
    }
}

add_action('woocommerce_checkout_order_processed', 'nele_custom_update_order_status', 10, 3);
function nele_custom_update_order_status($order_id, $posted_data, $order) {
	// Set shipping details to match billing details only if no shipping details were already provided
	if (empty($order->get_shipping_first_name())) {
		$order->set_shipping_first_name($posted_data['billing_first_name']);
	}
	if (empty($order->get_shipping_last_name())) {
		$order->set_shipping_last_name($posted_data['billing_last_name']);
	}
	if (empty($order->get_shipping_postcode())) {
		$order->set_shipping_postcode($posted_data['billing_postcode']);
	}
	$custom_address = nele_custom_order_address(array(), $order);
	if (empty($order->get_shipping_city())) {
		$order->set_shipping_city($custom_address['city']);
		$order->set_shipping_state($custom_address['state']);
	}
	if (empty($order->get_shipping_address_1())) {
		$order->set_shipping_address_1($custom_address['address_1']);
	}
	$order->save();
}

function nele_translate_post_code_field( $translated_text, $text, $domain ) {
	if ( $translated_text == 'Пощенски код' ) {
		$translated_text = __( 'П.К.', 'woocommerce' );
	}
    return $translated_text;
}
add_filter( 'gettext', 'nele_translate_post_code_field', 20, 3 );

// Ensure shipping fee is updated during checkout AJAX update
//add_action('woocommerce_checkout_update_order_review', 'nele_update_custom_shipping_fee_on_checkout');
//
//function nele_update_custom_shipping_fee_on_checkout($post_data) {
////	 WC()->cart->calculate_totals();  # TODO calc
//}