<?php

namespace Modules\Admin\ImportEntities\Model\Import;

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

	/**
	 *
	 * @var array
	 */
	protected $fields = ['idCorporate', 'contactType', 'contactDatetime', 'duration',
		'topics', 'description', 'comments', 'idContactPerson', 'idUser'];

	/**
	 *
	 * @var Boolean
	 */
	protected $useDateFormat = TRUE;

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

		$messagesFromImport = new \App\MessagesCollector();

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

			// PREPARE FIELDS ---------------------------------------------------------------------
			$contactDatetime = '';
			if ($row['contactDatetime']) {
				$dateObj = \Engine\DateTime::createFromFormat($this->dateFormat.' H:i', $row['contactDatetime']);
				if ($dateObj->isValid() and !$dateObj->isEmpty()) {
					$contactDatetime = $dateObj->formatDateTimeIso();
				}
			}

			// ADD CONTACT TO DB ------------------------------------------------------------------
			try {

			    \DB::startTransaction();
				$corpContact = \Entity\CorporateContact::insert();

				// contact fields
				$corpContact->idCorporate =			$row['idCorporate'];
				$corpContact->contactType =			$row['contactType'];
				$corpContact->contactDatetime =		$contactDatetime;
				$corpContact->duration =			$row['duration'];
				$corpContact->topics =				$row['topics'];
				$corpContact->description =			$row['description'];
				$corpContact->comments =			$row['comments'];
				$corpContact->idContactPerson =		$row['idContactPerson'];
				$corpContact->idUser =				$row['idUser']?:CURRENT_ID_USER;

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

				$idCorpContact = $corpContact->getId();

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

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

		return $messagesFromImport;

	}


}
