<?php
namespace Modules\Bsp\Listing;

class View_InsertGroups extends \App\Mvc\View_Popup_GeneralAbstract
{
	/**
	 * The rendering Smarty template file.
	 * @var String
	 */
	protected $renderingTemplate=SMARTY_LAYOUT_MAIN_POPUP_FORM;

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\ViewAbstract::render()
	 */
	public function render()
	{
		// draw the form
		$form = null;
		if (!$this->closePopup) {
			$form = $this->getForm();
		}
		if ($form) {
			$form->getMessagesObj()->addFromMessageCollector($this->messagesCollector);
			$this->setOutputVar('form', $form);
		}
		else {
			\MessageStack::GetObject()->addFromMessageCollector($this->messagesCollector);
		}

		// sets the closePopup flag
		$this->setOutputVar('closePopup', $this->closePopup);

		return $this->render_smarty($this->renderingTemplate);
	}

	public function getForm()
	{
		if ($this->input['currentStep']=='uploadFiles') {
			return $this->getForm_uploadFiles();	// step 1
		}
		elseif($this->input['currentStep']=='submitData') {
			return $this->getForm_fillData();	// step 2
		}
	}

	public function getForm_uploadFiles()
	{

		// create form and his fieldsets
		$form = \Engine\Form\General::create();
		$fieldset = \Engine\Form\Container\Fieldset::create($this->lang['insert']['uploadFiles']);
		$form->addContainer($fieldset);

		// file
		$file = new \Engine\Form\Input\File($this->lang['insert']['file'], 'file');
		$file->setMandatory(true);
		$form->addElement($file);

		// file type
		$bspTraverserFactory = \App\Bsp\Parser\BspTraverserFactory::getInstance();
		foreach (array_filter($bspTraverserFactory->getFileFormats()->getAll(), function($fmt){
			return !$fmt->hidden && $fmt->handlesGroupFile;
		}) as $fmt) {
			$possibleFileTypes[$fmt->code] = $fmt->label;
		}

		$fileType = new \Engine\Form\Input\Select($this->lang['insert']['fileType'], 'fileType', $this->input['formData']['fileType'], $possibleFileTypes);
		$fileType->setMandatory(true);
		$form->addElement($fileType);

		$fieldset = \Engine\Form\Container\Fieldset::create($this->lang['insert']['defaultValues']);
		$form->addContainer($fieldset);

		// add some info
		$fldsetInfo=new \Engine\Form\Input\Label();
		$fldsetInfo->setDetails($this->lang['insert']['defaultValuesInfo']);
		$fldsetInfo->setStyle("noLabel", true);
		$fieldset->addElement($fldsetInfo);

		// Default interval
		$filePeriod = new \Engine\Form\Input\DateInterval($this->lang['insert']['interval'], 'default[interval]', [
			'start' => 	$this->input['formData']['default']['interval']['start'],
			'end' => 	$this->input['formData']['default']['interval']['end'],
		]);
		$filePeriod->setTooltip($this->lang['insert']['allOfficesIntervalTooltip']);
		$fieldset->addElement($filePeriod);

		// Default description
		$description = new \Engine\Form\Input\Textarea($this->lang['insert']['description'], "default[description]", $this->input['formData']['default']['description']);
		$fieldset->addElement($description);

		$form->addElement(new \Engine\Form\Input\Hidden('', 'step', 'uploadFiles'));
		$form->addElement(new \Engine\Form\Input\Hidden('', 'stepSubmitted', 1));

		// $form->addElement(new \Engine\Form\Input\Hidden('', $this->submitButtonName, 1));

		return $form;
	}

