<?php
/**
 * LegalMonetaryTotal class to get the legal monetary total data.
 *
 * @since 1.4.0
 * @package EDD\Invoices\XML\Elements
 */

namespace EDD\Pro\Invoices\XML\Elements;

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

/**
 * LegalMonetaryTotal class.
 */
class LegalMonetaryTotal extends Element {

	/**
	 * Total excluding VAT.
	 *
	 * @since 1.4.0
	 * @var float
	 */
	private $total_excluding_vat = 0;

	/**
	 * Total VAT amount.
	 *
	 * @since 1.4.0
	 * @var float
	 */
	private $total_vat_amount = 0;

	/**
	 * Get the data.
	 *
	 * @since 1.4.0
	 * @return array
	 */
	protected function get_data(): array {
		$this->calculate_totals();

		return array(
			'name'     => 'cac:LegalMonetaryTotal',
			'children' => array(
				array(
					'name'       => 'cbc:LineExtensionAmount',
					'value'      => $this->format_number( $this->total_excluding_vat ),
					'attributes' => array(
						'currencyID' => $this->order->currency,
					),
				),
				array(
					'name'       => 'cbc:TaxExclusiveAmount',
					'value'      => $this->format_number( $this->total_excluding_vat ),
					'attributes' => array(
						'currencyID' => $this->order->currency,
					),
				),
				array(
					'name'       => 'cbc:TaxInclusiveAmount',
					'value'      => $this->format_number( $this->total_excluding_vat + $this->total_vat_amount ),
					'attributes' => array(
						'currencyID' => $this->order->currency,
					),
				),
				array(
					'name'       => 'cbc:PayableAmount',
					'value'      => $this->format_number( $this->total_excluding_vat + $this->total_vat_amount ),
					'attributes' => array(
						'currencyID' => $this->order->currency,
					),
				),
			),
		);
	}

	/**
	 * Calculate totals.
	 *
	 * @since 1.4.0
	 */
	private function calculate_totals() {
		$items    = $this->order->get_items();
		$tax_rate = $this->get_tax_rate();
		foreach ( $items as $item ) {
			$line_total_excluding_vat = $item->quantity * $item->subtotal;
			$line_vat_amount          = $line_total_excluding_vat * ( $tax_rate / 100 );

			$this->total_excluding_vat += $line_total_excluding_vat;
			$this->total_vat_amount    += $line_vat_amount;
		}
	}

	/**
	 * Get tax rate.
	 *
	 * @since 1.4.0
	 * @return float
	 */
	private function get_tax_rate() {
		if ( $this->order->tax_rate_id ) {
			$tax_rate_object = $this->order->get_tax_rate_object();
			if ( $tax_rate_object ) {
				return $tax_rate_object->amount;
			}
		}

		$maybe_tax_rate = edd_get_order_meta( $this->order->id, 'tax_rate', true );
		if ( $maybe_tax_rate ) {
			return $maybe_tax_rate;
		}

		return 0;
	}
}
