<?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
 */

defined('_JEXEC') or die();
defined('JPATH_BASE') or die;

jimport('joomla.html.html');
jimport('joomla.form.formfield');

require_once JPATH_ROOT.'/components/com_djcatalog2/helpers/price.php';
require_once JPATH_ROOT.'/components/com_djcatalog2/helpers/html.php';

class JFormFieldDjcdelivery extends JFormField {
	
	protected $type = 'Djcdelivery';
	
	protected function getInput()
	{
		$html = array();
		
		$app = JFactory::getApplication();
		$input = $app->input;

		// Initialize some field attributes.
		$class     = !empty($this->class) ? ' class="radio ' . $this->class . '"' : ' class="radio"';
		$required  = $this->required ? ' required aria-required="true"' : '';
		$autofocus = $this->autofocus ? ' autofocus' : '';
		$disabled  = $this->disabled ? ' disabled' : '';
		$readonly  = $this->readonly;
		
		$params = JComponentHelper::getParams('com_djcatalog2');
		$basket = Djcatalog2HelperCart::getInstance(true);
		$total = $basket->getProductTotal();
		
		$tax_already_incl = (bool)($params->get('price_including_tax', 1) == 1);
		
		//TODO - parameter
		$displayPrices = true;

		// Start the radio field output.
		$html[] = '<fieldset id="' . $this->id . '"' . $class . $required . $autofocus . $disabled . ' >';
		//$required = '';
		
		// Get the field options.
		$options = $this->getOptions();
		
		if (empty($options) && $app->isClient('site') && $input->getCmd('option') == 'com_djcatalog2' && ($input->getCmd('view') == 'cart' || $input->getCmd('view') == 'checkout' )) {
			//$app->enqueueMessage(JText::_('COM_DJCATALOG2_NOTICE_DELIVERY_OPTIONS_EMPTY'), 'notice');
			
			return '<div class="alert alert-notice">'.JText::_('COM_DJCATALOG2_NOTICE_DELIVERY_OPTIONS_EMPTY').'</div>';
		}

		// Build the radio field output.
		foreach ($options as $i => $option)
		{
			
			// Initialize some option attributes.
			$checked = ((string) $option->value == (string) $this->value || count($options) == 1) ? ' checked="checked"' : '';
			$class = !empty($option->class) ? ' class="' . $option->class . '"' : '';

			$disabled = !empty($option->disable) || ($readonly && !$checked);

			$disabled = $disabled ? ' disabled' : '';

			// Initialize some JavaScript option attributes.
			$onclick = !empty($option->onclick) ? ' onclick="' . $option->onclick . '"' : '';
			$onchange = !empty($option->onchange) ? ' onchange="' . $option->onchange . '"' : '';
			
			/*$lblText = $option->text;
			if ($displayPrices && $option->price > 0.0) {
				$price = ($option->free_amount > 0 && $option->free_amount <= $total['gross']) ? 0.0 : $option->price;
				$prices = Djcatalog2HelperPrice::getCartPrices($price, $price, $option->tax_rule_id, false,  1, $params);
				$priceText = strip_tags(DJCatalog2HtmlHelper::formatPrice($prices['base']['display'], $params));
				$lblText .= ' ('.$priceText.')';
			}*/
			
			$html[] = '<label for="' . $this->id . $i . '"' . $class . ' >';
			
			$html[] = '<input type="radio" id="' . $this->id . $i . '" name="' . $this->name . '" value="'
				. htmlspecialchars($option->value, ENT_COMPAT, 'UTF-8') . '"' . $checked . $class . $required . $onclick
				. $onchange . $disabled . ' data-shippment="'.(int)$option->shippment.'" '.$option->attributes.' />';
			
			$html[] = '<span class="djc_delivery_option">';
			
			if (trim($option->image) != '') {
				$html[] = '<img class="djc_delivery_option-image" src="' . ($option->image) .'" alt="'.htmlspecialchars($option->text).'" />';
			}
			
			$html[] = '<span class="djc_delivery_option-title">'
				. JText::alt($option->text, preg_replace('/[^a-zA-Z0-9_\-]/', '_', $this->fieldname))
				.'</span>';

			if (trim($option->short_description) != '') {
				$html[] = '<span class="djc_delivery_option-description">' . nl2br($option->short_description) .'</span>';
			}
			
			if ($displayPrices && ($option->price > 0.0 || $option->additional_fee > 0)) {
				
				$fee = 0;
				if ($option->additional_fee > 0) {
					if ($tax_already_incl) {
						$fee = round(($option->additional_fee * $total ['gross'])/100,2);
					} else {
						$fee = round(($option->additional_fee * $total ['net'])/100,2);
					}
				}
				
				$price = ($option->free_amount > 0 && $option->free_amount <= $total['gross']) ? 0.0 : $option->price + $fee;
				$prices = Djcatalog2HelperPrice::getCartPrices($price, $price, $option->tax_rule_id, false,  1, $params);
				$priceText = strip_tags(DJCatalog2HtmlHelper::formatPrice($prices['base']['display'], $params));
				$html[] = '<span class="djc_delivery_option-price">'.$priceText.'</span>';
			}
			
			$html[] = '</span>';
			$html[] = '</label>';
			
		}

		// End the radio field output.
		$html[] = '</fieldset>';
		
		return implode($html);
	}
	
