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

class AgencyOfficesInsert extends \Modules\Admin\ImportEntities\Model\ImportAbstract
{
	/**
	 *
	 * @var array
	 */
	protected $fields = [
		'name', 'city', 'country', 'address', 'iataCode',
		'telephone', 'email', 'zipCode'
	];

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

		$messagesFromImport = new \App\MessagesCollector();

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

			$officeLocation = [];
			if ($row['country']) {
				$matchCountry = new \App\EntityMatch\Country('intersect');
				$matchCountry->setName($row['country']);
				$matchCountry->search();
				if ($matchCountry->getResultsCount()==1) {
					$officeLocation['countryCode'] = $matchCountry->getFirstMatchId();
				}
			}
			if ($row['city']) {
				$matchCity = new \App\EntityMatch\City('intersect');
				$matchCity->setName($row['city']);
				if ($officeLocation['country']) {
					$matchCity->filterByCountryCode($officeLocation['country']);
				}
				$matchCity->search();
				if ($matchCity->getResultsCount()==1) {
					$cityDet = $matchCity->getFirstMatchDetails();
					$officeLocation['cityId'] = $cityDet['id'];
					$officeLocation['countryCode'] = $cityDet['countryCode'];
				}
			}

			// remarks
			$remarks = '';
			foreach ($row as $name=>$value) {
				if (preg_match('/remark:/', $name) and strlen($value)) {
					$remText = str_replace('remark:', '', $name);
					$remarks .= sprintf($remText, $value)."\n";
				}
			}

			try {
				\DB::startTransaction();

				$entityObj = \Entity\Office::insert();

				$entityObj->name = 					$row['name'];
				$entityObj->iataCode = 				array_filter(explode(',', $row['iataCode']));
				$entityObj->remarks = 				trim($remarks);
				if ($row['address']) {
					$entityObj->address =			$row['address'];
				}
				if ($row['zipCode']) {
					$entityObj->zipCode =			$row['zipCode'];
				}
				if ($row['telephone']) {
					$entityObj->telephone =			$row['telephone'];
				}
				if ($row['email']) {
					$entityObj->email =				$row['email'];
				}
				if ($officeLocation['countryCode']) {
					$entityObj->countryCode =		$officeLocation['countryCode'];
				}
				if ($officeLocation['cityId']) {
					$entityObj->cityId =			$officeLocation['cityId'];
				}

				$entityObj->save();

				\DB::commitTransaction();

				$idOffice = $entityObj->getId();

				$messagesFromImport->addSuccess(sprintf($_LANG['Admin']['ImportEntities']['index']['msgs']['offices']['officeSaveOk'], $row['name'], $idOffice));

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

	}

}

