<?php
namespace ModulesAbstract\PluginReports\Report\Model\Gatherer;

/**
 * Gatherer for the imported documents
 * @author Oana Nicolau
 *
 */
class ImportedDocuments extends GathererAbstract
{

	/**
	 * Recordset resulted after $db->Execute()
	 * @var \ModulesAbstract\PluginReports\Report\Model\Gatherer\DatabasePaginatedIterator
	 */
	protected $importedDocumentsIterator = null;

	public function getRequiredFilters()
	{
		return [
			'entity',
		];
	}

	protected function objectInitialize()
	{
		\Engine\Debug\ParserCallTrace\ParserCallTrace::getInstance()->logCallStart($this, __METHOD__, func_get_args());

		// select the imported document
		$listObj = new \App\EntityList\ImportedDocuments();
		$listObj->setColumns([]);
		$listObj->setFilter('status', 'IN', ['new', 'partial']);

		if ($this->filters['period']) {
			$listObj->setFilter('docDate', '>=', $this->filters['period']['start']);
			$listObj->setFilter('docDate', '<=', $this->filters['period']['end']);
		}

		if ($this->filters['entity']['type'] == 'corporate') {
			$listObj->setFilter('idCorporate', '=', $this->filters['entity']['entityId']);
		}
		elseif ($this->filters['entity']['type'] == 'customer') {
			$listObj->setFilter('idCustomer', '=', $this->filters['entity']['entityId']);
		}
		elseif ($this->filters['entity']['type'] == 'supplier') {
			$listObj->setFilter('idSupplier', '=', $this->filters['entity']['entityId']);
		}
		else {
			throw new \Exception(sprintf("[%s] Unknown entity type specified: %s", __METHOD__, $this->filters['entity']['type']));
		}

		$this->importedDocumentsIterator = $listObj->getExecution();

		\Engine\Debug\ParserCallTrace\ParserCallTrace::getInstance()->logCallEnd();

	}
	protected function objectNext()
	{
		if ($this->importedDocumentsIterator && !$this->importedDocumentsIterator->EOF) {
			$result = $this->importedDocumentsIterator->FetchRow();

			$importedDocumentEntity = \Entity\ImportedDocument::select($result['id']);

			$value = 0;
			if ($importedDocumentEntity->status == 'partial') {
				$value = (float)($importedDocumentEntity->docValue - $importedDocumentEntity->usedValue);
			}
			else {
				$value = (float)$importedDocumentEntity->docValue;
			}

			return [
				'importedDocument' => 				$importedDocumentEntity,
				'value' =>							$value,
			];
		}
		return NULL;
	}

	protected function objectDestroy()
	{
		if ($this->importedDocumentsIterator) {
			$this->importedDocumentsIterator = null;
		}
	}

}