<?php
/**
 * VAT information relating to an EDD order record.
 *
 * @package     EDD\Pro\Taxes\VAT
 * @copyright   Copyright (c) 2025, Sandhills Development, LLC
 * @license     https://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       3.5.0
 */

namespace EDD\Pro\Taxes\VAT;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit; // @codeCoverageIgnore

/**
 * VAT information relating to an EDD order record.
 *
 * @since 3.5.0
 */
class Order {

	/**
	 * VAT number.
	 *
	 * @var string
	 */
	public $vat_number;

	/**
	 * Whether the VAT number is valid.
	 *
	 * @var bool
	 */
	public $is_vat_number_valid;

	/**
	 * Whether the VAT is reverse charged.
	 *
	 * @var bool
	 */
	public $is_reverse_charged;

	/**
	 * Whether the order is an EU order.
	 *
	 * @var bool
	 */
	public $is_eu_payment;

	/**
	 * Name of the customer.
	 *
	 * @var string
	 */
	public $name;

	/**
	 * Address of the customer.
	 *
	 * @var string
	 */
	public $address;

	/**
	 * VAT consultation number.
	 *
	 * @var string
	 */
	public $consultation_number;

	/**
	 * Retrieves VAT information for an order.
	 *
	 * @since 3.5.0
	 * @param int $order_id Order ID.
	 * @return Order
	 */
	public static function get( $order_id ) {
		$vat = new self();

		$vat->vat_number          = edd_get_order_meta( $order_id, '_edd_payment_vat_number', true );
		$vat->name                = edd_get_order_meta( $order_id, '_edd_payment_vat_company_name', true );
		$vat->address             = edd_get_order_meta( $order_id, '_edd_payment_vat_company_address', true );
		$vat->is_vat_number_valid = (bool) edd_get_order_meta( $order_id, '_edd_payment_vat_number_valid', true );
		$vat->is_eu_payment       = (bool) edd_get_order_meta( $order_id, '_edd_payment_vat_is_eu', true );
		$vat->consultation_number = edd_get_order_meta( $order_id, '_edd_payment_vat_consultation_number', true );
		$vat->is_reverse_charged  = (bool) self::is_vat_reverse_charged( $order_id );

		return $vat;
	}

	/**
	 * Checks if VAT is reverse charged.
	 *
	 * @since 3.5.0
	 * @param int $order_id Order ID.
	 * @return bool
	 */
	private static function is_vat_reverse_charged( $order_id ) {
		// Back-compat: old EDD VAT plugin used meta key '_edd_payment_vat_reversed_charged'.
		if ( metadata_exists( 'edd_order', $order_id, '_edd_payment_vat_reversed_charged' ) ) {
			return edd_get_order_meta( $order_id, '_edd_payment_vat_reversed_charged', true );
		}

		return edd_get_order_meta( $order_id, '_edd_payment_vat_reverse_charged', true );
	}
}
