<?php
namespace Modules\Admin\ImportEntities\Model\Import;

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

	/**
	 * The fields that can be imported from csv for this entity
	 * @var array
	 */
	protected $fields = ['idTina', 'cityNameStandard', 'cityNameLocal',
		'regionStandard', 'regionLocal', 'districtStandard', 'districtLocal', 'code3',
		'codeLocal', 'areaCode'];

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

		$messagesFromImport = new \App\MessagesCollector();

		foreach ($this->fileData as $row) {

			try {
				\DB::startTransaction();
				$city = \Entity\City::update($row['idTina']);

				if ($row['cityNameStandard']) {
					$city->nameStandard = ($row['cityNameStandard'] != 'blank') ? $row['cityNameStandard'] : '';
				}

				if ($row['cityNameLocal']) {
					$city->nameLocal = ($row['cityNameLocal'] != 'blank') ? $row['cityNameLocal'] : '';
				}

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

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

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

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

				if ($row['code3']) {
					$city->code3 = ($row['code3'] != 'blank') ? $this->safeUppercaseHtmlCleanedText((string)$row['code3']) : '';
				}

				if ($row['codeLocal']) {
					$city->codeLocal = ($row['codeLocal'] != 'blank') ? $this->safeUppercaseHtmlCleanedText((string)$row['codeLocal']) : '';
				}

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

				$city->save();
				\DB::commitTransaction();

				$messagesFromImport->addSuccess($_LANG['Admin']['ImportEntities']['index']['msgs']['cities']['saveOk']);

			}
			catch (\App\Entity\Exception $e) {
				\DB::rollbackTransaction();
				$messagesFromImport->appendMessages($e->getMessagesCollector());
			}
		}

		return $messagesFromImport;
	}

}