<?php
namespace Modules\Admin\Config\Services\Advanced\BulkOperations;

class View_Utils_FormAdmin extends \App\Mvc\View_Utils_FormAbstract
{

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\View_Utils_FormAbstract::getForm()
	 */
	public function getForm()
	{

		if ($this->values['currentStep']==1) {
			$form = $this->getFormStep1();
		}
		elseif ($this->values['currentStep']==2) {
			$form = $this->getFormStep2();
		}
	 	elseif ($this->values['currentStep']==3) {
			$form = $this->getFormStep3();
		}
		else {
			throw new \Exception('Wrong step value');
		}

		return $form;
	}

	/**
	 * The first step (filtering calculations).
	 * @return \Engine\Form\General
	 */
	private function getFormStep1()
	{

		$form = \Engine\Form\General::create();

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

		// service codes
		$serviceCodes = new \App\Form\Input\Select_Service($this->lang['index']['form']['services'], 'filters[serviceCode]', $this->values['filters']['serviceCode']);
		$serviceCodes->setMultipleSelector(true);
		$serviceCodes->setStyle('height', '200');
		$serviceCodes->showDefaultOption(false);
		$fieldset->addElement($serviceCodes);

		// service location
		$serviceCriteria = new \App\Form\Input\Checkboxes_CountryCriterion($this->lang['index']['form']['location'], 'filters[location]', $this->values['filters']['location']);
		$fieldset->addElement($serviceCriteria);

		// calculation name
		$calcNameField = new \Engine\Form\Input\Text($this->lang['index']['form']['calcName'], 'filters[calculationName]', $this->values['filters']['calculationName']);
		$calcNameField->setTooltip($this->lang['index']['form']['calcNameDet']);
		$fieldset->addElement($calcNameField);

		// VAT percent / field
		$vatPercentValue = new \Engine\Form\Input\Text($this->lang['index']['form']['vatPercVal'], 'filters[vatPercent]', $this->values['filters']['vatPercent']);
		$vatPercentValue->setTooltip($this->lang['index']['form']['vatPercValDet']);
		$fieldset->addElement($vatPercentValue);
		$vatPercentField = new \Engine\Form\Input\Checkboxes($this->lang['index']['form']['vatPercFld'], 'filters[vatField]', $this->values['filters']['vatField']);
		$vatPercentField->setTooltip($this->lang['index']['form']['vatPercFldDet']);
		$fields =
		[
			'offer_supplier' => $this->globalLang['rowType']['supplierPrice'] .' '. $this->lang['index']['form']['filters']['offer'],
			'offer_commission' => $this->globalLang['rowType']['commission'] .' '. $this->lang['index']['form']['filters']['offer'],
			'offer_discount' => $this->globalLang['rowType']['discount'] .' '. $this->lang['index']['form']['filters']['offer'],
			'offer_serviceFee' => $this->globalLang['rowType']['serviceFee'] .' '. $this->lang['index']['form']['filters']['offer'],
			'offer_tax' => $this->globalLang['rowType']['tax'] .' '. $this->lang['index']['form']['filters']['offer'],
			'invoice_price' =>  $this->globalLang['rowType']['price'] .' '. $this->lang['index']['form']['filters']['invoice'],
			'invoice_commission' => $this->globalLang['rowType']['commission'] .' '. $this->lang['index']['form']['filters']['invoice'],
			'invoice_discount' => $this->globalLang['rowType']['discount'] .' '. $this->lang['index']['form']['filters']['invoice'],
			'invoice_serviceFee' => $this->globalLang['rowType']['serviceFee'] .' '. $this->lang['index']['form']['filters']['invoice'],
			'invoice_tax' => $this->globalLang['rowType']['tax'] .' '. $this->lang['index']['form']['filters']['invoice'],
			'invoice_penalty' => $this->globalLang['rowType']['advance'] .' '. $this->lang['index']['form']['filters']['invoice'],
			'invoice_advance' => $this->globalLang['rowType']['penalty'] .' '. $this->lang['index']['form']['filters']['invoice'],
		];
		$vatPercentField->setPossibleValues($fields);
		$fieldset->addElement($vatPercentField);

		// VAT quota
		$vatQuotaField = new \Engine\Form\Input\Text($this->lang['index']['form']['vatText'], 'filters[vatText]', $this->values['filters']['vatText']);
		$vatQuotaField->setTooltip($this->lang['index']['form']['vatTextDet']);
		$fieldset->addElement($vatQuotaField);

		$fieldset->addElement(new \Engine\Form\Input\Hidden(null, 'step', 1));
		$fieldset->addElement(new \Engine\Form\Input\Hidden(null, $this->submitButtonName, 1));

		return $form;

	}

