<?php
/**
 * @version		$Id: record.php 134 2009-06-24 05:52:18Z 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.controller');

/**
 * @package		TAOJ.Quanta
 * @subpackage	com_quanta
 */
class QuantaControllerRecord extends JController
{
	/**
	 * Constructor
	 */
	function __construct()
	{
		parent::__construct();

		$this->registerTask('save2copy',	'save');
		$this->registerTask('save2new',		'save');
		$this->registerTask('apply',		'save');
	}

	/**
	 * Display the view
	 */
	function display()
	{
	}

	/**
	 * Proxy for getModel
	 */
	function &getModel()
	{
		return parent::getModel('Record', '', array('ignore_request' => true));
	}

	/**
	 * Method to edit a object
	 *
	 * Sets object ID in the session from the request, checks the item out, and then redirects to the edit page.
	 *
	 * @access	public
	 * @return	void
	 */
	function edit()
	{
		// Initialize variables.
		$app	= &JFactory::getApplication();
		$pks	= JRequest::getVar('cid', array(), '', 'array');

		// Get the id of the group to edit.
		$pk =  (empty($pks) ? JRequest::getInt('record_id') : (int) array_pop($pks));

		// Get the current row id.
		$app->setUserState('com_quanta.edit.record.id', $pk);

		// Get the model.
		$model = &$this->getModel();

		// Check that this is not a new chart.
		if ($pk > 0)
		{
			$item = $model->getItem($pk);

			// If not already checked out, do so.
			if ($item->checked_out == 0)
			{
				if (!$model->checkout($pk))
				{
					// Check-out failed, go back to the list and display a notice.
					$message = JText::sprintf('JError_Checkout_failed', $model->getError());
					$this->setRedirect('index.php?option=com_quanta&view=records', $message, 'error');
					return false;
				}
			}
		}

		// Check-out succeeded, push the new row id into the session.
		$app->setUserState('com_quanta.edit.record.id',		$pk);
		$app->setUserState('com_quanta.edit.record.data',	null);

		$this->setRedirect('index.php?option=com_quanta&view=record&layout=edit');

		return true;
	}

	/**
	 * Method to cancel an edit
	 *
	 * Checks the item in, sets item ID in the session to null, and then redirects to the list page.
	 *
	 * @access	public
	 * @return	void
	 */
	function cancel()
	{
		// Checkin item if checked out
		$app = &JFactory::getApplication();
		if ($id = (int) $app->getUserState('com_quanta.edit.record.id')) {
			$model = $this->getModel();
			$model->checkin($id);
		}

		// Clear the session of the item
		$app->setUserState('com_quanta.edit.record.id', null);

		$this->setRedirect(JRoute::_('index.php?option=com_quanta&view=records', false));
	}

	/**
	 * Save the record
	 */
	function save()
	{
		// Check for request forgeries.
		JRequest::checkToken();

		$app	= &JFactory::getApplication();
		$model	= &$this->getModel();
		$task	= $this->getTask();

		// Get posted form variables.
		$data		= JRequest::getVar('jxform', array(), 'post', 'array');

		// Populate the row id from the session.
		$data['id'] = (int) $app->getUserState('com_quanta.edit.record.id');

		unset($data['created_time']);
		unset($data['created_user_id']);
		unset($data['modified_time']);
		unset($data['modified_user_id']);
		unset($data['latest_time']);
		unset($data['latest_value']);
		unset($data['latest_value2']);

		// Inject the parameters element.
		$data['params']	= JRequest::getVar('jxformparams',	array(), 'post', 'array');

		// Get the form model object and validate it.
		$form	= &$model->getForm('model');
		$form->filter($data);
		$result	= $form->validate($data);

		if (JError::isError($result))
		{
			// Get the validation messages.
			$errors	= $form->getErrors();

			// Push up to three validation messages out to the user.
			for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++)
			{
				if (JError::isError($errors[$i])) {
					$app->enqueueMessage($errors[$i]->getMessage(), 'notice');
				}
				else {
					$app->enqueueMessage($errors[$i], 'notice');
				}
			}

			// Save the data in the session.
			$app->setUserState('com_quanta.edit.record.data', $data);

			// Redirect back to the edit screen.
			$this->setRedirect(JRoute::_('index.php?option=com_quanta&view=record&layout=edit', false));
			return false;
		}

