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

class Controller extends \App\Mvc\Controller\Form\PopupAbstract
{

	protected function actionIndex($R)
	{
		// collects messages
		$msgs = \App\MessagesCollector::create();

		$modelOutput = null;
		// SAVE THE FORM DATA /////////////////////////////////////////////////////////////////////
		if ($R[$this->formSubmitButtonName]) {

			if (!$R['bulkOperation']) {
				$msgs->addError($this->lang['index']['msgs']['missingBulkOperation']);
			}

			if ($R['bulkOperation'] == 'existingImpDoc') {
				if (!$R['idImportedDocSelect']) {
					$msgs->addError($this->lang['index']['msgs']['missingDocumentId']);
				}

				if ($R['idImportedDocSelect'] == 'manual' and !$R['idImportedDocManual']) {
					$msgs->addError($this->lang['index']['msgs']['missingDocumentId']);
				}

				if (!$msgs->hasErrorOrWarning()) {
					try {
						$idImpDoc = ($R['idImportedDocSelect'] == 'manual')?$R['idImportedDocManual']:$R['idImportedDocSelect'];

						\DB::startTransaction();
						if ($R['entityType'] == 'clientInvoice') {
							$model = new ClientInvoiceModel($R['ids']);
						}
						elseif ($R['entityType'] == 'supplierInvoice') {
							$model = new SupplierInvoiceModel($R['ids']);
						}
						elseif ($R['entityType'] == 'service') {
							$model = new ServiceModel($R['ids']);
						}
						elseif ($R['entityType'] == 'importedService') {
							$model = new ImportedServiceModel($R['ids']);
						}
						$model->setImportedDocument($idImpDoc);
						$model->process();
						\DB::commitTransaction();

						if ($R['entityType'] == 'clientInvoice') {
							$listingSelection = new \App\Mvc\View\Listing\Members\Selection('Modules/Invoices/InvoicesList');
						}
						elseif ($R['entityType'] == 'supplierInvoice') {
							$listingSelection = new \App\Mvc\View\Listing\Members\Selection('Modules/Invoices/SupplierInvoices');
						}
						elseif ($R['entityType'] == 'service') {
							$listingSelection = new \App\Mvc\View\Listing\Members\Selection('Modules/Orders/ServicesList');
						}
						elseif ($R['entityType'] == 'importedService') {
							$listingSelection = new \App\Mvc\View\Listing\Members\Selection('Modules/Orders/ImportedOrders/ServicesList');
						}
						$listingSelection->clear();

						$msgs->addSuccess($this->lang['index']['form']['success']);
						$modelOutput = true;

						if ($R['processImpDocument']) {
							$response = new \Engine\Mvc\Response\HtmlRedirectWithPost(\Engine\Mvc\Dispatcher::getInstance()->getAppUrl("Modules/Documents/ImportedDocuments/ProcessDocument", "index", ['id' => $model->getImportedDocument()]));
							return $response;
						}

					} catch (\App\MessagesException $e) {
						\DB::rollbackTransaction();
						$msgs->appendMessages($e->getMessagesCollector());
						$modelOutput = false;
					} catch (\App\Entity\Exception $e) {
						\DB::rollbackTransaction();
						$msgs->appendMessages($e->getMessagesCollector());
						$modelOutput = false;
					}
				}
			}
			elseif ($R['bulkOperation'] == 'newImpDoc') {
				$postData = [];

				$postData['entityIds'] = $R['ids'];

				if ($R['entityType'] == 'clientInvoice') {
					$postData['entity'] = 'invoice';
					$postData['docCategory'] = 'cashing';

					$invoiceEnt = \Entity\Invoice::select(reset($R['ids']));
					if ($invoiceEnt->idCorporate) {
						$postData['clientType'] = 'legalEnt';
						$postData['corporate']['id'] = $invoiceEnt->idCorporate;
					}
					elseif ($invoiceEnt->idCustomer) {
						$postData['clientType'] = 'individual';
						$postData['customer']['id'] = $invoiceEnt->idCustomer;
					}
				}
				elseif ($R['entityType'] == 'supplierInvoice') {
					$postData['entity'] = 'supplierInvoice';
					$postData['docCategory'] = 'payment';

					$invoiceEnt = \Entity\SupplierInvoice::select(reset($R['ids']));
					$postData['supplier']['id'] = $invoiceEnt->idSupplier;
				}
				elseif ($R['entityType'] == 'service') {
					$postData['entity'] = 'service';
					$postData['docCategory'] = 'cashing';

					$serviceEnt = \Entity\Service::select(reset($R['ids']));
					if ($serviceEnt->order->idCorporateOwner) {
						$postData['clientType'] = 'legalEnt';
						$postData['corporate']['id'] = $serviceEnt->order->idCorporateOwner;
					}
					elseif ($serviceEnt->order->idCustomerOwner) {
						$postData['clientType'] = 'individual';
						$postData['customer']['id'] = $serviceEnt->order->idCustomerOwner;
					}
				}
				elseif ($R['entityType'] == 'importedService') {
					$postData['entity'] = 'importedService';
					$postData['docCategory'] = 'cashing';

					$impServiceEnt = \Entity\ImportedService::select(reset($R['ids']));
					if ($impServiceEnt->importedOrder->idCorporateOwner) {
						$postData['clientType'] = 'legalEnt';
						$postData['corporate']['id'] = $impServiceEnt->importedOrder->idCorporateOwner;
					}
					elseif ($impServiceEnt->importedOrder->idCustomerOwner) {
						$postData['clientType'] = 'individual';
						$postData['customer']['id'] = $impServiceEnt->importedOrder->idCustomerOwner;
					}
				}

				if ($R['processImpDocument']) {
					$postData['processImpDocument'] = $R['processImpDocument'];
				}

				$postData['docDate'] = TODAY_ISO;

				$postData['value']['value'] = 0;

				// We can add the values for all entities because the currencies are checked beforehand in the model
				foreach ($R['ids'] as $idEntity) {
					if ($R['entityType'] == 'clientInvoice') {
						$invoiceEnt = \Entity\Invoice::select($idEntity);

						$postData['value']['value'] += $invoiceEnt->printTotal - $invoiceEnt->cashedTotal;

						if (!$postData['value']['currency']) {
							$postData['value']['currency'] = $invoiceEnt->currency;
						}
					}
					elseif ($R['entityType'] == 'supplierInvoice') {
						$invoiceEnt = \Entity\SupplierInvoice::select($idEntity);

						$postData['value']['value'] += $invoiceEnt->totalValue - $invoiceEnt->payedValue;

						if (!$postData['value']['currency']) {
							$postData['value']['currency'] = $invoiceEnt->currency;
						}
					}
					elseif ($R['entityType'] == 'service') {
						$serviceEnt = \Entity\Service::select($idEntity);

						$postData['value']['value'] += $serviceEnt->chosenOffer->offerWorkTotal;

						if (!$postData['value']['currency']) {
							$postData['value']['currency'] = $serviceEnt->chosenOffer->totalCurrency;
						}
					}
					elseif ($R['entityType'] == 'importedService') {
						$impServiceEnt = \Entity\ImportedService::select($idEntity);

						$postData['value']['value'] += $impServiceEnt->offerTotalValue;

						if (!$postData['value']['currency']) {
							$postData['value']['currency'] = $impServiceEnt->offerTotalCurrency;
						}
					}
				}

				if (!$postData['value']['currency']) {
					$postData['value']['currency'] = \App\Config\Currencies::getInstance()->getDefaultCurrency();
				}

				if ($R['entityType'] == 'clientInvoice') {
					$listingSelection = new \App\Mvc\View\Listing\Members\Selection('Modules/Invoices/InvoicesList');
				}
				elseif ($R['entityType'] == 'supplierInvoice') {
					$listingSelection = new \App\Mvc\View\Listing\Members\Selection('Modules/Invoices/SupplierInvoices');
				}
				elseif ($R['entityType'] == 'service') {
					$listingSelection = new \App\Mvc\View\Listing\Members\Selection('Modules/Orders/ServicesList');
				}
				elseif ($R['entityType'] == 'importedService') {
					$listingSelection = new \App\Mvc\View\Listing\Members\Selection('Modules/Orders/ImportedOrders/ServicesList');
				}
				$listingSelection->clear();

				$response = new \Engine\Mvc\Response\HtmlRedirectWithPost(\Engine\Mvc\Dispatcher::getInstance()->getAppUrl("Modules/Documents/ImportedDocuments", "insert"));
				$response->setPostData($postData);
				return $response;
			}
		}

		// instantiate the view
		$view = new View_Index($this);

		// get form data for this operation
		$formData = $R;

		// send data to the view
		$view->addInput('formData', $formData);
		$view->getMessagesCollector()->appendMessages($msgs);
		$view->addInput('formSubmitButtonName', $this->formSubmitButtonName);
		if ($modelOutput) {
			$view->setClosePopup(true);
		}

		// do some more stuff (if needed)
		$this->preRenderOperations($view, $formData);

		// render the view
		return new \Engine\Mvc\Response\Html($view->render());

	}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::getDefaultFormData()
	 */
	protected function getDefaultFormData($R){}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::processFormData()
	 */
	protected function processFormData(Array $R, \App\MessagesCollector $msgs){}

