<?php

namespace Modules\Partners\SupplierProducts;

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 supplier products list
		$listObj = new \App\EntityList\SupplierProducts();
		$listObj->setColumns(['suppPr.id', 'serviceCode', 'category', 'productName', 'destinationCountryCode', 'destinationCityId', 'idAddUser', 'addTime']);
		if ($filters['text']) {
			$listObj->setCustomFilter('productName LIKE ? OR comments LIKE ?', ["%{$filters['text']}%", "%{$filters['text']}%"]);
		}
		if ($filters['supplier']['id']) {
			$listObj->setFilter('assoc.idSupplier', '=', $filters['supplier']['id']);
		}
		if ($filters['destination']['id']) {
			$location = explode("|", $filters['destination']['id']);
			$listObj->setFilter('suppPr.destinationCountryCode', '=', $location[0]);
			if ($location[1]) {
				$listObj->setFilter('suppPr.destinationCityId', '=', $location[1]);
			}
		}
		if ($filters['serviceCode']) {
			$listObj->setFilter('suppPr.serviceCode', '=', $filters['serviceCode']);
		}

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

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

		// attach service name and category name
		// attach destination country and city['index']['listCols']['hasDuplicateCorporate']
		$recordsList = [];
		foreach($tempRecordsList as $row) {
			$categories = \App\Config\Services_GeneralAttributes::getInstance()->getServiceCategory($row['serviceCode']);

			$row['serviceName'] = \App\Config\Services_Basic::getInstance()->getServiceName($row['serviceCode']);
			$row['categoryName']= $categories['list'][$row['category']];
			$row['destinationCountryName'] = \Entity\Country::select($row['destinationCountryCode'])->name;
			$row['destinationCityName'] = \Entity\City::select($row['destinationCityId'])->name;

			$supplierProductObj = \Entity\SupplierProduct::select($row['id']);
			$row['idRealSupplierProduct'] = $supplierProductObj->idRealSupplierProduct;
			$row['duplicatedSupplierProducts'] = count($supplierProductObj->duplicatedSupplierProducts);

			$recordsList[] = $row;
		}

		$this->recordsList = $recordsList;
	}

}
