<?php
namespace App\ExportData\ExportFile;

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

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

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

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

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

	/**
	 * 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()
	{
		$cashbookDocumentEntity = \Entity\CashBookDocument::select($this->idEntity);

		$exportType = 'cashbookDoc|'.$cashbookDocumentEntity->category."|".$cashbookDocumentEntity->type;
		$cashBookConfig = \App\Config\ExportData_ActiveEntities::getInstance()->get($exportType);

		$operation = "";

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

		return !$cashBookConfig[$operation];
	}

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

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

		// set file name
		$this->fileName = '_cashbookDoc_'.$doc->category.'_'.$doc->type;

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

		// DOCUMENT DETAILS ///////////////////////////////////////////////////////////////////////////
		// main details
		$xml->category = 	htmlUnclean($doc->category);
		$xml->type = 		htmlUnclean($doc->type);

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

		$xml->docNumber = 	htmlUnclean($doc->number);
		$xml->docDate = 	$doc->date;
		$xml->value = 		$doc->value;
		$xml->currency = 	htmlUnclean($doc->currency);
		$xml->currency['exchangeRate'] = \App\CurrencyExchange\Rates::getInstance($doc->date)->convert(1, $doc->currency, \App\Config\Currencies::getInstance()->getDefaultCurrency(), null);
		if ($doc->partner) {
			$xml->partner = htmlUnclean($doc->partner);
		}
		if ($doc->explanations) {
			$xml->explanations = htmlUnclean($doc->explanations);
		}
		if ($doc->comments) {
			$xml->comments = htmlUnclean($doc->comments);
		}

		// the bank account
		if ($doc->idAgencyBankAccount) {
			$baEnt = $doc->agencyBankAccount;
			$xml->bankAccount['id'] = $doc->idAgencyBankAccount;
			if ($baEnt->account)
				$xml->bankAccount->account = htmlUnclean($baEnt->account);
			if ($baEnt->idBank) {
				$xml->bankAccount->bankName = htmlUnclean($baEnt->bank->name);
				$xml->bankAccount->bankName['id'] = $baEnt->idBank;
			}
			if ($baEnt->idBankOffice) {
				$xml->bankAccount->bankOfficeName = htmlUnclean($baEnt->bankOffice->name);
				$xml->bankAccount->bankOfficeName['id'] = $baEnt->idBankOffice;
			}
		}

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

		// issue details
		if ($doc->idIssueUser) {
			$xml->issueUser = 			htmlUnclean($doc->issueUser->name);
			$xml->issueUser['id'] = 	$doc->idIssueUser;
		}
		if ($doc->issueTime) {
			$xml->issueTime = \Engine\DateTime::createFromTimestamp($doc->issueTime)->format("Y-m-d\TH:i:s");
		}

		// block user
		if ($doc->idBlockUser) {
			$xml->blockUser = 		htmlUnclean($doc->blockUser->name);
			$xml->blockUser['id'] = $doc->idBlockUser;
		}
		if ($doc->blockTime) {
			$xml->blockTime = \Engine\DateTime::createFromTimestamp($doc->blockTime)->format("Y-m-d\TH:i:s");
		}

		// add user
		if ($doc->idAddUser) {
			$xml->addUser = 		htmlUnclean($doc->addUser->name);
			$xml->addUser['id'] = 	$doc->idAddUser;
		}
		$xml->addTime = \Engine\DateTime::createFromTimestamp($doc->addTime)->format("Y-m-d\TH:i:s");


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

	}
}