	/**
	 * The second step (selecting calculations).
	 * @return \Engine\Form\General
	 */
	private function getFormStep2()
	{

		$form = \Engine\Form\General::create();
		$fieldset1 = \Engine\Form\Container\Fieldset::create($this->lang['index']['form']['operationLeg']);
		$fieldset2 = \Engine\Form\Container\Fieldset::create($this->lang['index']['form']['selectCalcLeg']);
		$form->addContainer($fieldset1);
		$form->addContainer($fieldset2);

		// ADD OPERATION FIELD --------------------------------------------------------------------
		$operationFld = new \Engine\Form\Input\Radio($this->lang['index']['form']['operationFld'], 'operation', $this->values['operation']);
		$operationFld->setPossibleValues(['clone'=>$this->lang['index']['form']['op_clone'], 'update'=>$this->lang['index']['form']['op_update']]);
		$operationFld->setMandatory(true);
		$fieldset1->addElement($operationFld);

		// ADD LIST OF CALCULATIONS ---------------------------------------------------------------
		$calcs = \App\Config\Services_Calculations::getAdmin()->getAll();
		$groupedCalcs = [];
		foreach($calcs as $calcCode=>$calcDet) {
			if (!$calcDet['deleted']) {
				$groupedCalcs[$calcDet['serviceCode']][$calcCode] = $calcDet;
			}
		}
		foreach ($groupedCalcs as $serviceCode=>$serviceCalcs) {
			$calcsFld = new \Engine\Form\Input\Checkboxes(\App\Config\Services_Basic::getInstance()->getServiceName($serviceCode), "calculations[{$serviceCode}]", $this->values['calculations'][$serviceCode]);
			$servCalcsList = [];
			foreach($serviceCalcs as $calcCode=>$calcDet) {
				$servCalcsList[$calcCode] = '<i>'.$calcDet['location'].'</i> ['.$calcDet['name'].']';
			}
			$calcsFld->setPossibleValues($servCalcsList);
			$fieldset2->addElement($calcsFld);
		}

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

		return $form;

	}

	/**
	 * The third step (defining operation details).
	 * @return \Engine\Form\General
	 */
	private function getFormStep3()
	{

		$form = \Engine\Form\General::create();

		// ADD CALCULATIONS AND OPERATION ---------------------------------------------------------
		$form->addElement(new \Engine\Form\Input\Hidden(null, 'operation', $this->values['operation']));

		if ($this->values['calculations']) {
			foreach($this->values['calculations'] as $servCode=>$servDet) {
				foreach($servDet as $calcCode=>$calcDet) {
					$form->addElement(new \Engine\Form\Input\Hidden(null, "calculations[{$servCode}][{$calcCode}]", $this->values['calculations'][$servCode][$calcCode]));
				}
			}
		}

		// save and step fields
		$form->addElement(new \Engine\Form\Input\Hidden(null, 'step', 3));
		$form->addElement(new \Engine\Form\Input\Hidden(null, $this->submitButtonName, 1));

		// FORM FOR THE UPDATE OPERATION ----------------------------------------------------------
		if ($this->values['operation']=='update') {
			$this->getFormStep3_popuplateUpdateForm($form);
		}
		elseif ($this->values['operation']=='clone') {
			$this->getFormStep3_popuplateCloneForm($form);
		}

		return $form;

	}

