<?php

namespace Modules\Admin\ImportEntities\Model\Import;

class PassengersInsert extends \Modules\Admin\ImportEntities\Model\ImportAbstract
{
	/**
	 * The fields that can be imported from csv for this entity
	 * @var array
	 */
	protected $fields = ['firstNameStandard', 'middleNameStandard', 'lastNameStandard',
		'firstNameLocal', 'middleNameLocal', 'lastNameLocal', 'PNC', 'passengerType',
		'passengerTitle', 'department', 'birthday', 'ID_series', 'ID_number',
		'ID_releaseDate' , 'ID_expireDate', 'address', 'zipCode', 'telephone', 'email',
		'mobile', 'originCity', 'corporation',
	];

	/**
	 * This entity uses the date format
	 * @var Boolean
	 */
	protected $useDateFormat = TRUE;


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

		$messagesFromImport = new \App\MessagesCollector();

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

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

			// city matching
			$countryCode = '';
			$cityId = 0;

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

			// match company
			$idCorporate = '';

			if ($row['corporation']) {
				$matchCorp = new \App\EntityMatch\Corporate('intersect');
				$matchCorp->setAlias($row['corporation']);
				$matchCorp->setCompany($row['corporation']);
				$matchCorp->search();

				if ($matchCorp->getFirstMatchId()) {
					$idCorporate = $matchCorp->getFirstMatchId();
				}
			}


			// add customers
			try {
				\DB::startTransaction();
				$customer = \Entity\Customer::insert();
				$customerCfg = $customer->getCFG();

				// customers fields
				if ($CFG['useAlternativeNames']['customers']) {
					$customer->lastNameStandard = 	($customerCfg['lastName']['validation']['case'] == 'upper')?$this->safeUppercaseHtmlCleanedText((string)$row['lastNameStandard']):$row['lastNameStandard'];;
					$customer->middleNameStandard = ($customerCfg['middleName']['validation']['case'] == 'upper')?$this->safeUppercaseHtmlCleanedText((string)$row['middleNameStandard']):$row['middleNameStandard'];
					$customer->firstNameStandard = 	($customerCfg['firstName']['validation']['case'] == 'upper')?$this->safeUppercaseHtmlCleanedText((string)$row['firstNameStandard']):$row['firstNameStandard'];

					$customer->lastNameLocal = 		($customerCfg['lastName']['validation']['case'] == 'upper')?$this->safeUppercaseHtmlCleanedText((string)$row['lastNameLocal']):$row['lastNameLocal'];;
					$customer->middleNameLocal = 	($customerCfg['middleName']['validation']['case'] == 'upper')?$this->safeUppercaseHtmlCleanedText((string)$row['middleNameLocal']):$row['middleNameLocal'];
					$customer->firstNameLocal = 	($customerCfg['firstName']['validation']['case'] == 'upper')?$this->safeUppercaseHtmlCleanedText((string)$row['firstNameLocal']):$row['firstNameLocal'];
				} else {
					$customer->lastNameStandard = 	($customerCfg['lastName']['validation']['case'] == 'upper')?$this->safeUppercaseHtmlCleanedText((string)$row['lastNameStandard']):$row['lastNameStandard'];;
					$customer->lastNameLocal 	=	'';
					$customer->middleNameStandard = ($customerCfg['middleName']['validation']['case'] == 'upper')?$this->safeUppercaseHtmlCleanedText((string)$row['middleNameStandard']):$row['middleNameStandard'];
					$customer->middleNameLocal 	= 	'';
					$customer->firstNameStandard = 	($customerCfg['firstName']['validation']['case'] == 'upper')?$this->safeUppercaseHtmlCleanedText((string)$row['firstNameStandard']):$row['firstNameStandard'];
					$customer->firstNameLocal = 	'';
				}

				$customer->PNC = 				(String)$row['PNC'];
				$customer->title = 				$row['passengerTitle'];
				$customer->type = 				$row['passengerType'];

				if ($row['birthday']) {
					$birthday = \Engine\DateTime::createFromFormat($this->dateFormat, $row['birthday']);
					if (!$birthday->isValid()) {
						$messagesFromImport->addWarning(sprintf($_LANG['Admin']['ImportEntities']['index']['msgs']['customers']['invalidBirthday'], $row['birthday']));
					}
					else {
						$customer->birthday = $birthday->formatDateIso();
					}
				}

				$customer->ID_series =			$row['ID_series'];
				$customer->ID_number =			$row['ID_number'];

				if ($row['ID_releaseDate']) {
					$ID_releaseDate = \Engine\DateTime::createFromFormat($this->dateFormat, $row['ID_releaseDate']);
					if (!$ID_releaseDate->isValid()) {
						$messagesFromImport->addWarning(sprintf($_LANG['Admin']['ImportEntities']['index']['msgs']['customers']['invalidReleaseDate'], $row['ID_releaseDate']));
					}
					else {
						$customer->ID_releaseDate = $ID_releaseDate->formatDateIso();
					}
				}

				if ($row['ID_expireDate']) {
					$ID_expireDate = \Engine\DateTime::createFromFormat($this->dateFormat, $row['ID_expireDate']);
					if (!$ID_expireDate->isValid()) {
						$messagesFromImport->addWarning(sprintf($_LANG['Admin']['ImportEntities']['index']['msgs']['customers']['invalidExpireDate'], $row['ID_expireDate']));
					}
					else {
						$customer->ID_expireDate = $ID_expireDate->formatDateIso();
					}
				}


				$customer->address = 			$row['address'];
				$customer->email = 				($row['email'])?$row['email']:'';
				$customer->telephone = 			($row['telephone'])?$row['telephone']:'';
				$customer->telephoneMobile = 	($row['mobile'])?$row['mobile']:'';
				$customer->countryCode = 		$countryCode;
				$customer->cityId = 			$cityId;
				$customer->idCorporate = 		$idCorporate;

				if ($row['department'] && $idCorporate) {
					$customer->department = $row['department'];
				}

				$customer->remarks = 			trim($remarks);

				$customer->save();

				\DB::commitTransaction();

				$idCustomer = $customer->getId();

				$messagesFromImport->addSuccess(sprintf($_LANG['Admin']['ImportEntities']['index']['msgs']['customers']['saveOk'], $idCustomer));

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

		}

		return $messagesFromImport;
	}
}