		// Attempt to save the data.
		if (!$model->save($data))
		{
			// Save the data in the session.
			$app->setUserState('com_quanta.edit.record.data', $data);

			// Redirect back to the edit screen.
			$this->setMessage(JText::sprintf('JError_Save_failed', $model->getError()), 'notice');
			$this->setRedirect(JRoute::_('index.php?option=com_quanta&view=record&layout=edit', false));
			return false;
		}

		// Save succeeded, check-in the row.
		if (!$model->checkin())
		{
			// Check-in failed, go back to the row and display a notice.
			$message = JText::sprintf('JError_Checkin_saved', $model->getError());
			$this->setRedirect('index.php?option=com_quanta&view=record&layout=edit', $message, 'error');
			return false;
		}

		$this->setMessage(JText::_('JController_Save_success'));

		// Redirect the user and adjust session state based on the chosen task.
		switch ($task)
		{
			case 'apply':
				// Set the row data in the session.
				$app->setUserState('com_quanta.edit.record.id',	$model->getState('record.id'));
				$app->setUserState('com_quanta.edit.record.data',	null);

				// Redirect back to the edit screen.
				$this->setRedirect(JRoute::_('index.php?option=com_quanta&view=record&layout=edit', false));
				break;

			case 'save2new':
				// Clear the row id and data in the session.
				$app->setUserState('com_quanta.edit.record.id',	null);
				$app->setUserState('com_quanta.edit.record.data',	null);

				// Redirect back to the edit screen.
				$this->setRedirect(JRoute::_('index.php?option=com_quanta&view=record&layout=edit', false));
				break;

			default:
				// Clear the row id and data in the session.
				$app->setUserState('com_quanta.edit.record.id',	null);
				$app->setUserState('com_quanta.edit.record.data',	null);

				// Redirect to the list screen.
				$this->setRedirect(JRoute::_('index.php?option=com_quanta&view=records', false));
				break;
		}


	}

	/**
	 * Removes an item
	 */
	function delete()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit(JText::_('JInvalid_token'));

		// Get items to remove from the request.
		$cid	= JRequest::getVar('cid', array(), '', 'array');

		if (!is_array($cid) || count($cid) < 1) {
			JError::raiseWarning(500, JText::_('Select an item to delete'));
		}
		else {
			// Get the model.
			$model = $this->getModel();

			// Make sure the item ids are integers
			jimport('joomla.utilities.arrayhelper');
			JArrayHelper::toInteger($cid);

			// Remove the items.
			if (!$model->delete($cid)) {
				JError::raiseWarning(500, $model->getError());
			}
		}

		$this->setRedirect('index.php?option=com_quanta&view=records');
	}

	/**
	 * Method to publish a list of taxa
	 *
	 * @access	public
	 * @return	void
	 * @since	1.0
	 */
	function publish()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit(JText::_('JInvalid_token'));

		// Get items to publish from the request.
		$cid	= JRequest::getVar('cid', array(), '', 'array');
		$values	= array('publish' => 1, 'unpublish' => 0, 'trash' => -2);
		$task	= $this->getTask();
		$value	= JArrayHelper::getValue($values, $task, 0, 'int');

		if (!is_array($cid) || count($cid) < 1) {
			JError::raiseWarning(500, JText::_('Select an item to publish'));
		}
		else {
			// Get the model.
			$model	= $this->getModel();

			// Make sure the item ids are integers
			JArrayHelper::toInteger($cid);

			// Publish the items.
			if (!$model->publish($cid, $value)) {
				JError::raiseWarning(500, $model->getError());
			}
		}

		$this->setRedirect('index.php?option=com_quanta&view=records');
	}

	/**
	 * Changes the order of an item
	 */
	function ordering()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit(JText::_('JInvalid_token'));

		$cid	= JRequest::getVar('cid', null, 'post', 'array');
		$inc	= $this->getTask() == 'orderup' ? -1 : +1;

		$model = & $this->getModel();
		$model->ordering($cid, $inc);

		$this->setRedirect('index.php?option=com_quanta&view=records');
	}
}