<?php
namespace BricksUltimate\WooCommerce;

if ( ! defined( 'ABSPATH' ) ) exit;

class WooMetaBoxOrderCustomFields {

	public static function output( $post ) {

		if ( $post instanceof WC_Order ) {
			$order = $post;
		} elseif($post instanceof \Automattic\WooCommerce\Admin\Overrides\Order ) {
			$order = $post;
		} else {
			$order = \wc_get_order( $post->ID );
		}

		if( ! $order || empty( $order ) )
			return;

		$template_id = \Bricks\Woocommerce::get_template_data_by_type( 'wc_form_checkout', false );
		
		if( ! $template_id )
			return;

		$template_data = get_post_meta( $template_id, BRICKS_DB_PAGE_CONTENT, true );

		if( ! $template_data )
			return;

		echo "<div class=\"order-attribution-metabox\">";

		foreach( $template_data as $template_content ) {
			if ( 
				$template_content['name'] == 'bu-billing-fields' || $template_content['name'] == 'bu-shipping-fields' 
			) {
				
				$settings = $template_content['settings'];

				if( 
					(
						( isset( $settings['billing_field'] ) && $settings['billing_field'] == 'custom' ) || 
						( isset( $settings['shipping_field'] ) && $settings['shipping_field'] == 'custom' )
					)

					&& isset( $settings['field_key'] ) 
				) {

					$data = $order->get_meta( '_' . $settings['field_key'] );
					if( $data ) {

						if( $settings['field_type'] == 'date' ) {
							$date = new \WC_DateTime( "{$data}", new \DateTimeZone( 'UTC' ) );
							$data = $date->date_i18n( wc_date_format() );
						}

						if( $settings['field_type'] == 'time' ) {
							$date = new \WC_DateTime( "{$data}", new \DateTimeZone( 'UTC' ) );
							$data = $date->date_i18n( wc_time_format() );
						}

						$class = str_replace(["_", " "], "-", $settings['field_key'] );
						$label = esc_html( $settings['label'] );
						echo "<h4 for=\"{$label}\">". wp_kses_post( $settings['label'] ) . "</h4>";
						echo "<span class=\"order-meta-{$class}\">{$data}</span>";

					}
				}
			}
		}

		do_action( 'woocommerce_order_custom_meta_data', $order );

		echo "</div>";
	}
}