	/**
	 * Do some more stuff on the current controller/view right before the render is called.
	 * @param \App\Mvc\View_Window_FormAbstract $view
	 * @param array $formData
	 */
	protected function preRenderOperations(\App\Mvc\ViewAbstract $view, array $formData)
	{
		$formData = $view->getInput('formData');

		if ($formData['entityType'] == 'clientInvoice') {
			$this->preRenderOperationsClientInvoice($view, $formData);
		}
		elseif ($formData['entityType'] == 'supplierInvoice') {
			$this->preRenderOperationsSupplierInvoice($view, $formData);
		}
		elseif ($formData['entityType'] == 'service') {
			$this->preRenderOperationsService($view, $formData);
		}
		elseif ($formData['entityType'] == 'importedService') {
			$this->preRenderOperationsImportedService($view, $formData);
		}
	}

	/**
	 * Do some more stuff for client invoices on the current controller/view right before the render is called.
	 * @param \App\Mvc\View_Window_FormAbstract $view
	 * @param array $formData
	 */
	protected function preRenderOperationsClientInvoice(\App\Mvc\ViewAbstract $view, array $formData)
	{
		$formData = $view->getInput('formData');

		$idCorporate = 0;
		$idCustomer = 0;
		$invoiceEnt = \Entity\Invoice::select(reset($formData['ids']));
		if ($invoiceEnt->idCorporate) {
			$idCorporate = $invoiceEnt->idCorporate;
			$formData['idCorporate'] = $invoiceEnt->idCorporate;
		}
		elseif ($invoiceEnt->idCustomer) {
			$idCustomer = $invoiceEnt->idCustomer;
			$formData['idCustomer'] = $invoiceEnt->idCustomer;
		}

		$impDocsObj = new \App\EntityList\ImportedDocuments();

		$impDocsObj->setFilter('status', '=', 'new');

		// corporate
		if ($idCorporate) {
			$impDocsObj->setFilter('idCorporate', '=', $idCorporate);
		}
		// customer
		if ($idCustomer) {
			$impDocsObj->setFilter('idCustomer', '=', $idCustomer);
		}

		$impDocsListEx = $impDocsObj->exportRecords();

		$formData['idImportedDocSelectList'] = [];
		foreach($impDocsListEx as $record) {
			$formData['idImportedDocSelectList'][] = $record['id'];
		}

		$formData['invValue'] = 0;
		foreach ($formData['ids'] as $idInvoice) {
			$invoiceEnt = \Entity\Invoice::select($idInvoice);

			$formData['invValue'] += $invoiceEnt->printTotal - $invoiceEnt->cashedTotal;

			if (!$formData['invCurrency']) {
				$formData['invCurrency'] = $invoiceEnt->currency;
			}
		}
		$view->addInput('formData', $formData);
	}

