<?php
/**
 * InvoiceLine class to get the order item data.
 *
 * @since 1.4.0
 * @package EDD\Invoices\XML\Elements
 */

namespace EDD\Pro\Invoices\XML\Elements;

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

/**
 * InvoiceLine class.
 */
class InvoiceLine extends Element {

	/**
	 * 1-based sequential line number (BT-126).
	 *
	 * @since 3.6.7
	 * @var int
	 */
	private int $line_number;

	/**
	 * Element constructor.
	 *
	 * @since 3.6.7
	 * @param \SimpleXMLElement $xml         The XML document.
	 * @param object            $item        The order item.
	 * @param int               $line_number 1-based sequential line ID (BT-126).
	 */
	public function __construct( $xml, $item = null, int $line_number = 1 ) {
		parent::__construct( $xml, $item );
		$this->line_number = $line_number;
	}

	/**
	 * Gets the data.
	 *
	 * @since 1.4.0
	 * @return array
	 */
	protected function get_data(): array {
		return array(
			'name'     => 'cac:InvoiceLine',
			'children' => $this->get_item_data(),
		);
	}

	/**
	 * Get the item data.
	 *
	 * @since 1.4.0
	 * @return array
	 */
	private function get_item_data() {
		$item = $this->item;

		return array(
			array(
				'name'  => 'cbc:ID',
				'value' => $this->line_number,
			),
			array(
				'name'       => 'cbc:InvoicedQuantity',
				'value'      => $item->quantity,
				'attributes' => array(
					'unitCode' => 'C62',
				),
			),
			array(
				'name'       => 'cbc:LineExtensionAmount',
				'value'      => $this->format_number( $item->subtotal ),
				'attributes' => array(
					'currencyID' => $this->order->currency,
				),
			),
			array(
				'name'     => 'cac:Item',
				'children' => array(
					array(
						'name'  => 'cbc:Description',
						'value' => $item->product_name,
					),
					array(
						'name'  => 'cbc:Name',
						'value' => $item->product_name,
					),
					array(
						'name'     => 'cac:ClassifiedTaxCategory',
						'children' => $this->get_tax_category_children(),
					),
				),
			),
			array(
				'name'     => 'cac:Price',
				'children' => array(
					array(
						'name'       => 'cbc:PriceAmount',
						'value'      => $this->format_number( $item->subtotal / max( $item->quantity, 1 ) ),
						'attributes' => array(
							'currencyID' => $this->order->currency,
						),
					),
				),
			),
		);
	}
}