	private function getFormStep3_popuplateUpdateForm(\Engine\Form\General $form)
	{

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

		$ttlCount = 0;
		foreach($this->values['calculations'] as $servCode=>$servDet) {
			$ttlCount += count($servDet);
		}
		// show count stuff
		$label = new \Engine\Form\Input\Label();
		$label->setStyle("noLabel", true);
		$label->setDetails(sprintf($this->lang['index']['form']['updateDetails'], '<b>'.$ttlCount.'</b>'));
		$fieldset->addElement($label);

		$labelQuotaAndRemark = new \Engine\Form\Input\Label();
		$labelQuotaAndRemark->setStyle("noLabel", true);
		$labelQuotaAndRemark->setDetails($this->lang['index']['form']['updateDetailsQuotasRemarks']);
		$fieldset->addElement($labelQuotaAndRemark);

		// FORCE VATS -----------------------------------------------------------------------------
		$offerComponents =
			[
				'supplier' => $this->globalLang['rowType']['supplierPrice'],
				'commission' => $this->globalLang['rowType']['commission'],
				'discount' => $this->globalLang['rowType']['discount'],
				'serviceFee' => $this->globalLang['rowType']['serviceFee'],
				'tax' => $this->globalLang['rowType']['tax'],
			];

		$invoiceComponents =
			[

				'price' => $this->globalLang['rowType']['price'],
				'commission' => $this->globalLang['rowType']['commission'],
				'discount' => $this->globalLang['rowType']['discount'],
				'serviceFee' => $this->globalLang['rowType']['serviceFee'],
				'tax' => $this->globalLang['rowType']['tax'],
				'penalty' => $this->globalLang['rowType']['advance'],
				'advance' => $this->globalLang['rowType']['penalty'],
			];


		$offerFieldset = \Engine\Form\Container\Fieldset::create($this->lang['index']['form']['offerVatPercent']);
		$form->addContainer($offerFieldset);

		$invoiceFieldset = \Engine\Form\Container\Fieldset::create($this->lang['index']['form']['invoiceVatPercent']);
		$form->addContainer($invoiceFieldset);

		$quotaFieldset = \Engine\Form\Container\Fieldset::create($this->lang['index']['form']['invoiceVatQuota']);
		$form->addContainer($quotaFieldset);

		$remarkFieldset = \Engine\Form\Container\Fieldset::create($this->lang['index']['form']['invoiceVatRemark']);
		$form->addContainer($remarkFieldset);

		// add offer VAT percents
		foreach($offerComponents as $componentCode=>$componentName) {
			$input = new \Engine\Form\Input\Text(sprintf($this->lang['index']['form']['forceVatFld'], $componentName), "offerVatPercent[{$componentCode}]", $this->values['offerVatPercent'][$componentCode]);
			$input->setValidator(['type'=>'float', 'minValue'=>0, 'maxValue'=>100]);
			$offerFieldset->addElement($input);
		}

		// add invoice VAT percents
		foreach($invoiceComponents as $componentCode=>$componentName) {
			$input = new \Engine\Form\Input\Text(sprintf($this->lang['index']['form']['forceVatFld'], $componentName), "invoiceVatPercent[{$componentCode}]", $this->values['invoiceVatPercent'][$componentCode]);
			$input->setValidator(['type'=>'float', 'minValue'=>0, 'maxValue'=>100]);
			$invoiceFieldset->addElement($input);
		}

		// add VAT quotas
		foreach($invoiceComponents as $componentCode=>$componentName) {
			$input = new \Engine\Form\Input\Text(sprintf($this->lang['index']['form']['forceVatQuotaFld'], $componentName), "vatText[{$componentCode}]", $this->values['vatText'][$componentCode]);
			$quotaFieldset->addElement($input);
		}

		// add VAT remarks
		foreach($invoiceComponents as $componentCode=>$componentName) {
			$input = new \Engine\Form\Input\Text(sprintf($this->lang['index']['form']['forceVatRemarkFld'], $componentName), "vatRemark[{$componentCode}]", $this->values['vatRemark'][$componentCode]);
			$remarkFieldset->addElement($input);
		}

	}

