<?php
/**
 * Address columns on the WooCommerce orders list (free).
 *
 * @package Vanquish\MultipleAddresses\Admin
 */

namespace Vanquish\MultipleAddresses\Admin;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Adds optional "Billing address" / "Shipping address" columns to the admin
 * orders screen. Supports both the classic post-based list and the HPOS list.
 *
 * NOTE: scaffold. Column registration is wired for both storage backends; the
 * cell rendering pulls straight from the order, so no plugin meta is needed.
 */
class OrderListColumn {

	/**
	 * Constructor.
	 */
	public function __construct() {
		// Classic (posts) orders table.
		add_filter( 'manage_edit-shop_order_columns', array( $this, 'add_columns' ) );
		add_action( 'manage_shop_order_posts_custom_column', array( $this, 'render_column_classic' ), 10, 2 );

		// HPOS orders table.
		add_filter( 'manage_woocommerce_page_wc-orders_columns', array( $this, 'add_columns' ) );
		add_action( 'manage_woocommerce_page_wc-orders_custom_column', array( $this, 'render_column_hpos' ), 10, 2 );
	}

	/**
	 * Register the columns.
	 *
	 * @param array $columns Existing columns.
	 * @return array
	 */
	public function add_columns( $columns ) {
		$columns['vanmuad_billing']  = __( 'Billing address', 'vanquish-multiple-addresses-for-woocommerce' );
		$columns['vanmuad_shipping'] = __( 'Shipping address', 'vanquish-multiple-addresses-for-woocommerce' );

		return $columns;
	}

	/**
	 * Render a cell on the classic (post) list.
	 *
	 * @param string $column  Column id.
	 * @param int    $post_id Order id.
	 * @return void
	 */
	public function render_column_classic( $column, $post_id ) {
		$this->render_cell( $column, wc_get_order( $post_id ) );
	}

	/**
	 * Render a cell on the HPOS list.
	 *
	 * @param string                        $column Column id.
	 * @param \WC_Order|\WC_Abstract_Order $order  Order object.
	 * @return void
	 */
	public function render_column_hpos( $column, $order ) {
		$this->render_cell( $column, $order );
	}

	/**
	 * Shared cell renderer.
	 *
	 * @param string        $column Column id.
	 * @param \WC_Order|null $order  Order object.
	 * @return void
	 */
	private function render_cell( $column, $order ) {
		if ( ! $order instanceof \WC_Order ) {
			return;
		}

		if ( 'vanmuad_billing' === $column ) {
			echo wp_kses_post( $order->get_formatted_billing_address( '&mdash;' ) );
		} elseif ( 'vanmuad_shipping' === $column ) {
			echo wp_kses_post( $order->get_formatted_shipping_address( '&mdash;' ) );
		}
	}
}
