<?php
/**
* @version 1.0.0
* @package RSFiles! 1.0.0
* @copyright (C) 2009 www.rsjoomla.com
* @license GPL, http://www.gnu.org/copyleft/gpl.html
*/

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


class RsfilesControllerGroups extends rsfilesController
{
	/**
	 * constructor (registers additional tasks to methods)
	 * @return void
	 */
	function __construct()
	{
		parent::__construct();

		// Register Extra tasks
		$this->registerTask('apply' ,  'save');
	}

	/**
	 * save a record (and redirect to main page)
	 * @return void
	 */
	function save()
	{
		$db = JFactory::getDBO();
		$model = $this->getModel('groups');
		$post=JRequest::get('post',JREQUEST_ALLOWRAW);
		$Acls = implode(',',$post['GroupAcl']);
		$IdUsers = implode(',',$post['addusers']);
		
		$row= & JTable::getInstance('Rsfiles_Groups','Table');
		
		if(!$row->bind($post)) {
			return JError::raiseWarning(500, $row->getError());
		}

		if ($row->store()) 
		{
			$msg = JText::_('RSFL_GROUP_SAVED' );
			
			$db->setQuery("SELECT IdGroupDetail FROM #__rsfiles_group_details WHERE IdGroup = ".$row->IdGroup);
			$IdGroupDetail = $db->loadResult();
			
			if(empty($IdGroupDetail))
				$db->setQuery("INSERT INTO #__rsfiles_group_details SET IdGroup = ".$row->IdGroup." , IdAcls = '".$Acls."' , IdUsers = '".$IdUsers."' ");
			else
				$db->setQuery("UPDATE #__rsfiles_group_details SET IdAcls = '".$Acls."' , IdUsers = '".$IdUsers."' WHERE IdGroup =".$row->IdGroup);
			$db->query();
			
			
		} else {
			JError::raiseWarning(500, $row->getError());

			$msg = JText::_('RSFL_GROUP_ERROR_SAVING' );
		}
		switch(JRequest::getCmd('task'))
		{
			case 'apply' :
					$link = 'index.php?option=com_rsfiles&task=editgroup&cid='.$row->IdGroup;

			break;
			
			case 'save' :
					$link = 'index.php?option=com_rsfiles&task=groups';

			break;
		}
		// redirect after saving
		$this->setRedirect($link, $msg);
	}

	/**
	 * remove record(s)
	 * @return void
	 */
	function remove()
	{
		$db = JFactory::getDBO();
		$model = $this->getModel('groups');
		$row =& JTable::getInstance('Rsfiles_Groups','Table');
		$cids=JRequest::getVar('cid',array(0),'post','array');
		
		if(!empty($cids))
		{
			foreach($cids as $cid) 
			{
				if(!$row->delete($cid)) {
					$msg = JText::_('RSFL_GROUP_ERROR_DELETING' );
				} else {
					$db->setQuery("DELETE FROM #__rsfiles_group_details WHERE IdGroup = ".$cid);
					$db->query();
					$msg = JText::_( 'RSFL_GROUP_DELETED' );
				}
			}
		} else
		{
			$msg = JText::_('RSFL_SELECT_GROUP' );
		}
		$this->setRedirect( 'index.php?option=com_rsfiles&task=groups', $msg ); 
	}

	/**
	 * cancel editing a record
	 * @return void
	 */
	function cancel()
	{
		$this->setRedirect( 'index.php?option=com_rsfiles&task=groups', JText::_('RSFL_CANCEL' ) );
	}	
}