<?php
namespace App\ExportData\ExportFile;

class ImportedDocument extends GeneralAbstract
{
	/**
	 * General description of the entity.
	 * @var String
	 */
	protected $entityType = 'importedDocument';

	/**
	 * General file name
	 * @var String
	 */
	protected $fileName = 'importedDocument';

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

	/**
	 * The document type of imported document
	 * @var String
	 */
	protected $documentType = NULL;

	/**
	 * The allowed operation types - they are checked in the constructor.
	 * @var array
	 */
	protected $allowedOperationTypes = ['issue', '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()
	{
		$importedDocumentEntity = \Entity\ImportedDocument::select($this->idEntity);

		$exportType = 'importedDocument|'.$importedDocumentEntity->docCategory."|".$importedDocumentEntity->docType;
		$importedDocConfig = \App\Config\ExportData_ActiveEntities::getInstance()->get($exportType);

		$operation = "";

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

		return !$importedDocConfig[$operation];
	}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\ExportData\ExportFile\GeneralAbstract::populateXml()
	 */
	protected function populateXml(\SimpleXMLElement $xml, \App\MessagesCollector $msgs)
	{
		$docEnt = \Entity\ImportedDocument::select($this->idEntity);

		// check record
		if (!$docEnt->recordExists()) {
			$msgs->addError("The imported document id `{$this->idEntity}` is not valid.");
		}

		$docObj = $docEnt->object;

		// set file name
		$this->fileName = '_importedDocument_'.$docEnt->docCategory.'_'.$docEnt->docType;

		// CREATE XML CONTENT ////////////////////////////////////////////////////////////////
		$xml->addAttribute('id', $docEnt->getId());
		$xml->addAttribute('operation', $this->operation);
		$xml->addAttribute('exportTime', \Engine\DateTime::create()->format("Y-m-d\TH:i:s"));
		$xml->addAttribute('addTime', \Engine\DateTime::create($docEnt->addTime)->format("Y-m-d\TH:i:s"));

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

		// system info
		$xml->addChild('idSystem', htmlUnclean($docEnt->idSystem));
		$sysXml = $xml->addChild('system');
		$sysXml->addAttribute('idTina', $docObj->getIdExternalSystem());
		$sysXml->addAttribute('code', htmlUnclean($docObj->externalSystemCode));

		// general details
		$xml->category = $docObj->getDocumentCategory();
		$xml->docType = $docObj->docType;
		$xml->docNumber = $docEnt->docNumber;
		$xml->docDate = $docObj->docDate;
		$xml->value = $docObj->value;
		$xml->currency = $docObj->currency;
		$xml->status = $docEnt->status;
		if ($docObj->explanations) {
			$xml->explanations = htmlUnclean($docObj->explanations);
		}
		if ($docObj->comments) {
			$xml->comments = htmlUnclean($docObj->comments);
		}
		if ($docObj->remarks) {
			$xmlRemarks = $xml->addChild('remarks');
			$this->attachXmlRemarks($xmlRemarks, $docObj->remarks, $docEnt->processedRemarks);
		}

		// agency bank account
		$baObj = $docObj->getAgencyBankAccount();
		if ($baObj) {
			$baXml = $xml->addChild('agencyBankAccount');
			if ($baObj->idTina) {
				$baXml->idTina = htmlUnclean($baObj->idTina);
			}
			if ($baObj->number) {
				$baXml->number = htmlUnclean($baObj->number);
			}
		}

		// add user details
		if ($docEnt->idAddUser) {
			$exportUserXML = $xml->addChild("addUser");
			$exportUserXML->addAttribute('id', $docEnt->idAddUser);
			$exportUserXML->lastName = htmlUnclean($docEnt->addUser->lastName);
			$exportUserXML->firstName = htmlUnclean($docEnt->addUser->firstName);
		}

		// responsible user details
		$respUser = $docObj->getResponsibleUser();
		if ($respUser) {
			$exportUserXML = $xml->addChild("respUser");
			if ($respUser->idTina) {
				$exportUserXML->idTina = htmlUnclean($respUser->idTina);
			}
			if ($respUser->idSystem) {
				$exportUserXML->idSystem = htmlUnclean($respUser->idSystem);
			}
			if ($respUser->lastName) {
				$exportUserXML->lastName = htmlUnclean($respUser->lastName);
			}
			if ($respUser->firstName) {
				$exportUserXML->firstName = htmlUnclean($respUser->firstName);
			}
		}

		$respOffice = $docObj->getResponsibleOffice();
		if ($respOffice) {
			$exportOfficeXML = $xml->addChild("respOffice");
			if ($respOffice->idTina) {
				$exportOfficeXML->idTina = htmlUnclean($respOffice->idTina);
			}
			if ($respOffice->idSystem) {
				$exportOfficeXML->idSystem = htmlUnclean($respOffice->idSystem);
			}
			if ($respOffice->name) {
				$exportOfficeXML->name = htmlUnclean($respOffice->name);
			}
		}

		// issue details
		if ($docEnt->idIssueUser) {
			$xml->issueUser = 			htmlUnclean($docEnt->issueUser->name);
			$xml->issueUser['id'] = 	$docEnt->idIssueUser;
		}
		if ($docEnt->issueTime) {
			$xml->issueTime = $docEnt->issueTime;
		}

		// partner details
		$exportDocPartnerDetailsXml = $xml->addChild("partner");

		$corpObj = $custObj = null;
		if ($docObj->getDocumentCategory()=='cashing') {
			$custObj = $docObj->getCustomer();
			if (!array_filter((array)$custObj)) { // if the object is empty
				$custObj = null;
			}
			$corpObj = $docObj->getCorporate();
			if (!array_filter((array)$corpObj)) { // if the object is empty
				$corpObj = null;
			}
		}
		if ($docObj->getDocumentCategory()=='payment') {
			$suppObj = $docObj->getSupplier();
			if (!array_filter((array)$suppObj)) { // if the object is empty
				$suppObj = null;
			}
		}

		if ($custObj) {
			$exportDocClientXml = $exportDocPartnerDetailsXml->addChild("customer");
			if ($docEnt->idCustomer) {
				$exportDocClientXml->addAttribute('initialMatchedId', $docEnt->idCustomer);
			}
			if ($custObj->idTina) {
				$exportDocClientXml->idTina = htmlUnclean($custObj->idTina);
			}
			if ($custObj->idSystem) {
				$exportDocClientXml->idSystem = htmlUnclean($custObj->idSystem);
			}
			if ($custObj->lastName) {
				$exportDocClientXml->lastName = htmlUnclean($custObj->lastName);
			}
			if ($custObj->firstName) {
				$exportDocClientXml->firstName = htmlUnclean($custObj->firstName);
			}
			if ($custObj->PNC) {
				$exportDocClientXml->PNC = htmlUnclean($custObj->PNC);
			}
			if ($custObj->email) {
				$exportDocClientXml->email = htmlUnclean($custObj->email);
			}
			if ($custObj->telephone) {
				$exportDocClientXml->telephone = htmlUnclean($custObj->telephone);
			}
		}
		elseif ($corpObj) {
			$exportDocClientXml = $exportDocPartnerDetailsXml->addChild("corporate");
			if ($docEnt->idCorporate) {
				$exportDocClientXml->addAttribute('initialMatchedId', $docEnt->idCorporate);
			}
			if ($corpObj->idTina) {
				$exportDocClientXml->idTina = htmlUnclean($corpObj->idTina);
			}
			if ($corpObj->idSystem) {
				$exportDocClientXml->idSystem = htmlUnclean($corpObj->idSystem);
			}
			if ($corpObj->name) {
				$exportDocClientXml->name = htmlUnclean($corpObj->name);
			}
			if ($corpObj->fiscalCode) {
				$exportDocClientXml->fiscalCode = htmlUnclean($corpObj->fiscalCode);
			}
			if ($corpObj->regNo) {
				$exportDocClientXml->regNo = htmlUnclean($corpObj->regNo);
			}
		}
		elseif ($suppObj) {
			$exportDocClientXml = $exportDocPartnerDetailsXml->addChild("supplier");
			if ($docEnt->idSupplier) {
				$exportDocClientXml->addAttribute('initialMatchedId', $docEnt->idSupplier);
			}
			if ($suppObj->idTina) {
				$exportDocClientXml->idTina = htmlUnclean($suppObj->idTina);
			}
			if ($suppObj->idSystem) {
				$exportDocClientXml->idSystem = htmlUnclean($suppObj->idSystem);
			}
			if ($suppObj->name) {
				$exportDocClientXml->name = htmlUnclean($suppObj->name);
			}
			if ($suppObj->fiscalCode) {
				$exportDocClientXml->fiscalCode = htmlUnclean($suppObj->fiscalCode);
			}
			if ($suppObj->zipCode) {
				$exportDocClientXml->zipCode = htmlUnclean($suppObj->zipCode);
			}
		}

		// REFERENCES

		// services
		if ($docEnt->docCategory=='cashing' && $docObj->getTinaServicesList()) {
			$servicesListXml = $xml->addChild('tinaServicesList');
			foreach ($docObj->getTinaServicesList() as $servObj) {
				$servXml = $servicesListXml->addChild('service');
				$servXml->addChild('idTina', htmlUnclean($servObj->idTina));
			}
		}

		// imported services
		if ($docEnt->docCategory=='cashing' && $docObj->getImportedServicesList()) {
			$impServicesListXml = $xml->addChild('importedServicesList');
			foreach ($docObj->getImportedServicesList() as $servobj) {
				$servXml = $impServicesListXml->addChild('importedService');
				if ($servobj->idTina) {
					$servXml->idTina = htmlUnclean($servobj->idTina);
				}
				if ($servobj->idServiceExtSys) {
					$servXml->idServiceExtSys = htmlUnclean($servobj->idServiceExtSys);
				}
				if ($servobj->extSysCode) {
					$servXml->extSysCode = htmlUnclean($servobj->extSysCode);
				}
			}
		}

		// client invoices
		if ($docEnt->docCategory=='cashing' && $docObj->getInvoicesList()) {
			$invoicesListXml = $xml->addChild('invoicesList');
			foreach ($docObj->getInvoicesList() as $invObj) {
				/* @var $invObj \App\ImportedDocument\ClientInvoice */
				$invXml = $invoicesListXml->addChild('invoice');
				if ($invObj->idTina) {
					$invXml->idTina = htmlUnclean($invObj->idTina);
				}
				if ($invObj->number) {
					$invXml->number = htmlUnclean($invObj->number);
				}
				if ($invObj->date) {
					$invXml->date = htmlUnclean($invObj->date);
				}
				if ($invObj->dueDate) {
					$invXml->dueDate = htmlUnclean($invObj->dueDate);
				}
				if ($invObj->limitProcessingValue) {
					$invXml->limitProcessingValue = htmlUnclean($invObj->limitProcessingValue);
				}
				if ($invObj->currency) {
					$invXml->currency = htmlUnclean($invObj->currency);
				}
			}
		}

		// supplier invoices
		if ($docEnt->docCategory=='payment' && $docObj->getSupplierInvoicesList()) {
			$supplierInvoicesListXml = $xml->addChild('supplierInvoicesList');
			foreach ($docObj->getSupplierInvoicesList() as $invObj) {
				/* @var $invObj \App\ImportedDocument\SupplierInvoice */
				$invXml = $supplierInvoicesListXml->addChild('supplierInvoice');
				if ($invObj->idTina) {
					$invXml->idTina = htmlUnclean($invObj->idTina);
				}
				if ($invObj->number) {
					$invXml->number = htmlUnclean($invObj->number);
				}
				if ($invObj->date) {
					$invXml->date = htmlUnclean($invObj->date);
				}
				if ($invObj->dueDate) {
					$invXml->dueDate = htmlUnclean($invObj->dueDate);
				}
				if ($invObj->limitProcessingValue) {
					$invXml->limitProcessingValue = htmlUnclean($invObj->limitProcessingValue);
				}
				if ($invObj->currency) {
					$invXml->currency = htmlUnclean($invObj->currency);
				}
			}
		}

		// generated documents
		if ($docEnt->documentsList) {
			$documentsListXml = $xml->addChild('generatedDocuments');
			$this->attachXmlGeneratedDocs($documentsListXml, $docEnt->documentsList);
		}

	}

}
