<?php
/**
 * Virtuemart Discount table
 *
 * @package 	CSVIVirtueMart
 * @author 		Roland Dalmulder
 * @link 		http://www.csvimproved.com
 * @copyright 	Copyright (C) 2006 - 2012 RolandD Cyber Produksi
 * @license 	GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 * @version 	$Id: vm_product_discount.php 1892 2012-02-11 11:01:09Z RolandD $
 */

// No direct access
defined('_JEXEC') or die('Restricted access');

/**
* @package CSVIVirtueMart
 */
class TableVm_product_discount extends JTable {
	
	// Sets whether the database columns have been loaded
	private $_loaded = false;

	/**
	* @param database A database connector object
	 */
	public function __construct($db) {
		$this->reset();
		parent::__construct('#__vm_product_discount', 'discount_id', $db );
	}
	
	/**
	* Resets the default properties
	* @return	void
	 */
	function reset() {
		if (!$this->_loaded) {
			$this->setProperties(CsvivirtuemartModelAvailablefields::DbFields('vm_product_discount'));
			$this->_loaded = true;
		}
		else {
			$class_vars = get_class_vars(get_class($this));
			foreach ($this as $name => $value) {
				if (substr($name, 0, 1) != '_') {
					$this->$name = null;
				}
			}
		}
	}
	
	/**
	* Check if a discount already exists. If so, retrieve the discount ID
	 */
	public function check() {
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');
		if ($this->amount) {
			// Check if the amount exists in the database
			$q_discount = "SELECT COUNT(discount_id) AS total_discount_ids 
						FROM #__vm_product_discount 
						WHERE amount = '".$this->amount."' ";
			$q_discount .= "AND is_percent = '".$this->is_percent."' ";
			$q_discount .= "AND start_date = '".$this->start_date."' ";
			$q_discount .= "AND end_date = '".$this->end_date."'";
			$db->setQuery($q_discount);
			$db->query();
			$csvilog->addDebug('COM_CSVIVIRTUEMART_CHECK_DISCOUNT_EXISTS', true);
			// There are multiple discount ids, we take the first one
			if ($db->loadResult() > 0) {
				$q_discount = "SELECT MIN(discount_id) AS discount_id 
							FROM #__vm_product_discount 
							WHERE amount = '".$this->amount."' ";
				$q_discount .= "AND is_percent = '".$this->is_percent."' ";
				$q_discount .= "AND start_date = '".$this->start_date."' ";
				$q_discount .= "AND end_date = '".$this->end_date."'";
				$db->setQuery($q_discount);
				$discount_id = $db->loadResult();
				$csvilog->addDebug(JText::sprintf('COM_CSVIVIRTUEMART_USE_DISCOUNT_ID', $discount_id));
				$this->setValue('discount_id', $discount_id);
			}
			else $this->setValue('discount_id', 0);
		}
		return true;
	}
	
	/**
	* Set a value for the class
	 */
	public function setValue($field, $value) {
		$this->$field = $value;
	}
	
	/**
	* Get a value from the class
	 */
	public function getValue($field) {
		return $this->$field;
	}
}
?>