<?php
/**
 * Class to generate an XML document with UBL 2.1 format.
 *
 * @since 1.4.0
 * @package EDD\Invoices\XML
 */

namespace EDD\Pro\Invoices\XML;

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

/**
 * Document class.
 *
 * @since 1.4.0
 */
class Document {

	/**
	 * Order object.
	 *
	 * @since 1.4.0
	 * @var \EDD\Orders\Order
	 */
	public $order;

	/**
	 * DOMDocument object.
	 *
	 * @since 1.4.0
	 * @var \DOMDocument
	 */
	public $dom;

	/**
	 * Constructor.
	 *
	 * @since 1.4.0
	 * @param \EDD\Orders\Order $order Order object.
	 */
	public function __construct( $order ) {
		$this->order = $order;
	}

	/**
	 * Generate the XML file.
	 *
	 * @since 1.4.0
	 * @return string|bool Path to the generated file or false on failure.
	 */
	public function generate() {
		if ( ! $this->order ) {
			return false;
		}

		$this->dom               = new \DOMDocument( '1.0' );
		$this->dom->formatOutput = true; // phpcs:ignore

		$invoice  = new Elements\Invoice( $this );
		$invoice  = $invoice->add();
		$supplier = new Elements\Supplier( $this );
		$supplier = $supplier->add( $invoice );

		$buyer = new Elements\Buyer( $this );
		$buyer = $buyer->add( $invoice );

		$tax_total = new Elements\TaxTotal( $this );
		$tax_total = $tax_total->add( $invoice );

		$legal_monetary_total = new Elements\LegalMonetaryTotal( $this );
		$legal_monetary_total = $legal_monetary_total->add( $invoice );

		foreach ( $this->order->get_items() as $order_item ) {
			$item = new Elements\InvoiceLine( $this, $order_item );
			$item = $item->add( $invoice );
		}

		$file = edd_get_exports_dir() . '/invoice-' . $this->order->get_number() . '.xml';
		if ( $this->dom->save( $file ) ) {
			return $file;
		}

		return false;
	}

	/**
	 * Download the XML file.
	 *
	 * @since 1.4.0
	 * @return void
	 */
	public function download() {
		if ( ! $this->dom ) {
			wp_die( esc_html__( 'No XML document found.', 'easy-digital-downloads' ) );
		}

		echo $this->dom->saveXML(); // phpcs:ignore
	}
}
