<?php
namespace Modules\Invoices\BalancesAuto;

class Model extends \App\Mvc\Model_ListingAbstract
{

	/**
	 * {@inheritDoc}
	 * @see \App\Mvc\Model_ListingAbstract::list_execute()
	 */
	public function list_execute(\App\Mvc\View\Listing\Members\Params $listingParams)
	{

		$filters = $listingParams->getFilters();
		$listObj = new \App\EntityList\ServicesBalancesSuggestions();
		$listObj->setColumns(['idService' => 'id', 'component', 'idOrder', 'orderNumber', 'orderDate', 'offerStartDate',
			'idUser', 'idOffice', 'ticketsList', 'invoiceIdCorporate', 'invoiceIdCustomer', 'clientInvoiceDate',
			'idSupplierInvoiceRows', 'idSupplierInvoices', 'supplierInvoiceDate', 'score', 'scoreDetails'
		]);

		// ORDER DATE FILTER
		if ($filters['orderDate']['start']) {
			$listObj->setFilter('orderDate', '>=', $filters['orderDate']['start']);
		}

		if ($filters['orderDate']['end']) {
			$listObj->setFilter('orderDate', '<=', $filters['orderDate']['end']);
		}

		// SERVICE CODE FILTER
		if ($filters['serviceCode']) {
			$listObj->setFilter('serviceCode', '=', $filters['serviceCode']);
		}

		// ID EXTERNAL SYSTEM FILTER
		if ($filters['idExternalSystem']) {
			$listObj->setFilter('idExternalSystem', '=', $filters['idExternalSystem']);
		}

		// ID ORDER FILTER
		if ($filters['idOrder']) {
			if ($filters['idOrderType']) {
				switch ($filters['idOrderType']) {
					case 'id':
						$listObj->setFilter('idOrder', '=', (int)\App\Utils\Db\TablesUtils::getInstance()->switchIdReservationConversion($filters['idOrder'], 'normal'));
						break;
					case 'code':
						$listObj->setFilter('orderCode', '=', $filters['idOrder']);
						break;
					case 'number':
						$listObj->setFilter('orderNumber', '=', $filters['idOrder']);
						break;
					case 'idService':
						$listObj->setFilter('idService', '=', $filters['idOrder']);
						break;
				}
			}
		}

		// OFFER DATE FILTER
		if ($filters['offerStartDate']['start']) {
			$listObj->setFilter('offerStartDate', '>=', $filters['offerStartDate']['start']);
		}

		if ($filters['offerStartDate']['end']) {
			$listObj->setFilter('offerStartDate', '<=', $filters['offerStartDate']['end']);
		}

		// OFFICE / USER ID FILTER
		if ($filters['idOfficeUser']) {
			list($idOffice, $idUser) = explode('|', $filters['idOfficeUser']['id']);

			if ($idUser) {
				$listObj->setFilter('idUser', '=', $idUser);
			}
			elseif ($idOffice) {
				$listObj->setFilter('idOffice', '=', $idOffice);
			}

		}

		// LOCATION CRITERION FILTER
		if ($filters['offerCriterion']) {
			$listObj->setFilter('location', '=', $filters['offerCriterion']);
		}

		// MICE FILTER
		// mice services assoc
		if ($filters['miceAssoc'] == 'miceServices') {
			$listObj->setFilter('idMiceProject', '>', 0);
		}
		elseif ($filters['miceAssoc'] == 'nonMiceServices') {
			$listObj->setFilter('idMiceProject', '=', 0);
		}
		// mice project
		if ($filters['idMiceProject']['id']) {
			$listObj->setFilter('idMiceProject', '=', $filters['idMiceProject']['id']);
		}

		// TICKET DATE FILTER
		if ($filters['ticketDate']['start']) {
			$listObj->setFilter('ticketDate', '>=', $filters['ticketDate']['start']);
		}

		if ($filters['ticketDate']['end']) {
			$listObj->setFilter('ticketDate', '<=', $filters['ticketDate']['end']);
		}

		// SUPPLIER FILTER
		if ($filters['idSupplier']['id']) {
			$listObj->setFilter('idSupplier', '=', $filters['idSupplier']['id']);
		}

		// COMPANY FILTER
		if ($filters['idInvoiceCorporate']['id']) {
			$listObj->setFilter('invoiceIdCorporate', '=', $filters['idInvoiceCorporate']['id']);
		}

		// CUSTOMER FILTER
		if ($filters['idInvoiceCustomer']['id']) {
			$listObj->setFilter('invoiceIdCustomer', '=', $filters['idInvoiceCustomer']['id']);
		}

		// OPTION DATE FILTER
		if ($filters['optionDate']['start']) {
			$listObj->setFilter('optionDate', '>=', $filters['optionDate']['start']);
		}

		if ($filters['optionDate']['end']) {
			$listObj->setFilter('optionDate', '<=', $filters['optionDate']['end']);
		}

		// SUPPLIER INVOICE STATUS FILTER
		if ($filters['supplierInvoiceStatusOp']) {
			$listObj->setFilter('supplierInvoicesStatus', '=', $filters['supplierInvoiceStatusOp']);
		}

		// BALANCE COMPONENT
		if ($filters['balanceComponent']) {
			$listObj->setFilter('component', '=', $filters['balanceComponent']);
		}

		// CLIENT/SUPPLIER INVOICE DATE
		if ($filters['clientInvoiceDate']['start']) {
			$listObj->setFilter('clientInvoiceDate', '>=', $filters['clientInvoiceDate']['start']);
		}

		if ($filters['clientInvoiceDate']['end']) {
			$listObj->setFilter('clientInvoiceDate', '<=', $filters['clientInvoiceDate']['end']);
		}

		if ($filters['supplierInvoiceDate']['start']) {
			$listObj->setFilter('supplierInvoiceDate', '>=', $filters['supplierInvoiceDate']['start']);
		}

		if ($filters['supplierInvoiceDate']['end']) {
			$listObj->setFilter('supplierInvoiceDate', '<=', $filters['supplierInvoiceDate']['end']);
		}

		// SUPPLIER INVOICE ID
		if ($filters['idSupplierInvoice']) {
			$listObj->setFilter('idSupplierInvoices', 'LIKE', "%|".$filters['idSupplierInvoice']."|%");
		}

		// SCORE FILTER
		if ($filters['score']) {
			$listObj->setFilter('score', '>=', $filters['score'] / 100);
		}

		$listObj = $this->entityList_inheritListingParams($listingParams, $listObj);
		$suggestionsArr = $listObj->exportRecords();

		$list = [];
		if ($suggestionsArr) {
			foreach($suggestionsArr as $suggestion) {
				$offerEnt = \Entity\Service::select($suggestion['id'])->chosenOffer;

				$suggestion['netCompany'] = $offerEnt->netCompanyWorkTotal;
				$suggestion['offerCurrency'] = $offerEnt->totalCurrency;

				if ($suggestion['scoreDetails']) {
					$suggestion['scoreDetails'] = unserialize($suggestion['scoreDetails']);
				}

				$suggestion['ticketsList'] = explodeClean('|', $suggestion['ticketsList']);


				$totalsSupplier = [];

				$supplierInvoices = [];
				$suggestion['idSupplierInvoiceRows'] = explodeClean('|', $suggestion['idSupplierInvoiceRows']);

				if ($suggestion['component']=='issue') {
					$suggestion['idServices'] = [ $suggestion['id'] ];
				}
				elseif ($suggestion['component']=='refund') {
					$suggestion['idServices'] = [ 'R'.$suggestion['id'] ];
				}
				elseif ($suggestion['component']=='both') {
					$suggestion['idServices'] = [ $suggestion['id'], 'R'.$suggestion['id'] ];
				}

				foreach ($suggestion['idSupplierInvoiceRows'] as $idRow) {
					$supplierRow = \Entity\SupplierInvoiceRow::select($idRow);
					$supplierInvoice = $supplierRow->supplierInvoice;
					$currency = $supplierInvoice->currency;

					if (!$totalsSupplier[$currency]) {
						$totalsSupplier[$currency] = 0;
					}
					$totalsSupplier[$currency] += $supplierRow->priceValue + $supplierRow->vatValue;

					if (!in_array($supplierInvoice->getId(), $supplierInvoices)) {
						$supplierInvoices[] = $supplierInvoice->getId();
					}
				}

				$suggestion['idSupplierInvoices'] = $supplierInvoices;

				$suggestion['totals'] = $totalsSupplier;
				$list[$suggestion['id']] = $suggestion;
			}
		}

		$this->recordsList = $list;
		$this->totalRecordsCount = $listObj->getRecordsCount();
	}

}
