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

/**
 * Supplier invoice rows gatherer - return list with invoice rows
 * @author Oana Stan
 */
class SupplierInvoiceRows extends GathererAbstract
{

	/**
	 * Recordset resulted after $db->Execute
	 */
	protected $invoiceRowsIterator = NULL;

	/**
	 * (non-PHPdoc)
	 * @see \ModulesAbstract\PluginReports\Report\Model\Gatherer\GathererAbstract::getRequiredFilters()
	 */
	public function getRequiredFilters()
	{
		return [
			'invoiceDate',
		];
	}

	public function getAcceptedFilters()
	{
		return [
			'invoiceDate',
			'invoiceIssued',
		];
	}

	/**
	 * (non-PHPdoc)
	 * @see \ModulesAbstract\PluginReports\Report\Model\Gatherer\GathererAbstract::objectInitialize()
	 */
	protected function objectInitialize()
	{
		$listObj = new \App\EntityList\SupplierInvoiceRows();

		// set columns
		$listObj->setColumns([
			'invRow.id'=>'idInvoiceRow',
			'invRow.idInvoice',
			'invRow.serviceCode',
			'invRow.rowType',
			'invRow.externalReservationId',
			'invRow.externalReservationDate',
			'invRow.reservationCode',
			'invRow.reservationNumber',
			'invRow.reservationId',
			'invRow.checkIn',
			'invRow.priceValue',
			'invRow.vatValue',
		]);

		////////// APPLY FILTERS ////////////////////////////////////////////////////

		// filter by invoice date
		$listObj->setFilter('invoiceDate', '>=', $this->filters['invoiceDate']['start']);
		$listObj->setFilter('invoiceDate', '<=', $this->filters['invoiceDate']['end']);
		$listObj->setFilter('inv.invoiceNumber', '!=', 0);
		$listObj->applyUserRestriction(false);

		// filter only issued invoices
		if ($this->filters['invoiceIssued']) {
			$listObj->setFilter('blockTime', '>', 0);
		}

		// the orderBy is "global", dont use specific table names in here!!
		$listObj->setOrderBy('idInvoice', 'DESC');	// use DESC in order to list the "latest" invoices first, and then go to the older ones. The older ones would get skipped in the _next() function, as defined above
		$listObj->setOrderBy('idInvoiceRow', 'ASC');

		$this->invoiceRowsIterator = $listObj->getExecution();
	}

	/**
	 * (non-PHPdoc)
	 * @see \ModulesAbstract\PluginReports\Report\Model\Gatherer\GathererAbstract::objectDestroy()
	 */
	protected function objectDestroy()
	{
		if ($this->invoiceRowsIterator) {
			$this->invoiceRowsIterator->Close();
			$this->invoiceRowsIterator = NULL;
		}
	}

	/**
	 * (non-PHPdoc)
	 * @see \ModulesAbstract\PluginReports\Report\Model\Gatherer\GathererAbstract::objectNext()
	 */
	protected function objectNext()
	{
		if ($this->invoiceRowsIterator && !$this->invoiceRowsIterator->EOF) {
			$result = $this->invoiceRowsIterator->FetchRow();
			return $result;
		}
		return NULL;
	}
}