<?php

namespace Modules\Admin\ImportEntities\Model\Import;

class ImportedServicesCancel extends \Modules\Admin\ImportEntities\Model\ImportAbstract
{
	/**
	 *
	 * @var array
	 */
	protected $fields = ['serviceId', 'cancelDate'];

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

    /**
     *
     * {@inheritDoc}
     * @see \Modules\Admin\ImportEntities\Model\ImportAbstract::process()
     * @return \App\MessagesCollector
     */
	public function process()
	{
		$CFG  = \Engine\Loader_Cfg::getInstance()->getGlobal();
		$_LANG = \App\Loader_Lang::getInstance()->getGlobal();

		$messagesFromImport = new \App\MessagesCollector();

		// LOOP THROUGH EACH IMPORTED SERVICE ////////////////////////////////////////////////////////////
		foreach($this->fileData as $row) {
            try {
                \DB::startTransaction();

                $importedOrderObj = new \App\ImportedOrder\Order();
                $importedOrderObj->externalSystemCode = $CFG['Admin']['ImportEntities']['ImportedServicesInsert']['system']['default'];

                // IMPORTED SERVICE OBJECT ////////////////////////////////////////////////////////////////
                $importedServiceObj = new \App\ImportedOrder\Service();
                $importedServiceObj->idSystem = $row['serviceId'];
                $importedServiceObj->operation = 'cancel';

                // CANCEL DETAILS
                $cancelDetails = new \App\ImportedOrder\CancelDetails();
                $cancelDetails->date = \Engine\DateTime::createFromFormat($this->dateFormat, $row['cancelDate'])->formatDateIso();
                $importedServiceObj->cancelDetails = $cancelDetails;

                // ADD THE SERVICE TO ORDER
                $importedOrderObj->addService($importedServiceObj);

                $importedOrderEnt = \Entity\ImportedOrder::insert();
                $importedOrderEnt->order = $importedOrderObj;

                $importedOrderEnt->save();

                \DB::commitTransaction();
                $messagesFromImport->addSuccess(sprintf($_LANG['Admin']['ImportEntities']['index']['msgs']['services']['saveOk'], $importedOrderEnt->getId()));

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

        }

		return $messagesFromImport;
	}
}
