<?php
namespace Modules\Orders\MiceProjects;

class Controller extends \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing
{
	/**
	 * Indicates if the entity execution should use or not a transaction. It left to 'null' the
	 * class won't work correctly - the concrete class must set it to true/false.
	 * @var Boolean
	 */
	protected $useSqlTransaction = true;

	/**
	 * The list of columns which support ordering.
	 * @var array
	 */
	protected $listOrderingColumns = ['name', 'addTime', 'estimatedPeriod'];


	protected function initialize()
	{
		parent::initialize();

		// access for close, open, preferences and reports action
		$this->actionsCfg['close'] = 		['checkOption' => 'Modules/Orders/MiceProjects-update',];
		$this->actionsCfg['open'] = 		['checkOption' => 'Modules/Orders/MiceProjects-update',];
		$this->actionsCfg['preferences'] = 	[];
		$this->actionsCfg['reports'] = 		[];
		$this->actionsCfg['download'] = 	[];
	}


	/**
	 * updates 'close' information
	 * @param array $R
	 */
	protected function actionClose($R)
	{
		$msgs = \App\MessagesCollector::create();

		$ids = $this->setListingSelection($R['listing']['selection'])->getList();
		foreach ($ids as $id) {

			try {
				\DB::startTransaction();

				$miceProjectEnt = \Entity\MiceProject::update($id);
				$miceProjectEnt->closed = true;
				$miceProjectEnt->save();

				// remove this record from the internal list
				if (count($ids) > 1) {
					$this->getListingSelection()->delete([$id]);
				}

				// commit the current transaction
				\DB::commitTransaction();

				// adds success message
				foreach($miceProjectEnt->getMessages()->getMessages() as $msg) {
					$msgs->addMessage($msg);
				}

			} catch(\App\Entity\Exception $ex) {
				\DB::rollbackTransaction();
				$msgs->appendMessages($ex->getMessagesCollector());
			}
		}

		return $this->executeListRecords($R, $msgs);
	}


	/**
	 * opens the project
	 * @param array $R
	 */
	protected function actionOpen($R)
	{
		$msgs = \App\MessagesCollector::create();

		$ids = $this->setListingSelection($R['listing']['selection'])->getList();
		foreach ($ids as $id) {

			try {
				\DB::startTransaction();

				$miceProjectEnt = \Entity\MiceProject::update($id);
				$miceProjectEnt->closed = false;
				$miceProjectEnt->save();

				// remove this record from the internal list
				$this->getListingSelection()->delete([$id]);

				// commit the current transaction
				\DB::commitTransaction();

				// adds success message
				foreach($miceProjectEnt->getMessages()->getMessages() as $msg) {
					$msgs->addMessage($msg);
				}

			} catch(\App\Entity\Exception $ex) {
				\DB::rollbackTransaction();
				$msgs->appendMessages($ex->getMessagesCollector());
			}
		}

		return $this->executeListRecords($R, $msgs);
	}


