<?php
/**
 * Admin order screen: show the delivery date and let staff edit it.
 * HPOS-safe (uses the order object, not post meta directly).
 *
 * @package Datery
 */

defined( 'ABSPATH' ) || exit;

class Datery_Admin {

	private static $instance = null;

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

	private function __construct() {
		add_action( 'woocommerce_admin_order_data_after_shipping_address', array( $this, 'render_edit_field' ) );
		add_action( 'woocommerce_process_shop_order_meta', array( $this, 'save_edit_field' ), 45, 2 );

		// Column in the orders list.
		add_filter( 'manage_woocommerce_page_wc-orders_columns', array( $this, 'add_list_column' ) );           // HPOS.
		add_filter( 'manage_edit-shop_order_columns', array( $this, 'add_list_column' ) );                       // Legacy.
		add_action( 'manage_woocommerce_page_wc-orders_custom_column', array( $this, 'render_list_column' ), 10, 2 ); // HPOS.
		add_action( 'manage_shop_order_posts_custom_column', array( $this, 'render_list_column_legacy' ), 10, 2 );    // Legacy.
	}

	public function render_edit_field( $order ) {
		$label = Datery_Settings::get( 'field_label', __( 'Delivery date', 'datery-delivery-date-for-woocommerce' ) );
		$value = $order->get_meta( DATERY_META_KEY );

		echo '<div class="datery-admin-delivery-date" style="margin-top:10px;">';
		echo '<p class="form-field form-field-wide"><label for="datery_admin_delivery_date"><strong>' . esc_html( $label ) . '</strong></label>';
		echo '<input type="date" id="datery_admin_delivery_date" name="datery_admin_delivery_date" value="' . esc_attr( $value ) . '" style="width:100%;" /></p>';
		echo '</div>';
	}

	public function save_edit_field( $order_id, $order ) {
		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			return;
		}
		// WooCommerce verifies the order-edit nonce before woocommerce_process_shop_order_meta fires; capability is also checked above.
		if ( ! isset( $_POST['datery_admin_delivery_date'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
			return;
		}
		$value = sanitize_text_field( wp_unslash( $_POST['datery_admin_delivery_date'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing

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

		if ( '' === $value ) {
			$order->delete_meta_data( DATERY_META_KEY );
		} else {
			// Admins may set any valid Y-m-d (not bound by the customer window).
			$d = DateTimeImmutable::createFromFormat( '!Y-m-d', $value, wp_timezone() );
			if ( $d && $d->format( 'Y-m-d' ) === $value ) {
				$order->update_meta_data( DATERY_META_KEY, $value );
			}
		}
		$order->save();
	}

	public function add_list_column( $columns ) {
		$new = array();
		foreach ( $columns as $key => $name ) {
			$new[ $key ] = $name;
			if ( 'order_status' === $key ) {
				$new['datery_delivery_date'] = Datery_Settings::get( 'field_label', __( 'Delivery date', 'datery-delivery-date-for-woocommerce' ) );
			}
		}
		// Fallback if order_status column was not found.
		if ( ! isset( $new['datery_delivery_date'] ) ) {
			$new['datery_delivery_date'] = Datery_Settings::get( 'field_label', __( 'Delivery date', 'datery-delivery-date-for-woocommerce' ) );
		}
		return $new;
	}

	public function render_list_column( $column, $order ) {
		if ( 'datery_delivery_date' !== $column ) {
			return;
		}
		$value = $order ? $order->get_meta( DATERY_META_KEY ) : '';
		echo $value ? esc_html( Datery_Dates::display( $value ) ) : '&mdash;';
	}

	public function render_list_column_legacy( $column, $post_id ) {
		if ( 'datery_delivery_date' !== $column ) {
			return;
		}
		$order = wc_get_order( $post_id );
		$value = $order ? $order->get_meta( DATERY_META_KEY ) : '';
		echo $value ? esc_html( Datery_Dates::display( $value ) ) : '&mdash;';
	}
}
