<?php
namespace Modules\Documents\ImportedDocuments\BulkDistributeImportedDocs;

/**
 * This class adds an imported document associated to the list of service ids received
 * @author LauraMotoc
 *
 */
class ServiceModel extends \Engine\Mvc\ModelAbstract
{
	private $serviceIds = [];

	private $idImpDocument = 0;

	/**
	 * Sets the service ids
	 * @param array $ids
	 */
	public function __construct(array $ids)
	{
		$this->serviceIds = $ids;
	}

	/**
	 * Gets the id of the imported document
	 * @param Integer $idImpDocument
	 */
	public function getImportedDocument()
	{
		return $this->idImpDocument;
	}

	/**
	 * Sets the id of the imported document
	 * @param Integer $idImpDocument
	 */
	public function setImportedDocument($idImpDocument)
	{
		$this->idImpDocument = $idImpDocument;
	}

	public function process()
	{
		$this->check();

		$impDocEnt = \Entity\ImportedDocument::selectForUpdate($this->idImpDocument);

		$impDocObj = new \App\ImportedDocument\Cashing();
		$impDocObj->operation = 'update';
		$impDocObj->idDocumentSystem = $impDocEnt->idSystem;
		$impDocObj->externalSystemCode = $impDocEnt->externalSystem->code;
		$impDocObj->docNumber = $impDocEnt->docNumber;

		foreach ($this->serviceIds as $serviceId) {
			$serviceObj = new \App\ImportedDocument\Service();
			$serviceObj->idTina = $serviceId;
			$impDocObj->addTinaService($serviceObj);
		}

		$impDocEntUpd = \Entity\ImportedDocument::insert();
		$impDocEntUpd->document = $impDocObj;


		$impDocEntUpd->save();
	}

	/**
	 * Checks if the data has been set
	 * @throws \Exception
	 * @throws \App\MessagesException
	 */
	private function check()
	{
		$_lang = \App\Loader_Lang::getInstance()->getSection('Modules/Documents/ImportedDocuments/BulkDistributeImportedDocs');

		if (!\DB::isInsideTransaction()) {
			throw new \Exception('You must be inside a transaction when updating an imported document.');
		}

		$this->isAvailable(true);

		$msgs = new \App\MessagesCollector();

		$impDocEnt = \Entity\ImportedDocument::select($this->idImpDocument);
		if (!$impDocEnt->recordExists()) {
			$msgs->addError($_lang['index']['msgs']['invalidImpDocument']);
		}
		if ($impDocEnt->systemStatus != 'added') {
			$msgs->addError($_lang['index']['msgs']['incorrectSystemStatus']);
		}
		if ($impDocEnt->status != 'new' and $impDocEnt->status != 'partial') {
			$msgs->addError($_lang['index']['msgs']['incorrectStatus']);
		}

		if ($msgs->hasErrorOrWarning()) {
			throw new \App\MessagesException($msgs);
		}
	}

	/**
	 * Checks if the operation is available
	 * @throws \App\MessagesException - if any problem found
	 */
	public function isAvailable($selectForUpdate)
	{
		$_LANG = \App\Loader_Lang::getInstance()->getGlobal();
		$_lang = \App\Loader_Lang::getInstance()->getSection('Modules/Documents/ImportedDocuments/BulkDistributeImportedDocs');
		$msgs = new \App\MessagesCollector();

		if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Invoices/Cashings/Listing-insert')) {
			$msgs->addWarning($_LANG['noAccessToOption']);
		}

		$currencies = [];
		foreach ($this->serviceIds as $serviceId) {
			$serviceEntity = \Entity\Service::select($serviceId);

			if (!$serviceEntity->recordExists()) {
				$msgs->addError($_lang['index']['options']['reasons']['distributeImpDocsBulk']['invalidServiceId']);
			}

			// service cancelled
			if ($serviceEntity->statusOp == 'XX') {
				$msgs->addWarning($_lang['index']['options']['reasons']['distributeImpDocsBulk']['serviceCancelled']);
				break;
			}

			// different currencies
			if ($serviceEntity->chosenOffer->totalCurrency) {
				$currencies[$serviceEntity->chosenOffer->totalCurrency] = $serviceEntity->chosenOffer->totalCurrency;
			}
		}

		if (count($currencies) > 1) {
			$msgs->addWarning($_lang['index']['options']['reasons']['distributeImpDocsBulk']['differentCurrencies']);
		}

		if ($msgs->hasErrorOrWarning()) {
			throw new \App\MessagesException($msgs);
		}
	}
}