/*
Theme Name: Elessi Theme Child
Theme URI: https://elessi.nasatheme.com
Description: This is a child theme for Elessi Theme
Author: NasaTheme team
Author URI: https://nasatheme.com
Template: elessi-theme
Version: 1.0
*/


/*************** ADD YOUR CUSTOM CSS IN THIS AREA ***************/


/**
 * BBG Travel
 * Chép custom fields đặt xe vào Billing Information
 * để ứng dụng Woo hiển thị trực tiếp.
 */
add_action(
	'woocommerce_checkout_order_created',
	'bbg_copy_booking_fields_to_billing',
	50,
	1
);

function bbg_copy_booking_fields_to_billing( $order ) {

	if ( ! $order instanceof WC_Order ) {
		return;
	}

	/*
	 * Các meta key hiện đã xác định:
	 * songuoi_
	 * diemden_
	 */
	$so_nguoi = trim(
		wp_strip_all_tags(
			(string) $order->get_meta( 'songuoi_', true )
		)
	);

	$diem_den = trim(
		wp_strip_all_tags(
			(string) $order->get_meta( 'diemden_', true )
		)
	);

	/*
	 * Thêm đúng meta key thật của form tại đây.
	 */
	$diem_don = trim(
		wp_strip_all_tags(
			(string) $order->get_meta( 'diemdon_', true )
		)
	);

	$ngay_di = trim(
		wp_strip_all_tags(
			(string) $order->get_meta( 'ngaydi_', true )
		)
	);

	$gio_don = trim(
		wp_strip_all_tags(
			(string) $order->get_meta( 'giodon_', true )
		)
	);

	$loai_xe = trim(
		wp_strip_all_tags(
			(string) $order->get_meta( 'loaixe_', true )
		)
	);

	/*
	 * Công ty:
	 * hiện "Số người: ..."
	 */
	if ( '' !== $so_nguoi ) {
		$order->set_billing_company(
			'Số người: ' . $so_nguoi
		);
	}

	/*
	 * Địa chỉ dòng 1:
	 * ưu tiên giữ địa chỉ khách đang có.
	 * Nếu có điểm đón thì ghép vào cuối.
	 */
	$current_address = trim(
		(string) $order->get_billing_address_1()
	);

	if ( '' !== $diem_don ) {
		$order->set_billing_address_1(
			$current_address
				? $current_address . ' | Điểm đón: ' . $diem_don
				: 'Điểm đón: ' . $diem_don
		);
	}

	/*
	 * Địa chỉ dòng 2:
	 * Điểm đến.
	 */
	if ( '' !== $diem_den ) {
		$order->set_billing_address_2(
			'Điểm đến: ' . $diem_den
		);
	}

	/*
	 * Thành phố:
	 * Ngày đi.
	 */
	if ( '' !== $ngay_di ) {
		$order->set_billing_city(
			'Ngày đi: ' . $ngay_di
		);
	}

	/*
	 * Tỉnh/thành:
	 * Giờ đón.
	 *
	 * Lưu ý: trường state đôi khi cần mã tỉnh hợp lệ.
	 * Nếu app không hiện đúng, bỏ phần này và ghép giờ đón
	 * vào billing_address_2.
	 */
	if ( '' !== $gio_don ) {
		$order->set_billing_state(
			'Giờ đón: ' . $gio_don
		);
	}

	/*
	 * Mã bưu điện:
	 * Loại xe.
	 */
	if ( '' !== $loai_xe ) {
		$order->set_billing_postcode(
			'Loại xe: ' . $loai_xe
		);
	}

	$order->save();
}