<?php

/**
 * eSales Media oxVoucher for Contao Open Source CMS
 *
 * Copyright (c) 2015 eSales Media
 *
 * @author  Benjamin Roth [benjamin@esales-media.de]
 * @license proprietary
 */

namespace eSM_oxVoucher;

class ModuleVoucherDetails extends ModuleVoucher
{
	/**
	 * Template
	 * @var string
	 */
	protected $strTemplate = 'mod_oxvoucher_details';

	protected $blnHide = false;

	/**
	 * Parse the template
	 * @return string
	 */
	public function generate()
	{
		if (TL_MODE == 'BE')
		{
			/** @var \BackendTemplate|object $objTemplate */
			$objTemplate = new \BackendTemplate('be_wildcard');

			$objTemplate->wildcard = '### ' . utf8_strtoupper($GLOBALS['TL_LANG']['FMD']['oxvoucher_details'][0]) . ' ###';
			$objTemplate->title = $this->headline;
			$objTemplate->id = $this->id;
			$objTemplate->link = $this->name;
			$objTemplate->href = 'contao/main.php?do=themes&amp;table=tl_module&amp;act=edit&amp;id=' . $this->id;

			return $objTemplate->parse();
		}

		$this->importOxDbInstance();

		$strBuffer = parent::generate();

		if (!$this->blnHide)
		{
			return $strBuffer;
		}
	}


