<?php
namespace Modules\Documents\ImportedDocuments;

class Model extends \App\Mvc\Model_ListingAbstract
{
	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Model_ListingAbstract::list_execute()
	 */
	public function list_execute(\App\Mvc\View\Listing\Members\Params $listingParams)
	{
		$filters=$listingParams->getFilters();

		// get the documents list
		$listObj = new \App\EntityList\ImportedDocuments();

		$listObj->setColumns(['idExternalSystem', 'docCategory', 'docType', 'docNumber', 'docCategory', 'docDate',
			'docValue', 'docCurrency', 'addTime', 'idAddUser', 'status', 'idSupplier', 'idCustomer', 'idCorporate',
			'systemStatus', 'usedValue', 'idUser', 'idAgencyBankAccount', 'idIssueUser', 'issueTime',
		]);

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

		// document category
		if ($filters['docCategory']) {
			$listObj->setFilter('docCategory', '=', $filters['docCategory']);
		}

		// document type
		if ($filters['docType']) {
			$listObj->setFilter('docType', '=', $filters['docType']);
		}

		// add date
		if ($filters['addDate']['start']) {
			$listObj->setFilter('addTime', '>=', $filters['addDate']['start'].' 00:00:00');
		}
		if ($filters['addDate']['end']) {
			$listObj->setFilter('addTime', '<=', $filters['addDate']['end'].' 23:59:59');
		}

		// system
		if ($filters['system']) {
			$listObj->setFilter('idExternalSystem', '=', $filters['system']);
		}

		// system status
		if ($filters['systemStatus']) {
			$listObj->setFilter('systemStatus', '=', $filters['systemStatus']);
		}

		// status
		if (is_array($filters['status']) && $filters['status']) {
			$listObj->setFilter('status', 'IN', array_values($filters['status']));
		}

		// document date
		if ($filters['issued'] == 'issued') {
			$listObj->setFilter('issueTime', 'IS NOT NULL');
		}
		elseif ($filters['issued'] == 'notIssued') {
			$listObj->setFilter('issueTime', 'IS NULL');
		}

		// responsible
		if ($filters['responsible']['id']) {
			$listObj->setFilter('idUser', '=', $filters['responsible']['id']);
		}

		// doc number
		if ($filters['docNumber']) {
			$listObj->setFilter('docNumber', '=', $filters['docNumber']);
		}

		// corporate
		if ($filters['corporate']['id']) {
			$listObj->setFilter('idCorporate', 'IN', \Entity\Corporate::select($filters['corporate']['id'])->fullDuplicatedCorporatesGroup);
		}

		// customer
		if ($filters['customer']['id']) {
			$listObj->setFilter('idCustomer', 'IN', \Entity\Customer::select($filters['customer']['id'])->fullDuplicatedCustomersGroup);
		}

		// supplier
		if ($filters['supplier']['id']) {
			$listObj->setFilter('idSupplier', 'IN', \Entity\Supplier::select($filters['supplier']['id'])->fullDuplicatedSuppliersGroup);
		}

		// doc value
		if ($filters['docCurrency']) {
			$listObj->setFilter('docCurrency', '=', $filters['docCurrency']);
		}

		// idDocSystem
		if ($filters['idDocSystem']) {
			$listObj->setFilter('idSystem', '=', $filters['idDocSystem']);
		}

		// idTina
		if ($filters['idTina']) {
			$docIds = array_filter( array_map( function($elem){ return trim($elem);}, explode(',', $filters['idTina']) ) );
			$listObj->setFilter('id', 'IN', $docIds);
		}

		// idAgencyBankAccount
		if ($filters['idAgencyBankAccount']) {
		    if ($filters['idAgencyBankAccount']!='none') {
                $listObj->setFilter('idAgencyBankAccount', '=', $filters['idAgencyBankAccount']);
		    } else {
		        $listObj->setFilter('idAgencyBankAccount', '=', '0');
		    }
		}

		// comments
		if ($filters['comments']) {
			$listObj->setFilter('comments', 'LIKE', "%{$filters['comments']}%");
		}

		// remarks
		if ($filters['remarks']) {
			$listObj->setFilter('importedDocumentRemarks.value', '=', $filters['remarks']);
			$listObj->setGroupBy('importedDocument.id');
		}

		// doc refs
		if ($filters['docRefId'] and $filters['docRefType']) {
			// get full references list per entity
			$refIds = array_filter( array_map( function($elem){ return trim($elem);}, explode(',', $filters['docRefId']) ) );
			$refSearchList = [];
			switch ($filters['docRefType']) {
				case 'service': case 'importedService': case 'clientInvoice': case 'supplierInvoice':
					foreach ($refIds as $refId) {
						$refSearchList[$filters['docRefType'].':'.$refId] = true;
					}
				break;
				case 'importedOrder':
					foreach ($refIds as $refId) {
						$impOrderEnt = \Entity\ImportedOrder::select($refId);
						foreach($impOrderEnt->importedServicesList as $impServDet) {
							$refSearchList['importedService:'.$impServDet['id']] = true;
						}
					}
				break;
			}
			// include in SQL
			if ($refSearchList) {
				$filterSQL = implode( ' OR ', array_fill(0, count($refSearchList), 'docReferences LIKE ?') );
				$bindVars = array_map( function($elem) { return '%|'.$elem.'|%';}, array_keys($refSearchList) );
				$listObj->setCustomFilter( $filterSQL, $bindVars);
			}
		}

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

		// these must be called in this specific order
		$this->recordsList = $listObj->exportRecords();
		$this->totalRecordsCount = 	$listObj->getRecordsCount();
	}

	/**
	 * Extract importedDocuments files
	 * @param String $idDocument
	 * @return Array
	 */
	public function getImportedDocumentFiles($idDocument)
	{
		// extract files from \Entity\ImportedDocument
		$filesList = \Entity\ImportedDocument::select($idDocument)->files;

		// extract global CFG
		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();

		$listFiles = [];

		foreach ($filesList as $fileInfo) {

			// check which files are valid
			$fullPathFile = APP_REAL_PATH.$CFG['paths']['files'].$fileInfo['file'];

			$listFiles[] = [
				'fullPathFile' => 	$fullPathFile,
				'file' => 			$fileInfo['file'],
				'name' => 			$fileInfo['name'],
				'fileExists' => 	\Engine\File::check($fullPathFile),
				'time' =>			$fileInfo['time'],
			];
		}

		// sort fileslist by date
		//uasort($listFiles, Array($this, '_sortByDate'));

		return $listFiles;
	}

	/**
	 * Sort ASC
	 * @param String $a
	 * @param String $b
	 */
	private function _sortByDate($a, $b)
	{
		return $a['time'] - $b['time'];
	}

}