<?php
/**
 * @package     Cherry Picker for HikaShop
 * @subpackage  Prices
 * @author		Maksym Stefanhuck
 * @copyright   Copyright (C) 2009 - 2014 Galt.md. All rights reserved.
 * @license     GNU General Public License version 2 or later; see COPYING.txt
 */

defined('_JEXEC') or die('Restricted access');

//require_once(dirname(__FILE__) .'/../helpers/fsschema.php');
require_once(dirname(__FILE__) ."/../defines.php");

class CPPrices {
	private $_selected_min = 0;
	private $_selected_max = 0;
	private $_min = 0;
	private $_max = 0;
	private $_available_min = 0;
	private $_available_max = 0;
	private $_sql_joins = array();
	private $_sql_wheres = array();
	private $_config = array();


	function __construct($options = array()) {
		$defaults = array(
			"include_taxes" => false
		);
		$config = array_merge($defaults, $options);
		$this->_config = $config;

		$min = $this->validate(JRequest::getVar('low-price', 0));
		$max = $this->validate(JRequest::getVar('high-price', 0));
		if ( !($max && $min && $max < $min)) {
			$this->_selected_min = $min;
			$this->_selected_max = $max;
		}
	}

	public function selectedMin() {
		return $this->_selected_min;
	}

	public function selectedMax() {
		return $this->_selected_max;
	}


	public function sqlJoins($on_table = 'p') {
		if ($this->_sql_joins)
			return $this->_sql_joins;

		$min = $this->_selected_min;
		$max = $this->_selected_max;
		$joins = array();
		if ($min || $max) {
			$joins[] = "JOIN `#__hikashop_price` as price".
				" ON ". $on_table .".`product_id`=price.`price_product_id`";

			if ($this->_config['include_taxes']) {
				$joins[] = "LEFT JOIN `#__hikashop_category` as c_tax ON $on_table.`product_tax_id`=c_tax.`category_id`";
				$joins[] = "LEFT JOIN `#__hikashop_taxation` as taxation ON c_tax.`category_namekey`=taxation.`category_namekey`";
				$joins[] = "LEFT JOIN `#__hikashop_tax` as tax ON taxation.`tax_namekey`=tax.`tax_namekey`";
			}

			$this->_sql_joins = $joins;
		}
		return $joins;
	}


	public function sqlWheres() {
		if ($this->_sql_wheres)
			return $this->_sql_wheres;

		$min = $this->_selected_min;
		$max = $this->_selected_max;
		$wheres = array();
		if ($min || $max) {
			$column = $this->_config['include_taxes'] ?
				"price.`price_value` * (1 + `tax_rate`)" :
				"price.`price_value`";

			if ($min && $max) {
				$wheres[] = ($min == $max) ? "$column=$min" :
							"$column BETWEEN $min AND $max";
			} else {
				$wheres[] = ($min) ? "$column>=$min" : "$column<=$max";
			}

			$this->_sql_wheres = $wheres;
		}
		return $wheres;
	}


	private function validate($value) {
		// not empty or not -X or 0
		if ( !$value || $value <= 0)
			return 0;
		// change , with .
		$value = str_replace(',','.',$value);
		if (! is_numeric($value))
			return 0;
		// remove leading/trailing zeros
		$value += 0;

		return $value;
	}
}
?>