	/**
	 * Compile the current element
	 */
	protected function compile()
	{
		if (\Input::get('voucher_search') || \Input::post('FORM_SUBMIT') == 'eSM_oxVoucher_details')
		{
			if (\Input::post('FORM_SUBMIT') == 'eSM_oxVoucher_details')
			{
				$objSQL = $this->oxDB->prepare("SELECT v.* FROM oxvouchers v, oxvoucherseries vs WHERE vs.OXID = v.OXVOUCHERSERIEID AND LOWER(v.OXID) = ? AND vs.OXDISCOUNTTYPE = 'absolute'");
				$objVoucher = $objSQL->execute(strtolower(\Input::post('OXID')));
			} else {
				$objSQL = $this->oxDB->prepare("SELECT v.* FROM oxvouchers v, oxvoucherseries vs WHERE vs.OXID = v.OXVOUCHERSERIEID AND LOWER(v.OXVOUCHERNR) = ? AND vs.OXDISCOUNTTYPE = 'absolute'");
				$objVoucher = $objSQL->execute(strtolower(\Input::get('voucher_search')));
			}

			if ($objVoucher->numRows < 1 || $objVoucher->numRows > 1)
			{
				if (!\Input::get('voucher_search'))
				{
					$this->Template->noVoucher = $GLOBALS['TL_LANG']['MSC']['oxVoucher']['supplyVoucherNo'];
				} else {
					$this->Template->noVoucher = sprintf($GLOBALS['TL_LANG']['MSC']['oxVoucher']['noVoucher'],\Input::get('voucher_search'));
				}
				return;
			}

			$objVoucher = new VoucherHandler($objVoucher->OXID);
			$blnIsValid = $objVoucher->isValid();

			// Voucher remaining value
			$fUsedVal = $objVoucher->getUsedVal();
			$fRemainingVal = ($blnIsValid ? $objVoucher->getRemainingVal() : (!$objVoucher->isValidTime() ? $objVoucher->getRemainingVal() : 0.00));

			// Update voucher
			if (\Input::post('FORM_SUBMIT') == 'eSM_oxVoucher_details')
			{
				$blnInvalidate = false;

				if (\Input::post('voucher_deductAll'))
				{
					$fDeductVal = $fRemainingVal;
				} else {
					$fDeductVal = floatval(\Input::post('voucher_deductValue'));

				}

				if ($fDeductVal <= $fRemainingVal && $fDeductVal > 0) {
					$objVoucher->deductValue($fDeductVal);

					$strMessage = sprintf($GLOBALS['TL_LANG']['MSC']['oxVoucher']['voucher_confirm'],$this->getFormattedNumber($fDeductVal),$this->getFormattedNumber($objVoucher->getRemainingVal()));
					$strType = 'confirm';

					if ($fDeductVal == $fRemainingVal)
					{
						$strMessage = sprintf($GLOBALS['TL_LANG']['MSC']['oxVoucher']['voucher_confirm_depleted'],$this->getFormattedNumber($fDeductVal));
					}
				} else if ($fDeductVal > $fRemainingVal)
				{
					$strMessage = sprintf($GLOBALS['TL_LANG']['MSC']['oxVoucher']['voucher_error_gtv'],$this->getFormattedNumber($fDeductVal),$this->getFormattedNumber($objVoucher->getRemainingVal()));
					$strType = 'error';
				} else
				{
					$strMessage = $GLOBALS['TL_LANG']['MSC']['oxVoucher']['voucher_error_zero'];
					$strType = 'error';
				}

				$this->setMessage($strMessage,$strType);
				$this->reload();
			}



			// Voucher time
			$Today = new \Date();

			// Template Vars
			if (!is_null($objVoucher->oxdateused))
			{
				$strInvalid = sprintf($GLOBALS['TL_LANG']['MSC']['oxVoucher']['invalid_used'], \Date::parse(\Date::getNumericDateFormat(), $objVoucher->oxdateused));
			} else if (!$objVoucher->isValidTime()) {
				$strInvalid = $GLOBALS['TL_LANG']['MSC']['oxVoucher']['invalid_date'];
			} else {
				$strInvalid = $GLOBALS['TL_LANG']['MSC']['oxVoucher']['invalid'];
			}
			$arrData = array
			(
				'titleDetails'      => $GLOBALS['TL_LANG']['MSC']['oxVoucher']['detailsTitle'],
				'titleDeduct'       => $GLOBALS['TL_LANG']['MSC']['oxVoucher']['deductTitle'],

				'lblVoucherNo'      => $GLOBALS['TL_LANG']['MSC']['oxVoucher']['lblVoucherNo'],
				'lblSerieNo'        => $GLOBALS['TL_LANG']['MSC']['oxVoucher']['lblSerieNo'],
				'lblSerieDesc'      => $GLOBALS['TL_LANG']['MSC']['oxVoucher']['lblSerieDesc'],
				'lblSerieDiscount'  => $GLOBALS['TL_LANG']['MSC']['oxVoucher']['lblSerieDiscount'],
				'lblValidFrom'      => $GLOBALS['TL_LANG']['MSC']['oxVoucher']['lblValidFrom'],
				'lblValidTil'       => $GLOBALS['TL_LANG']['MSC']['oxVoucher']['lblValidTil'],
				'lblRemainingVal'   => $GLOBALS['TL_LANG']['MSC']['oxVoucher']['lblRemainingVal'],

				'voucherOxid'       => $objVoucher->oxid,
				'voucherNo'         => $objVoucher->oxvouchernr,
				'serieNo'           => $objVoucher->oxserienr,
				'serieDesc'         => $objVoucher->oxseriedescription,
				'validFrom'         => (!is_null($objVoucher->oxbegindate) ? \Date::parse(\Date::getNumericDatimFormat(),$objVoucher->oxbegindate) : ''),
				'validTil'          => (!is_null($objVoucher->oxenddate) ? \Date::parse(\Date::getNumericDatimFormat(),$objVoucher->oxenddate) : ''),
				'serieDiscount'     => $this->getFormattedNumber($objVoucher->oxseriediscount),
				'usedVal'           => $fUsedVal,
				'remainingVal'      => $fRemainingVal,
				'fRemainingVal'     => $this->getFormattedNumber($fRemainingVal),

				'submitLabel'       => $GLOBALS['TL_LANG']['MSC']['oxVoucher']['deductSubmitLabel'],
				'valueLabel'        => $GLOBALS['TL_LANG']['MSC']['oxVoucher']['valueLabel'],
				'maxValueLabel'     => sprintf($GLOBALS['TL_LANG']['MSC']['oxVoucher']['maxValueLabel'],$this->getFormattedNumber($fRemainingVal)),

				'isValid'           => $blnIsValid,
				'invalid'           => $strInvalid,

				'messages'          => $this->getMessages(),
			);

			$this->Template->setData($arrData);
		} else
		{

			$this->blnHide = true;
		}


	}

}