	public function getForm_fillData()
	{
		// create form and his fieldsets
		$form = \Engine\Form\General::create();
		$fieldset = \Engine\Form\Container\Fieldset::create($this->lang['insert']['fillData']);
		$form->addContainer($fieldset);

		// filename
		$file = new \Engine\Form\Input\Text($this->lang['insert']['file'], null, $this->input['fileName']);
		if ($this->input['fileData']) {
			$fdetails = [];
			if ($this->input['fileData']['agent']) {
				$fdetails[]= sprintf($this->lang['insert']['file_agent'], $this->input['fileData']['agent']);
			}
			if ($this->input['fileData']['rowsCount']) {
				$fdetails[]= sprintf($this->lang['insert']['file_rows'], number_format($this->input['fileData']['rowsCount']), number_format($this->input['fileData']['ticketsCount']));
			}
			$fdetails[]= sprintf($this->lang['insert']['file_dates'],
				\Engine\DateTime::createFromIsoDate($this->input['fileData']['dates']['minTicketDate'])->formatDateStd(),
				\Engine\DateTime::createFromIsoDate($this->input['fileData']['dates']['maxTicketDate'])->formatDateStd()
			);
// 			if ($this->input['fileData']['totals']) { // TODO: commented as it seems that it does not do anything
// 				$cdetails = [];
// 				foreach ($this->input['fileData']['totals'] as $currency=>$totals) {
// 					$cdetails[]= sprintf("%s %s", number_format($totals['balancePayable'], 2), $currency);
// 				}
// 			}

			$file->setDetails(implode(", ", $fdetails));
		}
		$form->addElement($file->setDisabled());

		if ($this->input['fileData']['groups']) {
			foreach ($this->input['fileData']['groups'] as $idx=>$group) {
				$groupFieldset = \Engine\Form\Container\Fieldset::create(sprintf($this->lang['insertGroups']['groupData'], $group['agent'], $group['agencyIataCode']));
				$form->addContainer($groupFieldset);

				$filePeriod = new \Engine\Form\Input\DateInterval($this->lang['insert']['interval'], "group[{$idx}][interval]", [
					'start' => 	($this->input['formData'][$idx]['interval']['start']?:$this->input['formData']['default']['interval']['start']),
					'end' => 	($this->input['formData'][$idx]['interval']['end']?:$this->input['formData']['default']['interval']['end']),
				]);

				if ($this->input['fileData'][$idx]['interval']['start'] && $this->input['fileData'][$idx]['interval']['end']) {
					$filePeriod->setDetails(sprintf("%s - %s",
						\Engine\DateTime::createFromIsoDate($this->input['fileData'][$idx]['interval']['start'])->formatDateStd(),
						\Engine\DateTime::createFromIsoDate($this->input['fileData'][$idx]['interval']['end'])->formatDateStd()
					));
				}

				$filePeriod->setMandatory();
				$groupFieldset->addElement($filePeriod);

				if (\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Bsp/Listing-completeAccess')) {
					$office = new \App\Form\Input\Autocomplete_OfficeAndIataCode($this->lang['insert']['office'], "group[{$idx}][office]", $this->input['formData'][$idx]['office']);
					$office->setMandatory();
					$groupFieldset->addElement($office);
				}
				else {
					$office = new \App\Form\Input\Autocomplete_OfficeAndIataCode($this->lang['insert']['office'], null, ['id'=>sprintf("%s:%s", CURRENT_ID_OFFICE, \Entity\Office::select(CURRENT_ID_OFFICE)->iataCode[0])]);
					$office->setMandatory();
					$office->setDisabled();
					$groupFieldset->addElement($office);
					$groupFieldset->addElement(new \Engine\Form\Input\Hidden('', "group[{$idx}][office][id]", sprintf("%s:%s", CURRENT_ID_OFFICE, \Entity\Office::select(CURRENT_ID_OFFICE)->iataCode[0])));
				}

				$description = new \Engine\Form\Input\Textarea($this->lang['insert']['description'], "group[{$idx}][description]", ($this->input['formData'][$idx]['description']?:$this->input['formData']['default']['description']));
				$groupFieldset->addElement($description);
			}
		}

		$form->addElement(new \Engine\Form\Input\Hidden('', 'step', 'submitData'));
		$form->addElement(new \Engine\Form\Input\Hidden('', 'stepSubmitted', 1));

		return $form;
	}
}
