<?php

namespace Modules\Admin\ImportEntities\Model\Import;

class SupplierProductsUpdate extends \Modules\Admin\ImportEntities\Model\ImportAbstract
{

	/**
	 *
	 * @var array
	 */
	protected $fields = ['idTina', 'supplierProductName', 'category', 'destinationCityName', 'chainCode',
		'address', 'telephone', 'email', 'website'];

	public function process()
	{
		$_LANG = \App\Loader_Lang::getInstance()->getGlobal();

		$messagesFromImport = new \App\MessagesCollector();

		// LOOP THROUGH EACH SUPPLIER PRODUCT /////////////////////////////////////////////////////
		foreach($this->fileData as $row) {

			// city matching
			$countryCode = null;
			$cityId = null;

			if ($row['destinationCityName']) {
				if ($row['destinationCityName'] == 'blank') {
					$countryCode = '';
					$cityId = 0;
				}
				else {
					$matchCity = new \App\EntityMatch\City('intersect');
					$matchCity->setName($row['destinationCityName']);
					$matchCity->search();
					if ($matchCity->getResultsCount()==1) {
						$cityDet = $matchCity->getFirstMatchDetails();
						$cityId = $cityDet['id'];
						$countryCode = $cityDet['countryCode'];
					}
				}
			}

			try {
				\DB::startTransaction();

				// create entity supplier product
				$supplierProduct = \Entity\SupplierProduct::update($row['idTina']);

				if ($row['category']) {
					$supplierProduct->category 	= 		($row['category']!='blank')?$row['category']:'';
				}
				if ($row['supplierProductName']) {
					$supplierProduct->productName = 	($row['supplierProductName']!='blank')?$row['supplierProductName']:'';
				}
				if ($row['chainCode']) {
					$supplierProduct->chainCode 	= 	($row['chainCode']!='blank')?$row['chainCode']:'';
				}

				if ($countryCode !== null) {
					$supplierProduct->destinationCountryCode = (string)$countryCode;
				}
				if ($cityId !== null) {
					$supplierProduct->destinationCityId 	 = (int)$cityId;
				}

				if ($row['address']) {
					$supplierProduct->address 	= ($row['address']!='blank')?$row['address']:'';
				}

				if ($row['telephone']) {
					$supplierProduct->telephone = ($row['telephone']!='blank')?$row['telephone']:'';
				}
				if ($row['email']) {
					$supplierProduct->email 	= ($row['email']!='blank')?$row['email']:'';
				}
				if ($row['website']) {
					$supplierProduct->website 	= ($row['website']!='blank')?$row['website']:'';
				}

				$supplierProduct->save();

				\DB::commitTransaction();

				$idSupplierProduct = $supplierProduct->getId();
				$messagesFromImport->addSuccess(sprintf($_LANG['Admin']['ImportEntities']['index']['msgs']['supplierProduct']['saveOk'], $row['supplierProductName'], $idSupplierProduct));

			} catch (\App\Entity\Exception $e) {
				\DB::rollbackTransaction();
				$messagesFromImport->addWarning(sprintf($_LANG['Admin']['ImportEntities']['index']['msgs']['supplierProduct']['saveError'], $row['supplierProductName']));
				$messagesFromImport->appendMessages($e->getMessagesCollector());
			}

		}

		return $messagesFromImport;
	}
}