<?php

namespace WcElectronInvoice\WooCommerce\Providers;


use WcElectronInvoice\Providers\OrdersProviderAbstract;

defined( 'ABSPATH' ) || die( 'Not allowed.' );

class OrdersProvider extends OrdersProviderAbstract {

	/**
	 * @inheritDoc
	 */
	public function getOrders( $args = array() ) {

		$query        = new \WC_Order_Query( $args );
		$orders       = [];

		foreach ( $query->get_orders() as $index => $orderId ) {
			$orders[] = $this->getOrder( $orderId );
		}

		return $orders;

	}

	/**
	 * @inheritDoc
	 */
	public function getOrderSummaries( $args = array() ) {
		$args = $this->mapArgs( $args );
		$args['return'] = 'ids';

		$summaries = array();
		foreach ( wc_get_orders( $args ) as $orderId ) {
			$order = $this->getOrder( $orderId );
			if ( ! $order ) {
				continue;
			}

			$extra = array();
			if ( is_subclass_of( $order, '\WcElectronInvoice\Providers\OrderRefund' ) ) {
				$parentOrder = $this->getOrder( $order->get_parent_id() );
				$refunds = $parentOrder && method_exists( $parentOrder, 'get_refunds' ) ? (array) $parentOrder->get_refunds() : array();
				$latestRefund = ! empty( $refunds ) ? end( $refunds ) : null;

				$extra = array(
					'parent_invoice_number'         => $parentOrder ? (string) $parentOrder->get_order_number_invoice() : '',
					'parent_invoice_sent'           => $parentOrder ? $parentOrder->get_invoice_sent( $order->get_parent_id() ) : '',
					'parent_invoice_sent_timestamp' => $parentOrder ? $parentOrder->get_invoice_sent_timestamp( $order->get_parent_id() ) : '',
					'refund_invoice_sent_timestamp' => $order->get_invoice_sent_timestamp( $order->get_id() ),
					'refund_number'                 => (string) $order->get_order_number_invoice(),
					'refund_count'                  => count( $refunds ),
					'is_latest_refund'              => $latestRefund ? ( (int) $latestRefund->get_id() === (int) $order->get_id() ) : true,
				);
			}

			$summaries[] = $this->buildOrderSummary( $order, $extra );
		}

		return $summaries;
	}

	/**
	 * @param $orderId
	 *
	 * @return null|\WcElectronInvoice\Providers\Order|\WcElectronInvoice\Providers\OrderRefund
	 */
	public function getOrder( $orderId ) {

		$order = wc_get_order( $orderId );
		if ( $order instanceof \WC_Order_Refund ) {
			return new OrderRefund(
				$order,
				$this,
				new TaxesProvider()
			);
		}

		if ( $order instanceof \WC_Order ) {
			return new Order(
				$order,
				$this,
				new TaxesProvider()
			);
		}

		return null;
	}

	/**
	 * @inerhitDoc
	 */
	public function name() {
		return 'woocommerce';
	}

	/**
	 * @inheritDoc
	 */
	public function get_label() {
		return __( 'WooCommerce', WC_EL_INV_TEXTDOMAIN );
	}

	/**
	 * @inheritDoc
	 */
	function mapArgs( $args ) {
		return $args;
	}
}
