<?php
/**
 * Virtuemart orders table
 *
 * @package 	CSVIVirtueMart
 * @subpackage 	Tables
 * @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_orders.php 1892 2012-02-11 11:01:09Z RolandD $
 */

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

/**
 * @package CSVIVirtueMart
 * @subpackage Tables
 */
class TableVm_orders 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_orders', 'order_id', $db );
	}
	
	/**
	* Resets the default properties
	* @return	void
	*/
	function reset() {
		if (!$this->_loaded) {
			$this->setProperties(CsvivirtuemartModelAvailablefields::DbFields('vm_orders'));
			$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 order
	*
	* @author RolandD
	* @since 2.3.10
	* @access public 
	* @return bool true|false on result of query 
	*/
	public function store() {
		$db = JFactory::getDBO();
		$check = $this->check();

		if($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 the order ID already exists. If yes, do an update, otherwise so an insert 
	 * 
	 * @copyright 
	 * @author 		RolandD
	 * @todo 
	 * @see 
	 * @access 		public
	 * @param 
	 * @return 		bool 	true if order exists | false if order does not exist
	 * @since 		2.3.10
	 */
	public function check() {
		if (!empty($this->order_id)) {
			$db = JFactory::getDBO();
			$csvilog = JRequest::getVar('csvilog');
			
			// Check if the attribute in the database
			$q = "SELECT ".$this->_tbl_key."
				FROM ".$this->_tbl."
				WHERE order_id = ".$this->order_id;
			$db->setQuery($q);
			$db->query($q);
			$csvilog->addDebug(JText::_('DEBUG_CHECK_ORDER_EXISTS'), true);
			if ($db->getAffectedRows() > 0) return true;
			else return false;
		}
		else return false;
	}
}
?>