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

/**
 * Invoice reservation gatherer, will list services with "fake invoices" (confirmed and cancelled)
 * The output will be a list of service id's
 */
class OrderServicesWithFakeInvoicesAndVoids extends OrderServices
{
	/**
	 * (non-PHPdoc)
	 * @see \ModulesAbstract\PluginReports\Report\Model\Gatherer\GathererAbstract::objectInitialize()
	 */
	protected function objectInitialize()
	{
		$listObj = new \App\EntityList\OrderServices();

		// get columns
		$listObj->setColumns([
			'serv.id' => 					'idOrderService',
			'serv.passengersTicketsDate' => 'ticketDate',
		]);

		//// APPLY FILTERS //////////////////////////////////
		// filter by passenger tickets date

		$listObj->setFilter('res.date', 'BETWEEN', [
				\Engine\DateTime::createFromIsoDate($this->filters['ticketDate']['start'])->sub(new \DateInterval('P6M'))->formatDateIso(),
				\Engine\DateTime::createFromIsoDate($this->filters['ticketDate']['end'])->add(new \DateInterval('P6M'))->formatDateIso(),
		]);

		// filter services with statusOp 'OK' for confirmed or 'XX' for voids
		$listObj->setFilter('serv.statusOp', 'IN', ['OK', 'XX']);

		// filter by idUser or idOffice
		if ($this->filters['userAndOffice']['type'] == 'user') {
			if ($this->filters['userAndOffice']['entityId']) {
				$listObj->setFilter('serv.idUser', '=', $this->filters['userAndOffice']['entityId']);
			}
		}
		elseif ($this->filters['userAndOffice']['type'] == 'office') {
			if ($this->filters['userAndOffice']['entityId']) {
				$listObj->setFilter('serv.idOffice', '=', $this->filters['userAndOffice']['entityId']);
			}
		}

		// filter by corporate or segment or groups
		// when filtering by corporate/segment/groups, if the specified segment doesn't contain any corporates, directly return a fake empty resultset
		if (in_array($this->filters['corporatesAndSegmentsAndGroups']['type'], ['segment', 'groups']) && !$this->filters['corporatesAndSegmentsAndGroups']['corporateIds']) {
			$this->orderServicesIterator = new \ADORecordSet_empty();
			return;
		}

		if (in_array($this->filters['corporatesAndSegmentsAndGroups']['type'], ['all', 'corporate', 'segment', 'groups'])) {
			if ($this->filters['corporatesAndSegmentsAndGroups']['corporateIds']) {
				$listObj->setFilter('res.idCorporateOwner', 'IN', $this->filters['corporatesAndSegmentsAndGroups']['corporateIds']);
			}
			else {
				$listObj->setFilter('res.idCorporateOwner', '!=', 0);
			}
		}
		else {
			throw new \Exception(sprintf("%s type is invalid", __METHOD__));
		}

		$listObj->setFilter('off.offerWorkTotal', '=', 0);

		// order services
		$listObj->setOrderBy('ticketDate', 'ASC');
		$listObj->setOrderBy('idOrderService', 'ASC');
		$listObj->applyUserRestriction(false);

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