	protected function getOptions()
	{
		$app = JFactory::getApplication();
		$user = JFactory::getUser();
		
		$options = array();
		
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);
		$query->select('*')->from('#__djc2_delivery_methods');
		if (!$app->isClient('administrator') && !$user->authorise('djcatalog2.salesman', 'com_djcatalog2')) {
			$user = JFactory::getUser();
			$userGroups = implode(',', $user->getAuthorisedViewLevels());
			
			$query->where('published=1');
			$query->where('access IN ('.$userGroups.')');
		}
		$query->order('ordering asc');
		
		$db->setQuery($query);
		$rows = $db->loadObjectList('id');
		
		$query = $db->getQuery(true);
		$query->select('*')->from('#__djc2_deliveries_gauges');
		$db->setQuery($query);
		$gauges = $db->loadObjectList();
		
		if (count($gauges) > 0) {
			foreach($gauges as $gauge) {
				if (!isset($rows[$gauge->delivery_id])) continue;
				if (!isset($rows[$gauge->delivery_id]->gauges)) {
					$rows[$gauge->delivery_id]->gauges = [];
				}
				
				$rows[$gauge->delivery_id]->gauges[] = $gauge->gauge_id;
			}
		}

		$optOptions = array(
			'attr' => null,
			'disable' => false,
			'option.attr' => null,
			'option.disable' => 'disable',
			'option.key' => 'value',
			'option.label' => null,
			'option.text' => 'text'
		);
		
		$basket = Djcatalog2HelperCart::getInstance(true);
		$totalWeight = $basket->getTotalWeight();
		
		$gaugesMap = $basket->getGaugesMap();
		$requiredGauges = count($gaugesMap) ? array_keys($gaugesMap) : [];
		
		foreach ($rows as $option)
		{
			$minWeight =  DJCatalog2HelperQuantity::convertWeigthUnit($option->min_weight, $option->weight_unit, 'G');
			$maxWeight = DJCatalog2HelperQuantity::convertWeigthUnit($option->max_weight, $option->weight_unit, 'G');
			
			if (/*$totalWeight > 0.0000 &&*/ ($option->min_weight != 0 || $option->max_weight > 0)) {
				if ($minWeight > $totalWeight || $maxWeight < $totalWeight) {
					continue;
				}
			}
			
			if (!empty($requiredGauges) && !empty($option->gauges)) {
				$missing = array_diff($requiredGauges, $option->gauges);
				if (count($missing) > 0) {
					continue;
				}
			}
			
			$disabled = false;
			
			$optOptions['option.attr'] = 'attributes';
			$attr = array (
				'countries' => $option->countries ? explode(',', $option->countries) : array(),
				'postcodes' => $option->postcodes ? explode('|', $option->postcodes, 2) : array(),
				'min_weight' => $minWeight,
				'max_weight' => $maxWeight
			);
			
			$optOptions['attr'] = 'data-options=\''.json_encode($attr).'\'';
			
			// Create a new option object based on the <option /> element.
			$tmp = Joomla\CMS\HTML\HTMLHelper::_(
				'select.option', (string) $option->id, trim((string) $option->name), $optOptions, 'text',
				$disabled
			);

			// Set some option attributes.
			$tmp->class = 'djc_delivery_method';
			
			$tmp->shippment = $option->shipping_details;
			$tmp->price = $option->price;
			$tmp->free_amount = $option->free_amount;
			$tmp->tax_rule_id = $option->tax_rule_id;
			$tmp->image = $option->image;
			$tmp->short_description = $option->short_description;
			$tmp->description = $option->description;
			$tmp->additional_fee = $option->additional_fee;

			// Set some JavaScript option attributes.
			//$tmp->onclick = (string) $option['onclick'];
			//$tmp->onchange = (string) $option['onchange'];

			// Add the option object to the result set.
			$options[] = $tmp;
		}

		reset($options);

		return $options;
	}
}
?>