<?php
/**
 * Customer-facing display of the saved delivery date:
 * order-received (thank you) page, emails, and the My Account order view.
 *
 * @package Datery
 */

defined( 'ABSPATH' ) || exit;

class Datery_Order {

	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		// Thank-you page + My Account → View order (both fire woocommerce_order_details_after_order_table).
		add_action( 'woocommerce_order_details_after_order_table', array( $this, 'render_on_order_page' ) );

		// Emails (customer + admin).
		add_action( 'woocommerce_email_order_meta', array( $this, 'render_in_email' ), 10, 3 );
	}

	private function get_date( $order ) {
		$value = $order->get_meta( DATERY_META_KEY );
		return $value ? Datery_Dates::display( $value ) : '';
	}

	public function render_on_order_page( $order ) {
		if ( apply_filters( 'datery_skip_classic_display', false, $order ) ) {
			return; // Block checkout already renders the field via the Store API.
		}
		$date = $this->get_date( $order );
		if ( '' === $date ) {
			return;
		}
		$label = Datery_Settings::get( 'field_label', __( 'Delivery date', 'datery-delivery-date-for-woocommerce' ) );
		echo '<p class="datery-order-delivery-date"><strong>' . esc_html( $label ) . ':</strong> ' . esc_html( $date ) . '</p>';
	}

	public function render_in_email( $order, $sent_to_admin, $plain_text ) {
		if ( apply_filters( 'datery_skip_classic_display', false, $order ) ) {
			return; // Block checkout already includes the field in the email.
		}
		$date = $this->get_date( $order );
		if ( '' === $date ) {
			return;
		}
		$label = Datery_Settings::get( 'field_label', __( 'Delivery date', 'datery-delivery-date-for-woocommerce' ) );

		if ( $plain_text ) {
			echo "\n" . esc_html( $label ) . ': ' . esc_html( $date ) . "\n";
			return;
		}

		echo '<div style="margin-bottom:20px;">';
		echo '<h2 style="display:inline-block;font-size:16px;margin:0 0 6px;">' . esc_html( $label ) . '</h2>';
		echo '<p style="margin:0;">' . esc_html( $date ) . '</p>';
		echo '</div>';
	}
}
