<?php
/**
 * @package DJ-Catalog2
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 */

// no direct access
defined('_JEXEC') or die;

//Joomla\CMS\HTML\HTMLHelper::_('bootstrap.tooltip');
Joomla\CMS\Factory::getDocument()->getWebAssetManager()->useScript('form.validate');
//Joomla\CMS\HTML\HTMLHelper::_('formbehavior.chosen', 'select');

$params = JComponentHelper::getParams('com_djcatalog2');

$net_prices = (bool)((int)$params->get('price_including_tax', 1) == 0);
?>
<script type="text/javascript">
	Joomla.submitbutton = function(task)
	{
		if (task == 'payment.cancel' || document.formvalidator.isValid(document.getElementById('edit-form'))) {
			Joomla.submitform(task, document.getElementById('edit-form'));
		}
		else {
			alert('<?php echo $this->escape(JText::_('JGLOBAL_VALIDATION_FORM_FAILED'));?>');
		}
	}
</script>

<form
	action="<?php echo JRoute::_('index.php?option=com_djcatalog2&view=payment&layout=edit&id='.(int) $this->item->id); ?>"
	method="post" name="adminForm" id="edit-form" class="form-validate"
	enctype="multipart/form-data">
	<fieldset>
		<div class="row row-fluid">
			<div class="col-md-12 form-horizontal">
			
			<?php echo Joomla\CMS\HTML\HTMLHelper::_('uitab.startTabSet', 'myTab', array('recall' => true, 'active' => 'details')); ?>
			
			<?php echo Joomla\CMS\HTML\HTMLHelper::_('uitab.addTab', 'myTab', 'details', JText::_('COM_DJCATALOG2_EDIT')); ?>
				
					<?php echo $this->form->renderField('name'); ?>
					<?php echo $this->form->renderField('image'); ?>
					<?php echo $this->form->renderField('id'); ?>
					<?php echo $this->form->renderField('plugin'); ?>
					
					<?php echo $this->form->renderField('price'); ?>
					
					<div class="control-group">
						<div class="control-label">
							<label>&nbsp;&nbsp;&raquo;&nbsp;<?php echo JText::_($net_prices ? 'COM_DJCATALOG2_PRICE_INCL_TAX' : 'COM_DJCATALOG2_PRICE_EXCL_TAX')?></label>
						</div>
						<div class="controls">
							<input type="text" class="djc_price_tax readonly input form-control input-mini" readonly="readonly" id="jform_price_tax" data-type="<?php echo $net_prices ? 'net' : 'gross'?>" value="" />
						</div>
					</div>
					
					<?php echo $this->form->renderField('tax_rule_id'); ?>
					<?php echo $this->form->renderField('additional_fee'); ?>
					<?php echo $this->form->renderField('free_amount'); ?>
					<?php echo $this->form->renderField('currencies'); ?>
					<?php echo $this->form->renderField('deliveries'); ?>
					<?php echo $this->form->renderField('note'); ?>
					
					<?php echo $this->form->renderField('recurring'); ?>
	
					<?php echo $this->form->renderField('published'); ?>
					
					<?php echo $this->form->renderField('access'); ?>
					
					<?php echo $this->form->renderField('countries'); ?>
					
					<?php echo $this->form->renderField('postcodes'); ?>
					
					<?php echo $this->form->renderField('short_description'); ?>
					
					<?php /* ?>
					<div class="control-group">
						<div class="control-label">
							<label><?php echo JText::_('COM_DJCATALOG2_DELIVERIES'); ?> </label>
						</div>
						<div class="controls">
						<?php if (empty($this->item->id) || ($this->item->id == 0)) { ?>
							<a class="btn btn-primary" href="#"
								onclick="javascript:Joomla.submitbutton('payment.apply')"> <?php echo JText::_('COM_DJCATALOG2_SAVE_FIRST'); ?>
							</a>
							<?php } else { ?>
							<a class="btn btn-primary modal"
								rel="{handler: 'iframe', size: {x: 875, y: 550}, onClose: function() {}}"
								href="index.php?option=com_djcatalog2&amp;view=deliveries&amp;layout=payments&amp;item_id=<?php echo $this->item->id; ?>&amp;tmpl=component">
								<?php echo JText::_('COM_DJCATALOG2_SELECT_DELIVERIES'); ?>
							</a>
							<?php }?>
						</div>
					</div>
					<?php */ ?>
					<div class="control-group">
						<div class="control-label">
						<?php echo $this->form->getLabel('description'); ?>
						</div>
						<div class="controls">
						<?php echo $this->form->getInput('description'); ?>
						</div>
					</div>
					
				<?php echo Joomla\CMS\HTML\HTMLHelper::_('uitab.endTab'); ?>
				
				<?php echo Joomla\CMS\HTML\HTMLHelper::_('uitab.addTab', 'myTab', 'params', JText::_('COM_DJCATALOG2_PARAMS')); ?>
				
				<?php if (empty($this->item->plugin)) {
					echo JText::_('COM_DJCATALOG2_PLUGIN_SAVE_FIRST');
				} else {
					$fieldSets = $this->form->getFieldsets('params');
					if (empty($fieldSets)) {
						echo JText::_('COM_DJCATALOG2_PLUGIN_EMPTY_CONFIG');
					} else {
						foreach ($fieldSets as $name => $fieldSet) {
							if (isset($fieldSet->description) && trim($fieldSet->description)) {
								echo '<p class="alert alert-info">'.$this->escape(JText::_($fieldSet->description)).'</p>';
							}
							?>
							<?php foreach ($this->form->getFieldset($name) as $field) { ?>
								<div class="control-group">
									<div class="control-label"><?php echo $field->label; ?></div>
									<div class="controls"><?php echo $field->input; ?></div>
								</div>
							<?php } ?>
						<?php } ?>
					<?php } ?>
				<?php } ?>
				
				<?php echo Joomla\CMS\HTML\HTMLHelper::_('uitab.endTab'); ?>
				
				<?php echo Joomla\CMS\HTML\HTMLHelper::_('uitab.endTabSet'); ?>
				
			</div>
		</div>
	</fieldset>
	<div class="clr"></div>
	<input type="hidden" name="task" value="" />
	<?php echo Joomla\CMS\HTML\HTMLHelper::_('form.token'); ?>
