<?php

namespace WPO\WC\PDF_Invoices_Pro;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( '\\WPO\\WC\\PDF_Invoices_Pro\\Edi' ) ) :

	class Edi {

		/**
		 * Constructor
		 */
		public function __construct() {
			add_filter( 'wpo_ips_edi_syntax_formats', array( $this, 'add_ubl_credit_note_documents' ) );
			add_filter( 'wpo_ips_edi_order_payment_totals', array( $this, 'adjust_totals_for_refunds' ), 10, 2 );
			add_filter( 'wpo_wcpdf_document_output_formats', array( $this, 'add_xml_format_to_bulk_documents' ), 10, 2 );
		}

		/**
		 * Add UBL credit note documents
		 * 
		 * @param array $formats
		 * @return array
		 */
		public function add_ubl_credit_note_documents( array $formats ): array {
			$formats['ubl']['formats']['ubl-2p1']['documents']['credit-note']        = \WPO\IPS\EDI\Syntaxes\Ubl\Formats\Ubl2p1\CreditNote::class;
			$formats['ubl']['formats']['peppol-bis-3p0']['documents']['credit-note'] = \WPO\IPS\EDI\Syntaxes\Ubl\Formats\PeppolBis3p0\CreditNote::class;
			return $formats;
		}
		
		/**
		 * Adjust totals for refunds / credit notes
		 * 
		 * @param array $totals
		 * @param \WC_Abstract_Order $order
		 * @return array
		 */
		public function adjust_totals_for_refunds( array $totals, \WC_Abstract_Order $order ): array {
			if ( 'shop_order_refund' === $order->get_type() || $order instanceof \WC_Order_Refund ) {
				$totals['prepaid_amount'] = 0.0;
				$totals['payable_amount'] = $totals['total_inc_tax'] + $totals['rounding_diff'];
			}

			return $totals;
		}
		
		/**
		 * Add XML format to bulk documents
		 * 
		 * @param array $formats
		 * @param object $document
		 * @return array
		 */
		public function add_xml_format_to_bulk_documents( array $formats, $document ): array {
			if ( $document instanceof \WPO\IPS\Documents\BulkDocument && ! in_array( 'xml', $formats, true ) ) {
				$formats[] = 'xml';
			}
			
			return $formats;
		}
		
	}

endif;

return new Edi();