	/**
	 * action for insert/edit preferences
	 * @param array $R
	 */
	protected function actionPreferences($R)
	{
		$msgs = \App\MessagesCollector::create();

		$miceProjectPreferences = \App\EntityPreference\MiceProject::getInstance($R['id']);
		$formData = 	[];

		// get form default values ////////////////////////////////////////////////////////////////
		if (!$R[$this->formSubmitButtonName]) {
			$formData['id'] = 							$R['id'];
			$formData['invoiceRowsDescriptionScheme'] = $miceProjectPreferences->invoiceRowsDescriptionScheme;
			$formData['idAgencyBankAccount'] = 			$miceProjectPreferences->idAgencyBankAccount;
			$formData['idInvoiceSeries'] = 				$miceProjectPreferences->idInvoiceSeries;
			$formData['idInvoiceTemplate'] = 			$miceProjectPreferences->idInvoiceTemplate;
			$formData['idCashingSeries'] = 				$miceProjectPreferences->idCashingSeries;
			$formData['idCashingTemplate'] = 			$miceProjectPreferences->idCashingTemplate;
		}
		else {
			$formData = $R;
		}

		// save preferences ///////////////////////////////////////////////////////////////////////
		$closePopup = false;
		if ($R[$this->formSubmitButtonName]) {
			\DB::startTransaction();
			$miceProjectPreferences->invoiceRowsDescriptionScheme =	$R['invoiceRowsDescriptionScheme'];
			$miceProjectPreferences->idAgencyBankAccount =			$R['idAgencyBankAccount'];
			$miceProjectPreferences->idInvoiceSeries =				$R['idInvoiceSeries'];
			$miceProjectPreferences->idInvoiceTemplate =			$R['idInvoiceTemplate'];
			$miceProjectPreferences->idCashingSeries =				$R['idCashingSeries'];
			$miceProjectPreferences->idCashingTemplate =			$R['idCashingTemplate'];
			\DB::commitTransaction();

			$msgs->addSuccess($this->lang['preferences']['succes']);
			$closePopup = true;
		}

		// render view
		$view = new View_Preferences($this);
		$view->addInput('formData', $formData);
		if ($closePopup) {
			$view->setClosePopup(true);
		}
		$view->getMessagesCollector()->appendMessages($msgs);
		$view->addInput('formSubmitButtonName', $this->formSubmitButtonName);

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


	/**
	 * show reports for the project
	 * @param array $R
	 */
	protected function actionReports($R)
	{
		$msgs = \App\MessagesCollector::create();

		// default info about project
		$miceProject = \Entity\MiceProject::select($R['id']);

		$data['id'] = 				$R['id'];
		$data['name'] = 			$miceProject->name;
		$data['period']['start'] = 	$miceProject->startDate;
		$data['period']['end'] = 	$miceProject->endDate;
		$data['countryCode'] = 		$miceProject->countryCode;
		$data['cityId'] = 			$miceProject->cityId;


		//
		if ($R[$this->formSubmitButtonName]) {
			if ($R['reportType']) {

				$data['reportType'] = $R['reportType'];
				$data['downloadReport'] = $R['downloadReport'];

				$report = new MiceReports();
				$reportData = $report->getRecords($R['id']);

				// date
				$start = $reportData['startDate'];
				while ($start<=$reportData['endDate']) {
					$reportData['time'][] = $start;
					$start = date('Y-m-d', strtotime("+1day", strtotime($start)));
				}

				$data['reportData'] = $reportData;
			}
			else {
				$msgs->addInfo($this->lang['reports']['noSelection']);
			}
		}

		// send info to view
		$view = new View_Reports($this);
		$view->addInput('formData', $data);
		$view->setOutputVar('formData', $data);
		$view->getMessagesCollector()->appendMessages($msgs);
		$view->addInput('formSubmitButtonName', $this->formSubmitButtonName);

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

	}

	/**
	 * download the report
	 * @param int $R
	 */
	protected function actionDownload($R)
	{
		$miceProject = \Entity\MiceProject::select($R['id']);

		$data['id'] = 				$R['id'];
		$data['name'] = 			$miceProject->name;

		$report = new MiceReports();
		$reportData = $report->getRecords($R['id']);

		$start = $reportData['startDate'];
		while ($start<=$reportData['endDate']) {
			$reportData['time'][] = $start;
			$start = date('Y-m-d', strtotime("+1day", strtotime($start)));
		}

		$data['reportData'] = $reportData;

		$view = new View_Download($this);
		$view->setOutputVar('formData', $data);

		$fileName = sprintf("%s-%s(%s).xml.xls", "Daily_agenda",$miceProject->name, TODAY_ISO);

		$response = new \Engine\Mvc\Response\FileDownload($view->render());
		$response->setFilename($fileName);

		return $response;
	}



	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing::insert_createEntityObject()
	 */
	protected function insert_createEntityObject($formData)
	{
		$miceProject = \Entity\MiceProject::insert();

		$miceProject->name = 				$formData['name'];
		$miceProject->code = 				$formData['code'];
		$miceProject->idCorporate = 		$formData['corporate']['id'];
		$miceProject->idContactPerson =		$formData['contactPerson']['id'];
		$miceProject->idType = 				$formData['idType']['id'];
		$miceProject->startDate = 			$formData['interval']['start'] ? : null;
		$miceProject->endDate = 			$formData['interval']['end'] ? : null;
		$miceProject->idResponsibleUser = 	$formData['idResponsibleUser']['id'];
		$miceProject->email =				$formData['email'];
		$miceProject->comments =			$formData['comments'];
		$miceProject->remarks =				$formData['remarks'];
		list($countryCode, $cityId) = explode("|", $formData['location']['id']);
		$miceProject->countryCode = 		(string)$countryCode;
		$miceProject->cityId = 				(int)$cityId;

		return $miceProject;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::update_getDefaultFormData()
	 */
	protected function update_getDefaultFormData($id)
	{
		$miceProject = \Entity\MiceProject::select($id);

		$formData['name'] = 					$miceProject->name;
		$formData['code'] = 					$miceProject->code;
		$formData['corporate']['id'] = 			$miceProject->idCorporate;
		$formData['contactPerson']['id'] = 		$miceProject->idContactPerson;
		$formData['idType']['id'] = 			$miceProject->idType;
		$formData['interval']['start'] = 		$miceProject->startDate;
		$formData['interval']['end'] = 			$miceProject->endDate;
		$formData['idResponsibleUser']['id'] = 	$miceProject->idResponsibleUser;
		$formData['email'] = 					$miceProject->email;
		$formData['comments'] = 				$miceProject->comments;
		$formData['remarks'] = 					$miceProject->remarks;
		$formData['location']['id'] = implode('|', [$miceProject->countryCode, $miceProject->cityId]);

		return $formData;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing::update_createEntityObject()
	 */
	protected function update_createEntityObject($formData)
	{
		$miceProject = \Entity\MiceProject::update($this->updateIdRecord);

		$miceProject->name = 				$formData['name'];
		$miceProject->code = 				$formData['code'];
		$miceProject->idCorporate = 		$formData['corporate']['id'];
		$miceProject->idContactPerson =		$formData['contactPerson']['id'];
		$miceProject->idType = 				$formData['idType']['id'];
		$miceProject->startDate = 			$formData['interval']['start'] ? $formData['interval']['start'] : null;
		$miceProject->endDate = 			$formData['interval']['end'] ? $formData['interval']['end'] : null;
		$miceProject->idResponsibleUser = 	$formData['idResponsibleUser']['id'];
		$miceProject->email =				$formData['email'];
		$miceProject->comments =			$formData['comments'];
		$miceProject->remarks =				$formData['remarks'];
		list($countryCode, $cityId) = 		explode("|", $formData['location']['id']);
		$miceProject->countryCode =			(string)$countryCode;
		$miceProject->cityId =				(int)$cityId;

		return $miceProject;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing::delete_createEntityObject()
	 */
	protected function delete_createEntityObject($id)
	{
		return \Entity\MiceProject::delete($id);
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::optionDefineParams()
	 */
	protected function optionDefineParams(\App\Mvc\View\Utils\RowOptions\Option\Option $option, $selection)
	{
		switch($option->getId()){
			case 'close':
				foreach ($selection as $selectedItem) {
					$miceProject = \Entity\MiceProject::select($selectedItem);
					if ($miceProject->closed) {
						$option->setDisabled();
					}
				}
			break;

			case 'open':
				foreach ($selection as $selectedItem) {
					$miceProject = \Entity\MiceProject::select($selectedItem);
					if (!$miceProject->closed) {
						$option->setDisabled();
					}
				}
			break;

			case 'update':
				foreach ($selection as $selectedItem) {
					if (!$option->determineOperationAvailability(\Entity\MiceProject::update($selectedItem))) {
						break;
					}
				}
			break;

			case 'delete':
				foreach ($selection as $selectedItem) {
					if (!$option->determineOperationAvailability(\Entity\MiceProject::delete($selectedItem))) {
						break;
					}
				}
			break;

			case 'insert':
				$option->determineOperationAvailability(\Entity\MiceProject::insert());
			break;

			case 'showReservation': case 'reports': 	case 'preferences':
			break;

			default:
				return false;
		}

		return true;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::optionGetEntityName()
	 */
	protected function optionGetEntityName($id)
	{
		return \Entity\MiceProject::select($id)->name;
	}
}