</form>

<script type="text/javascript">
(function($){
	$(document).ready(function() {
		var djItemPriceInput = $('#jform_price');
		djItemPriceInput.on('keyup change click', function(){
			djValidatePrice(djItemPriceInput);
		});
		
		if ($('#jform_tax_rule_id')) {
			$('#jform_tax_rule_id').change(function(evt) {
				$('#jform_tax_rule_id').trigger("liszt:updated");
				djValidatePrice(djItemPriceInput);
				//djValidatePrice(djItemSpecialPriceInput);
			});
			
			$('#jform_tax_rule_id').trigger('change');
		}
	});

	function djValidatePrice(priceInput) {
			//var r = new RegExp("\,", "i");
			//var t = new RegExp("[^0-9\,\.]+", "i");
			//priceInput.setProperty('value', priceInput.getProperty('value').replace(r, "."));
			//priceInput.setProperty('value', priceInput.getProperty('value').replace(t, ""));
		
		
			var price = priceInput.val();
			
			// valid format
			var valid_price = new RegExp(/^(\d+|\d+\.\d+)$/);
			
			// comma instead of dot
			var wrong_decimal = new RegExp(/\,/g);
			
			// non allowed characters
			var restricted = new RegExp(/[^\d+\.]/g);
			
			// replace comma with a dot
			price = price.replace(wrong_decimal, ".");
			
			if (valid_price.test(price) == false) {
				// remove illegal chars
				price = price.replace(restricted, '');
			}
			
			if (valid_price.test(price) == false) {
				// too many dots in here
				parts = price.split('.');
				if (parts.length > 2 ) {
					price = parts[0] + '.' + parts[1];
				}
			}
			
			priceInput.val(price);
			
			taxInput = $('#' + priceInput.attr('id') + '_tax');
			if(!taxInput.length) {
				return;
			}
			
			rateInput = $('#jform_tax_rule_id');
			
			if (!rateInput.length) {
				return;
			}
			
			var inputType = taxInput.attr('data-type');
			var taxRateOption = rateInput.find('option:selected').first().text();
			
			parser = new RegExp(/.*\[(.+)\]$/);
			
			if (parser.test(taxRateOption)) {
				taxRate = parseFloat(parser.exec(taxRateOption)[1]);
				if (inputType == 'gross') {
					djPriceFromGross(taxInput, price, taxRate);
				} else if (inputType == 'net') {
					djPriceFromNet(taxInput, price, taxRate);
				}
			}
		}

	function djPriceFromGross(element, price, taxrate) {
		price = parseFloat(price);
		taxrate = parseFloat(taxrate);
		if (!price || !(taxrate >= 0)) {
			element.val('');
			return;
		}

		var netPrice = (price * 100) / (100 + taxrate);
		element.val(netPrice.toFixed(2));
	}

	function djPriceFromNet(element, price, taxrate) {
		price = parseFloat(price);
		taxrate = parseFloat(taxrate);

		if (!price || !(taxrate >= 0)) {
			element.val('');
			return;
		}

		var grossPrice = price * ((100 + taxrate)/100) ;
		element.val(grossPrice.toFixed(2));
	}
})(jQuery);
</script>