<?php

namespace Modules\Partners\Corporates;

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 corporates list
		$listObj = new \App\EntityList\Corporates();
		$listObj->setColumns(['alias', 'alias AS name', 'corp.status', 'corp.locked', 'corp.type', 'corp.idRealCorporate',
				'corp.telephone', 'corp.fax', 'corp.email',
				'corp.idAccountManager', 'corp.companyPrefix', 'corp.company', 'corp.companySuffix', 'corp.company2Prefix',
				'corp.company2', 'corp.company2Suffix',
				'corp.vatCertificateNumber', 'corp.registryAddress', 'corp.vatRegistered', 'corp.fiscalCode', 'corp.regNo',
				'corp.idTrust', 'corp.idAddUser', 'corp.addTime', 'corp.idRealCorporate', 'corp.idSegment', 'collection.profileCode'=>'collectionProfileCode'
		]);
		// company name search
		if (strlen((string)$filters['nameText'])) {
			switch ($filters['nameMode']) {
				case 'starts':
					$searchText = $filters['nameText'] . '%';
					break;
				case 'contains':
					$searchText = '%' . $filters['nameText'] . '%';
					break;
				default: // exact
					$searchText = $filters['nameText'];
			}
			$listObj->setCustomFilter('corp.alias LIKE ? OR corp.company LIKE ?', [ $searchText, $searchText ] );
		}
		if ($filters['idCorporate']) {
			$listObj->setFilter('corp.id', '=', $filters['idCorporate']);
		}
		if ($filters['idTrust']['id']??null) {
			$listObj->setFilter('corp.idTrust', '=', $filters['idTrust']['id']);
		}
		if ($filters['type']) {
			$listObj->setFilter('corp.type', '=', $filters['type']);
		}
		if ($filters['idSegment']) {
			$listObj->setFilter('corp.idSegment', '=', $filters['idSegment']);
		}
		if ($filters['fiscalCode']) {
			$listObj->setFilter('corp.fiscalCode', 'LIKE', '%' . $filters['fiscalCode'] . '%');
		}
		if ($filters['regNo']) {
			$listObj->setFilter('corp.regNo', '=', $filters['regNo']);
		}
		if ($filters['accountingNumber']) {
			$listObj->setFilter('corp.accountingNumber', '=', $filters['accountingNumber']);
		}
		if ($filters['vatCertificateNumber']) {
			$listObj->setFilter('corp.vatCertificateNumber', '=', $filters['vatCertificateNumber']);
		}
		if ($filters['vatRegistered']=='y') {
			$listObj->setFilter('corp.vatRegistered', '=', 1);
		} elseif ($filters['vatRegistered']=='n') {
			$listObj->setFilter('corp.vatRegistered', '=', 0);
		}

		if ($filters['idAddUser']['id']??null) {
			$listObj->setColumn('addUser.idOffice');
			list($idOffice, $idUser) = explode("|", $filters['idAddUser']['id']);
			if ($idUser) {
				$listObj->setFilter('corp.idAddUser', '=', $idUser);
			}
			elseif ($idOffice) {
				$listObj->setFilter('addUser.idOffice', '=', $idOffice);
			}

		}
		if ($filters['idAccountManager']['id']??null) {
			$listObj->setFilter('corp.idAccountManager', '=', $filters['idAccountManager']['id']);
		}
		if ($filters['idCollectionResponsible']['id']??null) {
			$listObj->setFilter('corp.idCollectionResponsible', '=', $filters['idCollectionResponsible']['id']);
		}
		if ($filters['idInvoiceResponsible']['id']??null) {
			$listObj->setFilter('corp.idInvoiceResponsible', '=', $filters['idInvoiceResponsible']['id']);
		}
		if ($filters['duplicateStatus'] == 'duplicated') {
			$listObj->setFilter('corp.idRealCorporate', '!=', '0');
		}
		if ($filters['duplicateStatus'] == 'notDuplicated') {
			$listObj->setFilter('corp.idRealCorporate', '=', '0');
		}
		if ($filters['activityDomain']['id']??null) {
			list($idDomainCategory, $idDomain)= explode("|", $filters['activityDomain']['id']);
			if ($idDomain) {
				$listObj->setFilter('corp.idDomain', '=', $idDomain);
			}
			if ($idDomainCategory) {
				$listObj->setFilter('corp.idDomainCategory', '=', $idDomainCategory);
			}
		}
		if ($filters['status']) {
			$listObj->setFilter('corp.status', '=', $filters['status']);
		}
		if ($filters['blockStatus'] == 'notBlocked') {
			$listObj->setFilter('corp.locked', '=', '0');
		}
		if ($filters['blockStatus'] == 'blocked') {
			$listObj->setFilter('corp.locked', '=', '1');
		}

		if ($filters['remarks']) {
			$listObj->setColumn('remarks.idCorporate');
			$listObj->setFilter('remarks.value', 'LIKE', $filters['remarks']);
		}

		if($filters['creditLimit'] == 'withCreditLimit'){
			$listObj->setFilter('creditLimits.idCorporate', 'IS NOT NULL');
		}

		if($filters['creditLimit'] == 'withoutCreditLimit'){
			$listObj->setFilter('creditLimits.idCorporate', 'IS NULL');
		}

		if ($filters['idGdsProfileTemplate']) {
			$listObj->setFilter('corp.idGdsProfileTemplate', '=', $filters['idGdsProfileTemplate']);
		}

		// filter by corporate collection profile
		if ($filters['collectionProfileCode']) {
			switch ($filters['collectionProfileCode']) {
				case 'ALL':
					$listObj->setFilter('collection.profileCode', 'IS NOT NULL');
				break;
				case 'NONE':
					$listObj->setFilter('collection.profileCode', 'IS NULL');
				break;
				default:
					$listObj->setFilter('collection.profileCode', '=', $filters['collectionProfileCode']);
			}
		}

		// filter by autoCompensate profile
		if ($filters['autoCompensateType']) {

			if ($filters['autoCompensateType']=='noProfile') {
				global $DBTCorporatesPreferences;
				$listObj->setCustomFilter("corp.id NOT IN (SELECT `idCorporate` FROM `{$DBTCorporatesPreferences}` WHERE var='autoCompensateType')");
			}
			elseif ($filters['autoCompensateType']=='anyProfile') {
				$listObj->setFilter('prefs.var', '=', 'autoCompensateType');
				$listObj->setFilter('prefs.value', 'IS NOT NULL');
			}
			else {
				$listObj->setFilter('prefs.var', '=', 'autoCompensateType');
				$listObj->setFilter('prefs.value', '=', $filters['autoCompensateType']);
			}
		}


		// groups filters
		if ($filters['idGroupElements']) {
			$idGroupElementsFilters = [];
			foreach($filters['idGroupElements'] as $groupCode=>$elementCode) {
				if ($elementCode) {
					$idGroupElementsFilters[$groupCode] = [$elementCode];
				}
			}
			// if at least one group selected
			if ($idGroupElementsFilters) {
				// gets the corporates associated to the combination of these groups elements
				$corporateGroupsHelper = new \App\Utils\PartnerGroups\Corporate();
				$corporateGroupsHelper->setGroupElementsStructured($idGroupElementsFilters);
				$idAssociatedCorporates = $corporateGroupsHelper->getPartnerIdsList();
				// filter by corporate ids
				if ($idAssociatedCorporates) {
					$listObj->setFilter('corp.id', 'IN', $idAssociatedCorporates);
				} else { // if $idAssociatedCorporates is empty, the list must be empty
					$listObj->setCustomFilter('0');
				}
			}
		}

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

		// add extra fields
		$recordsList = $listObj->exportRecords();
		$collectionCfg = \App\Config\CorporateCollectionProfiles::getInstance();
		foreach ($recordsList as $idx=>$corpDet) {
			if ($corpDet['collectionProfileCode']) {
				$recordsList[$idx]['collectionProfileName'] = $collectionCfg->get($corpDet['collectionProfileCode'])['name'];
			}
		}

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

	}
}
