<?php

namespace App\ExportData\ExportFile;

class SupplierInvoicePayment extends GeneralAbstract
{
	/**
	 * General description of the entity. Used in the XML file name.
	 * @var String
	 */
	protected $entityType = 'payment';

	/**
	 * The XML root tag name.
	 * @var String
	 */
	protected $rootTag = 'payment';

	/**
	 * The document type of supplier invoice payment
	 * @var String
	 */
	protected $documentType = NULL;

	/**
	 * The allowed operation types - they are checked in the constructor.
	 * @var array
	 */
	protected $allowedOperationTypes = ['issue', 'confirm', 'unconfirm', 'void'];

	/**
	 * Checks the input for the current class.
	 * @param Int $idEntity
	 * @param String $operation
	 * @throws \Exception - if there's anything wrong with the input
	 */
	public function __construct($idEntity, $operation, $documentType=NULL)
	{
		parent::__construct($idEntity, $operation);

		if ($this->operation == 'issue' and !$documentType) {
			throw new \Exception("The document type `{$documentType}` is not valid for entity type `{$this->entityType}`, operation `{$this->operation}`.");
		}

		$this->documentType = $documentType;
	}

	/**
	 * {@inheritDoc}
	 * @see \App\ExportData\ExportFile\GeneralAbstract::checkIfInactiveEntity()
	*/
	protected function checkIfInactiveEntity()
	{
		$supplierInvoicePaymentEntity = \Entity\SupplierInvoicePayment::select($this->idEntity);
		$supplierInvPaymentConfig = \App\Config\ExportData_ActiveEntities::getInstance()->get('payment|'.$supplierInvoicePaymentEntity->docTypeCode);

		$operation = "";

		if ($this->operation == "issue" or $this->operation == "void") {
			$operation = "issue";
		}
		elseif ($this->operation == "confirm" or $this->operation == "unconfirm") {
			$operation = "block";
		}

		return !$supplierInvPaymentConfig[$operation];
	}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\ExportData\ExportFile\GeneralAbstract::populateXml()
	 */
	protected function populateXml(\SimpleXMLElement $xml, \App\MessagesCollector $msgs)
	{
		global $CFG;

		// GET DOCUMENT DETAILS ///////////////////////////////////////////////////////////////////
		$supplierInvoicePaymentEntity = \Entity\SupplierInvoicePayment::select($this->idEntity);

		// check record
		if (!$supplierInvoicePaymentEntity->recordExists()) {
			$msgs->addError("The supplier invoice payment id `{$this->idEntity}` is not valid.");
		}
		$supplierInvoiceEntity = $supplierInvoicePaymentEntity->supplierInvoice;

		// set file name
		$this->fileName = "payment_".$supplierInvoicePaymentEntity->docTypeCode;

		// GET IMPORTED DOCUMENT DETAILS //////////////////////////////////////////////////////////
		if ($supplierInvoicePaymentEntity->idImportedDoc) {
			$importedDocument = $supplierInvoicePaymentEntity->importedDocument;
			$importingSystem = \Entity\ImportedDocumentsSystem::select($importedDocument->idExternalSystem);
		}

		// EXPORT CONFIGS ////////////////////////////////////////////////////////////////////////
		$idOffice = $supplierInvoicePaymentEntity->blockUser->idOffice;
		if (!$idOffice) {
			$idOffice = CURRENT_ID_OFFICE;
		}

		$docComponents = [
			'docType' => 		$supplierInvoicePaymentEntity->docTypeCode,
			'idOffice' => 		$idOffice,
			'idBankAccount' => 	$supplierInvoicePaymentEntity->idBankAccount,
			'currency' =>		$supplierInvoicePaymentEntity->currency,
		];

		$exportConfigs = \App\Config\ExportData_Fields_Payment::getInstance()->getActiveFieldsValues($docComponents);


		// CREATE XML CONTENT /////////////////////////////////////////////////////////////////////

		// add main attributes
		$xml['operation'] = 	$this->operation;

		if ($this->operation == 'issue') {
			$xml['issueDocType'] = $this->documentType;
		}

		$xml['id'] = 			$this->idEntity;
		$xml['exportTime'] = 	date("Y-m-d\TH:i:s");

		// IMPORTED DOCUMENT DETAILS //////////////////////////////////////////////////////////////
		if ($supplierInvoicePaymentEntity->idImportedDoc) {
			$xml->imported = '';
			$xml->imported['idDocTina'] = 	$supplierInvoicePaymentEntity->idImportedDoc;
			$xml->imported['idDocSystem'] = htmlUnclean($importedDocument->idSystem);
			$xml->imported->system = '';
			$xml->imported->system['id'] = $importedDocument->idExternalSystem;
			if ($importingSystem->code) {
				$xml->imported->system['code'] = htmlUnclean($importingSystem->code);
			}
			if ($importingSystem->name) {
				$xml->imported->system['name'] = htmlUnclean($importingSystem->name);
			}
		}

		// DOCUMENT GENERAL DATA //////////////////////////////////////////////////////////////////
		if ($supplierInvoicePaymentEntity->docNumber) {
			$xml->docNumber = htmlUnclean($supplierInvoicePaymentEntity->docNumber);
		}
		$xml->docDate = 	$supplierInvoicePaymentEntity->docDate;
		if ($supplierInvoicePaymentEntity->idPaymentSeries) {
			$xml->paymentSeries			= htmlUnclean($supplierInvoicePaymentEntity->paymentSeries->code);
			$xml->paymentSeries['id']	= $supplierInvoicePaymentEntity->idPaymentSeries;
		}
		$xml->docType =		$supplierInvoicePaymentEntity->docTypeCode;
		$xml->value = 		$supplierInvoicePaymentEntity->value;
		$xml->currency = 	htmlUnclean($supplierInvoicePaymentEntity->currency);
		$xml->currency['exchangeRate'] = \App\CurrencyExchange\Rates::getInstance($supplierInvoicePaymentEntity->docDate, $CFG['currencies']['defaultCurrencyType'])->convert(1, $supplierInvoicePaymentEntity->currency, $CFG['currencies']['defaultCurrency'], null);

		$xml->invoicePayedValue = $supplierInvoicePaymentEntity->invoicePayedValue;

		if ($supplierInvoicePaymentEntity->explanations) {
			$xml->explanations = htmlUnclean($supplierInvoicePaymentEntity->explanations);
		}
		if ($supplierInvoicePaymentEntity->comments) {
			$xml->comments = htmlUnclean($supplierInvoicePaymentEntity->comments);
		}

		// add remarks
		if ($supplierInvoicePaymentEntity->remarks) {
			$xmlRemarks = $xml->addChild('remarks');
			$this->attachXmlRemarks($xmlRemarks, $supplierInvoicePaymentEntity->remarks, $supplierInvoicePaymentEntity->processedRemarks);
		}


		// BANK ACCOUNT ///////////////////////////////////////////////////////////////////////////
		if ($supplierInvoicePaymentEntity->idBankAccount) {
			$bankAccountEntity = $supplierInvoicePaymentEntity->bankAccount;
			$xml->bankAccount['id'] = $supplierInvoicePaymentEntity->idBankAccount;

			if ($bankAccountEntity->account) {
				$xml->bankAccount->account = htmlUnclean($bankAccountEntity->account);
			}

			if ($bankAccountEntity->idBank) {
				$xml->bankAccount->bankName = 		htmlUnclean($bankAccountEntity->bank->name);
				$xml->bankAccount->bankName['id'] = $bankAccountEntity->idBank;
			}

			if ($bankAccountEntity->idBankOffice) {
				$xml->bankAccount->bankOfficeName = 		htmlUnclean($bankAccountEntity->bankOffice->name);
				$xml->bankAccount->bankOfficeName['id'] = 	$bankAccountEntity->idBankOffice;
			}
		}

		// ADD USER -------------------------------------------------------------------------------
		$xml->addUser['id'] = 				$supplierInvoicePaymentEntity->idAddUser;
		$xml->addUser->lastName = 			htmlUnclean($supplierInvoicePaymentEntity->addUser->lastName);
		$xml->addUser->firstName = 			htmlUnclean($supplierInvoicePaymentEntity->addUser->firstName);
		$xml->addUser->office = 			htmlUnclean($supplierInvoicePaymentEntity->addUser->office->name);
		$xml->addUser->office['id']=  		$supplierInvoicePaymentEntity->addUser->idOffice;
		$xml->addUser->department = 		htmlUnclean($supplierInvoicePaymentEntity->addUser->department->name);
		$xml->addUser->department['id'] = 	$supplierInvoicePaymentEntity->addUser->idDepartment;
		$xml->addTime =						\Engine\DateTime::createFromTimestamp($supplierInvoicePaymentEntity->addTime)->format("Y-m-d\TH:i:s");

		// BLOCK USER -----------------------------------------------------------------------------
		if ($supplierInvoicePaymentEntity->idBlockUser) {
			$xml->blockUser['id'] = 				$supplierInvoicePaymentEntity->idBlockUser;
			$xml->blockUser->lastName = 			htmlUnclean($supplierInvoicePaymentEntity->blockUser->lastName);
			$xml->blockUser->firstName = 			htmlUnclean($supplierInvoicePaymentEntity->blockUser->firstName);
			$xml->blockUser->office = 				htmlUnclean($supplierInvoicePaymentEntity->blockUser->office->name);
			$xml->blockUser->office['id'] = 		$supplierInvoicePaymentEntity->blockUser->idOffice;
			$xml->blockUser->department = 			htmlUnclean($supplierInvoicePaymentEntity->blockUser->department->name);
			$xml->blockUser->department['id'] = 	$supplierInvoicePaymentEntity->blockUser->idDepartment;
		}
		if ($supplierInvoicePaymentEntity->blockTime) {
			$xml->blockTime = \Engine\DateTime::createFromTimestamp($supplierInvoicePaymentEntity->blockTime)->format("Y-m-d\TH:i:s");
		}

		// ISSUE USER -----------------------------------------------------------------------------
		if ($supplierInvoicePaymentEntity->idIssueUser) {
			$xml->issueUser['id'] = 				$supplierInvoicePaymentEntity->idIssueUser;
			$xml->issueUser->lastName = 			htmlUnclean($supplierInvoicePaymentEntity->issueUser->lastName);
			$xml->issueUser->firstName = 			htmlUnclean($supplierInvoicePaymentEntity->issueUser->firstName);
			$xml->issueUser->office = 				htmlUnclean($supplierInvoicePaymentEntity->issueUser->office->name);
			$xml->issueUser->office['id'] = 		$supplierInvoicePaymentEntity->issueUser->idOffice;
			$xml->issueUser->department = 			htmlUnclean($supplierInvoicePaymentEntity->issueUser->department->name);
			$xml->issueUser->department['id'] = 	$supplierInvoicePaymentEntity->issueUser->idDepartment;
		}
		if ($supplierInvoicePaymentEntity->issueTime) {
			$xml->issueTime = \Engine\DateTime::createFromTimestamp($supplierInvoicePaymentEntity->issueTime)->format("Y-m-d\TH:i:s");
		}

		// RESPONSIBLE USER -----------------------------------------------------------------------
		$xml->responsibleUser='';
		$xml->responsibleUser['id'] = 				$supplierInvoicePaymentEntity->idUser;
		$xml->responsibleUser->lastName = 			htmlUnclean($supplierInvoicePaymentEntity->user->lastName);
		$xml->responsibleUser->firstName = 			htmlUnclean($supplierInvoicePaymentEntity->user->firstName);
		$xml->responsibleUser->office = 			htmlUnclean($supplierInvoicePaymentEntity->office->name);
		$xml->responsibleUser->office['id'] = 		$supplierInvoicePaymentEntity->idOffice;
		$xml->responsibleUser->department = 		htmlUnclean($supplierInvoicePaymentEntity->user->department->name);
		$xml->responsibleUser->department['id'] = 	$supplierInvoicePaymentEntity->user->idDepartment;
		$xml->responsibleUser->department['code'] = htmlUnclean($supplierInvoicePaymentEntity->user->department->code);


		// SUPPLIER INVOICE GENERAL DETAILS ///////////////////////////////////////////////////////
		$xml->invoiceDetails='';
		$xml->invoiceDetails['id'] = 				$supplierInvoiceEntity->getId();
		$xml->invoiceDetails->invoiceNumber = 		htmlUnclean($supplierInvoiceEntity->invoiceNumber);
		$xml->invoiceDetails->invoiceDate = 		$supplierInvoiceEntity->invoiceDate;
		$xml->invoiceDetails->invoiceTotalValue =  	$supplierInvoiceEntity->totalValue;
		$xml->invoiceDetails->invoiceCurrency = 	$supplierInvoiceEntity->currency;

		// SUPPLIER DETAILS -----------------------------------------------------------------------
		$supplierEntity = $supplierInvoiceEntity->supplier;
		$xml->invoiceDetails->supplier = '';
		$xml->invoiceDetails->supplier['id'] = $supplierEntity->getId();
		if ($supplierEntity->idRealSupplier) {
			$xml->invoiceDetails->supplier['idRealSupplier'] = $supplierEntity->idRealSupplier;
		}
		$xml->invoiceDetails->supplier->alias = 			htmlUnclean($supplierEntity->alias);
		$xml->invoiceDetails->supplier->company = 			htmlUnclean($supplierEntity->company);
		$xml->invoiceDetails->supplier->company['prefix'] = htmlUnclean($supplierEntity->companyPrefix);
		$xml->invoiceDetails->supplier->company['suffix'] = htmlUnclean($supplierEntity->companySuffix);
		if ($supplierEntity->fiscalCode) {
			$xml->invoiceDetails->supplier->fiscalCode = htmlUnclean($supplierEntity->fiscalCode);
		}
		if ($supplierEntity->regNo) {
			$xml->invoiceDetails->supplier->regNo = htmlUnclean($supplierEntity->regNo);
		}

		// RESPONSIBLE USER -----------------------------------------------------------------------
		$xml->invoiceDetails->responsibleUser = '';
		$xml->invoiceDetails->responsibleUser['id'] = 				$supplierInvoiceEntity->idUser;
		$xml->invoiceDetails->responsibleUser->lastName = 			htmlUnclean($supplierInvoiceEntity->user->lastName);
		$xml->invoiceDetails->responsibleUser->firstName = 			htmlUnclean($supplierInvoiceEntity->user->firstName);
		$xml->invoiceDetails->responsibleUser->office = 			htmlUnclean($supplierInvoiceEntity->office->name);
		$xml->invoiceDetails->responsibleUser->office['id'] = 		$supplierInvoiceEntity->idOffice;
		$xml->invoiceDetails->responsibleUser->department = 		htmlUnclean($supplierInvoiceEntity->user->department->name);
		$xml->invoiceDetails->responsibleUser->department['id'] = 	$supplierInvoiceEntity->user->idDepartment;

		// GENERATED DOCUMENTS ////////////////////////////////////////////////////////////////////
		if ($supplierInvoicePaymentEntity->documentsList) {
			$documentsListXml = $xml->addChild('generatedDocuments');
			$this->attachXmlGeneratedDocs($documentsListXml, $supplierInvoicePaymentEntity->documentsList);
		}

		// DOCUMENT EXPORT CONFIGS ////////////////////////////////////////////////////////////////
		if (is_array($exportConfigs)) {
			$xml->exportConfigs='';
			foreach($exportConfigs as $expCfgName => $expCfgVal) {
				if (!$expCfgName) {
					$expCfgName="_DEFAULT_";
				}
				$xml->exportConfigs->$expCfgName = htmlUnclean($expCfgVal);
			}
		}

	}

}
