<?php
/**
 * @version		$Id: samples.php 132 2009-06-23 07:25:22Z eddieajau $
 * @copyright	Copyright (C) 2009 New Life in IT Pty Ltd. All rights reserved.
 * @license		GNU General Public License <http://www.gnu.org/copyleft/gpl.html>
 * @link		http://www.theartofjoomla.com
 */

// no direct access
defined('_JEXEC') or die;

jimport('joomla.application.component.model');

/**
 * Setup Model
 *
 * @package		TAOJ.Quanta
 * @subpackage	com_quanta
 */
class QuantaModelSamples extends JModel
{
	/**
	 * Method to add sample data.
	 *
	 * @return	boolean	True on success, false otherwise and internal error set.
	 */
	public function add()
	{
		jimport('joomla.filesystem.file');

		$file = JPath::clean(JPATH_COMPONENT.'/install/samples.mysql.utf8.php');

		if (JFile::exists($file))
		{
			try
			{
				// Get the database object.
				$db = &$this->_db;

				// Set the samples SQL from the file.
				$db->setQuery(JFile::read($file));

				// Execute the upgrade SQL.
				$return = $db->queryBatch(false);

				// Check for a database error.
				if ($db->getErrorNum()) {
					throw new Exception($db->getErrorMsg());
				}

				// Get the ID of the samples category
				$db->setQuery(
					'SELECT id' .
					' FROM #__categories' .
					' WHERE alias = '.$db->quote('samples') .
					'  AND section = '.$db->quote('com_quanta')
				);
				if ($categoryId = $db->loadResult())
				{
					$db->setQuery(
						'UPDATE #__taoj_quanta_charts' .
						' SET category_id = '.(int) $categoryId .
						' WHERE alias LIKE '.$db->quote('sample-%')
					);
					if (!$db->query()) {
						throw new Exception($db->getErrorMsg());
					}
				}
				else if ($db->getErrorNum()) {
					throw new Exception($db->getErrorMsg());
				}
			}
			catch (Exception $e)
			{
				$this->setError($e->getMessage());
				return false;
			}
		}

		return true;
	}

	/**
	 * Method to remove sample data.
	 *
	 * @return	boolean	True on success, false otherwise and internal error set.
	 */
	public function remove()
	{
		try
		{
			// Get the database object.
			$db = &$this->_db;

			$db->setQuery(
				'DELETE FROM #__categories' .
				' WHERE alias LIKE '.$db->quote('samples') .
				'  AND section = '.$db->quote('com_quanta')
			);

			if (!$db->query()) {
				throw new Exception($db->getErrorMsg());
			}

			$db->setQuery(
				'DELETE FROM #__taoj_quanta_charts' .
				' WHERE alias LIKE '.$db->quote('sample-%')
			);
			if (!$db->query()) {
				throw new Exception($db->getErrorMsg());
			}
		}
		catch (Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}

		return true;
	}

}