<?php

namespace WPDesk\FakturyKSEF\Xml;

use DOMDocument;
use WPDesk\FakturyKSEF\Api\Repository\DocumentStateRepository;
use WPDesk\FakturyKSEF\Xml\DocumentData\CorrectionDocumentData;
use WPDesk\FakturyKSEF\Xml\DocumentData\DocumentData;
use WPDesk\FakturyKSEF\Xml\Mapper\FA3\KorDataMapper;
use WPDesk\FakturyKSEF\Xml\Mapper\FA3\VatDataMapper;

class XmlFactory {

	public const NAMESPACE = 'http://crd.gov.pl/wzor/2025/06/25/13775/';

	private DocumentStateRepository $document_ksef_state_repository;

	public function __construct( DocumentStateRepository $document_ksef_state_repository ) {
		$this->document_ksef_state_repository = $document_ksef_state_repository;
	}

	public function create_correction( CorrectionDocumentData $document ): DOMDocument {
		$vat_data_mapper = new KorDataMapper( $this->document_ksef_state_repository );
		$data            = $vat_data_mapper->map( $document );

		return $this->build_converted_document( $data );
	}

	public function create_invoice( DocumentData $document ): DOMDocument {
		$vat_data_mapper = new VatDataMapper();
		$data            = $vat_data_mapper->map( $document );

		return $this->build_converted_document( $data );
	}

	private function build_converted_document( array $data ): DOMDocument {
		$dom = new DOMDocument( '1.0', 'UTF-8' );

		$root = $dom->createElementNS( self::NAMESPACE, 'tns:Faktura' );

		if ( isset( $data['Faktura'][ ArrayToXmlConverter::ATTRIBUTES_KEY ] ) ) {
			foreach ( $data['Faktura'][ ArrayToXmlConverter::ATTRIBUTES_KEY ] as $key => $value ) {
				if ( strpos( $key, 'xmlns:' ) === 0 ) {
					$root->setAttributeNS( 'http://www.w3.org/2000/xmlns/', $key, $value );
				} else {
					$root->setAttribute( $key, $value );
				}
			}
			unset( $data['Faktura'][ ArrayToXmlConverter::ATTRIBUTES_KEY ] );
		}

		$dom->appendChild( $root );

		$converter = new ArrayToXmlConverter( 'tns', self::NAMESPACE );
		$converter->build_xml( $dom, $root, $data['Faktura'] );

		return $dom;
	}
}