	private function getFormStep3_popuplateCloneForm(\Engine\Form\General $form)
	{

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

		// CALCULATION NAME -----------------------------------------------------------------------
		$fld = new \Engine\Form\Input\Text($this->lang['index']['form']['calcNameFld'], 'calculationName', $this->values['calculationName']);
		$fld->setMandatory();
		$fieldset->addElement($fld);

		if ($this->values['calculations']) {
			$vatsDetails = $this->getVatDetails($this->values['calculations']);
		}

		// VATS FOR OFFER -------------------------------------------------------------------------
		if ($vatsDetails['offerVatPercents']) {
			$fieldset1 = \Engine\Form\Container\Fieldset::create($this->lang['index']['form']['offerVatPercFld']);
			$form->addContainer($fieldset1);
			foreach($vatsDetails['offerVatPercents'] as $vatPercent=>$count) {
				$fld = new \Engine\Form\Input\Text(sprintf($this->lang['index']['form']['cloneVatFld'], $vatPercent), "offerVatPercent[{$vatPercent}]", $this->values['offerVatPercent'][$vatPercent]);
				$fld->setDetails(sprintf($this->lang['index']['form']['vatPercFound'], $count));
				$fld->setValidator(['type'=>'float', 'minValue'=>0, 'maxValue'=>100]);
				$fieldset1->addElement($fld);
			}
		}

		// VATS FOR INVOICE -----------------------------------------------------------------------
		if ($vatsDetails['invoiceVatPercents']) {
			$fieldset2 = \Engine\Form\Container\Fieldset::create($this->lang['index']['form']['invoiceVatsCont']);
			$form->addContainer($fieldset2);
			foreach($vatsDetails['invoiceVatPercents'] as $vatPercent=>$count) {
				$fld = new \Engine\Form\Input\Text(sprintf($this->lang['index']['form']['cloneVatFld'], $vatPercent), "invoiceVatPercent[{$vatPercent}]", $this->values['invoiceVatPercent'][$vatPercent]);
				$fld->setDetails(sprintf($this->lang['index']['form']['vatPercFound'], $count));
				$fld->setValidator(['type'=>'float', 'minValue'=>0, 'maxValue'=>100]);
				$fieldset2->addElement($fld);
			}
		}

		// VAT TEXT FOR INVOICE -------------------------------------------------------------------
		if ($vatsDetails['invoiceVatTexts']) {
			$fieldset3 = \Engine\Form\Container\Fieldset::create($this->lang['index']['form']['invVatTextCont']);
			$form->addContainer($fieldset3);
			foreach($vatsDetails['invoiceVatTexts'] as $vatText=>$count) {
				$fld = new \Engine\Form\Input\Text(sprintf($this->lang['index']['form']['cloneVatTextFld'], $vatText), "invoiceVatText[{$vatText}]", $this->values['invoiceVatText'][$vatText]);
				$fld->setDetails(sprintf($this->lang['index']['form']['vatTextFound'], $count));
				$fieldset3->addElement($fld);
			}
		}

	}

	/**
	 * Returns calculation VAT details grouped for step 3 (cloning).
	 * @param Array $calculations
	 */
	private function getVatDetails(Array $calculations)
	{

		$return = [];
		$offCfg = \App\Config\Services_Calculations_OfferVat::getAdmin();
		$invCfg = \App\Config\Services_Calculations_InvoiceVat::getAdmin();
		$return['offerVatPercents'] = [];
		$return['invoiceVatPercents'] = [];
		$return['invoiceVatTexts'] = [];
		foreach($calculations as $serviceCode=>$servCalcs) {
			foreach($servCalcs as $calcCode=>$calcDet) {

				// offer
				$vatsDet = $offCfg->get($calcCode);
				foreach($vatsDet as $comp=>$det) {
					$return['offerVatPercents'][$det['percent']] += 1;
				}

				// invoice
				$vatsDet = $invCfg->get($calcCode);
				foreach($vatsDet as $comp=>$det) {
					$return['invoiceVatPercents'][$det['vatPercent']] += 1;
					if (strlen($det['vatText'])) {
						$return['invoiceVatTexts'][$det['vatText']] += 1;
					}
				}

			}
		}

		return $return;

	}


}

