<?php
/**
 * Virtuemart Product Review 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_reviews.php 1892 2012-02-11 11:01:09Z RolandD $
 */

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

/**
 * @package CSVIVirtueMart
 */
class TableVm_product_reviews extends JTable {
	
	// Sets whether the database columns have been loaded
	private $_loaded = false;
	
	/**
	* @param database A database connector object
	 */
	function __construct($db) {
		$this->reset();
		parent::__construct('#__vm_product_reviews', 'review_id', $db );
	}
	
	/**
	* 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;
	}
	
	/**
	* Resets the default properties
	* @return	void
	 */
	public function reset() {
		if (!$this->_loaded) {
			$this->setProperties(CsvivirtuemartModelAvailablefields::DbFields('vm_product_reviews'));
			$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;
				}
			}
		}
	}
	
	/**
	 * Store the product review 
	 * 
	 * @copyright 
	 * @author		RolandD 
	 * @todo 
	 * @see 
	 * @access 		public
	 * @param 
	 * @return 		bool	true on success | false on failure
	 * @since 		3.0
	 */
	public function store() {
		$db = JFactory::getDBO();
		
		if($this->check()) {
			$ret = $db->updateObject( $this->_tbl, $this, $this->_tbl_key, false );
		}
		else {
			$ret = $db->insertObject( $this->_tbl, $this, $this->_tbl_key );
		}
		if(!$ret) {
			$this->setError(get_class( $this ).'::store failed - '.$db->getErrorMsg());
			return false;
		}
		else  return true;
	}
	
	/**
	 * Check if there is already an existing review by the user 
	 * 
	 * @copyright 
	 * @author 		RolandD
	 * @todo 
	 * @see 
	 * @access 		public
	 * @param 
	 * @return 
	 * @since 		3.0
	 */
	 public function check() {
	 	// See if we already have review id
		if (empty($this->review_id)) {
			$db = JFactory::getDBO();
			$csvilog = JRequest::getVar('csvilog');
			
			// Check if a record already exists in the database
			$q = "SELECT ".$this->_tbl_key."
				FROM ".$this->_tbl."
				WHERE product_id = '".$this->product_id."'
				AND userid = ".$this->userid;
			$db->setQuery($q);
			$db->query($q);
			$csvilog->addDebug(JText::_('COM_CSVIVIRTUEMART_CHECK_REVIEW_EXISTS'), true);
			if ($db->getAffectedRows() > 0) {
				$this->review_id = $db->loadResult();
				return true;
			}
			else {
				// There is no entry yet, so we must insert a new one
				return false;
			}
		}
		// There is already a reviewid
		else return true;
	 }
}
?>