	/**
	 * Do some more stuff for supplier invoices on the current controller/view right before the render is called.
	 * @param \App\Mvc\View_Window_FormAbstract $view
	 * @param array $formData
	 */
	protected function preRenderOperationsSupplierInvoice(\App\Mvc\ViewAbstract $view, array $formData)
	{
		$formData = $view->getInput('formData');
		$idSupplier = 0;

		$invoiceEntity = \Entity\SupplierInvoice::select(reset($formData['ids']));
		if ($invoiceEntity->idSupplier) {
			$idSupplier = $invoiceEntity->idSupplier;
			$formData['idSupplier'] = $invoiceEntity->idSupplier;
		}

		$impDocsObj = new \App\EntityList\ImportedDocuments();

		$impDocsObj->setFilter('status', '=', 'new');

		if ($formData['idSupplier']) {
			$impDocsObj->setFilter('idSupplier', '=', $idSupplier);
		}

		$impDocsListEx = $impDocsObj->exportRecords();

		$formData['idImportedDocSelectList'] = [];
		foreach($impDocsListEx as $record) {
			$formData['idImportedDocSelectList'][] = $record['id'];
		}

		$formData['invValue'] = 0;
		foreach ($formData['ids'] as $idInvoice) {
			$invoiceEnt = \Entity\SupplierInvoice::select($idInvoice);

			$formData['invValue'] += $invoiceEnt->totalValue - $invoiceEnt->payedValue;

			if (!$formData['invCurrency']) {
				$formData['invCurrency'] = $invoiceEnt->currency;
			}
		}
		$view->addInput('formData', $formData);
	}

