//Hide country
add_action("wp_head", function() {
	echo "<style>.force-hide {display: none !important;} #billing_country_field, #billing_address_1_field {display: none !important;}</style>";
});

add_filter("woocommerce_form_field_args", function ($args, $key, $value) {
	if(in_array($key, ['shipping_autofill_checkout_field', 'autofill_checkout_field'])){
		$args['required'] = true;
		$args['placeholder'] = '';
	}
	return $args;
}, 10, 3);

add_action("wp_footer", function () {
?>
<script>
	if(jQuery("#autofill_checkout_field_field").length > 0)
		jQuery("#autofill_checkout_field_field").detach().insertAfter('#billing_first_name_field');
	
	jQuery("body").on("change", "#autofill_checkout_field", function () {
		setTimeout(function () {
			if(jQuery("#billing_postcode").val() == '')
				jQuery("#billing_postcode_field").removeClass("force-hide");
			else {
				jQuery("#billing_address_1").val(jQuery("#autofill_checkout_field").val()+" "+jQuery("#billing_postcode").val());
				jQuery("#billing_postcode_field").addClass("force-hide");
				jQuery(document.body).trigger("update_checkout");
			}
			}, 500);
	});
	
	setTimeout(function () {
		if(jQuery("#billing_postcode_field").length > 0)
	   jQuery("#billing_postcode_field").addClass("force-hide");
	}, 550);

	jQuery("body").on("change", ".shipping_method", function () {
		if(jQuery(this).val() == "free_shipping:6")
			jQuery("#billing_postcode_field").addClass("force-hide");
	});
	
	jQuery("body").on("updated_checkout", function () {
		//Check billing country
		if(jQuery(".shipping_method:checked").val() == "free_shipping:6")
			jQuery("#billing_postcode_field").addClass("force-hide");
	});

</script>
<?php
});

add_action("init", function () {
	if(isset($_GET['wc-ajax']) && $_GET['wc-ajax'] == "checkout" && isset($_POST['shipping_method']) && is_array($_POST['shipping_method']) && $_POST['shipping_method'][0] == "free_shipping:6"){
		$_POST['billing_postcode'] = 'BT47 6BE';
		$_POST['billing_address_1'] = 'Collection';
	}
});

add_action('woocommerce_new_order', function ($order_id) {
	if(get_post_meta($order_id, '_billing_address_1', true) == "Collection"){
    	delete_post_meta($order_id, '_billing_postcode');
		delete_post_meta($order_id, '_shipping_postcode');
	}
}, 10, 1);