	/**
	 * Do some more stuff for services on the current controller/view right before the render is called.
	 * @param \App\Mvc\View_Window_FormAbstract $view
	 * @param array $formData
	 */
	protected function preRenderOperationsService(\App\Mvc\ViewAbstract $view, array $formData)
	{
		$formData = $view->getInput('formData');

		$idCorporate = 0;
		$idCustomer = 0;
		$serviceEnt = \Entity\Service::select(reset($formData['ids']));
		if ($serviceEnt->order->idCorporateOwner) {
			$idCorporate = $serviceEnt->order->idCorporateOwner;
			$formData['idCorporate'] = $serviceEnt->order->idCorporateOwner;
		}
		elseif ($serviceEnt->order->idCustomerOwner) {
			$idCustomer = $serviceEnt->order->idCustomerOwner;
			$formData['idCustomer'] = $serviceEnt->order->idCustomerOwner;
		}

		$impDocsObj = new \App\EntityList\ImportedDocuments();

		$impDocsObj->setFilter('status', '=', 'new');

		// corporate
		if ($idCorporate) {
			$impDocsObj->setFilter('idCorporate', '=', $idCorporate);
		}
		// customer
		if ($idCustomer) {
			$impDocsObj->setFilter('idCustomer', '=', $idCustomer);
		}

		$impDocsListEx = $impDocsObj->exportRecords();

		$formData['idImportedDocSelectList'] = [];
		foreach($impDocsListEx as $record) {
			$formData['idImportedDocSelectList'][] = $record['id'];
		}

		$view->addInput('formData', $formData);
	}

	/**
	 * Do some more stuff for imported services on the current controller/view right before the render is called.
	 * @param \App\Mvc\View_Window_FormAbstract $view
	 * @param array $formData
	 */
	protected function preRenderOperationsImportedService(\App\Mvc\ViewAbstract $view, array $formData)
	{
		$formData = $view->getInput('formData');

		$idCorporate = 0;
		$idCustomer = 0;
		$impServiceEnt = \Entity\ImportedService::select(reset($formData['ids']));
		if ($impServiceEnt->importedOrder->idCorporateOwner) {
			$idCorporate = $impServiceEnt->importedOrder->idCorporateOwner;
			$formData['idCorporate'] = $impServiceEnt->importedOrder->idCorporateOwner;
		}
		elseif ($impServiceEnt->importedOrder->idCustomerOwner) {
			$idCustomer = $impServiceEnt->importedOrder->idCustomerOwner;
			$formData['idCustomer'] = $impServiceEnt->importedOrder->idCustomerOwner;
		}

		$impDocsObj = new \App\EntityList\ImportedDocuments();

		$impDocsObj->setFilter('status', '=', 'new');

		// corporate
		if ($idCorporate) {
			$impDocsObj->setFilter('idCorporate', '=', $idCorporate);
		}
		// customer
		if ($idCustomer) {
			$impDocsObj->setFilter('idCustomer', '=', $idCustomer);
		}

		$impDocsListEx = $impDocsObj->exportRecords();

		$formData['idImportedDocSelectList'] = [];
		foreach($impDocsListEx as $record) {
			$formData['idImportedDocSelectList'][] = $record['id'];
		}

		$view->addInput('formData', $formData);
	}
}