<?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 rsfilesControllerLicenses extends rsfilesController
{
	/**
	 * constructor (registers additional tasks to methods)
	 * @return void
	 */
	function __construct()
	{
		parent::__construct();

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

	/**
	 * save a record (and redirect to main page)
	 * @return void
	 */
	function save()
	{
		$model = $this->getModel('licenses');
		$post=JRequest::get('post',JREQUEST_ALLOWRAW);
		
		$row= & JTable::getInstance('Rsfiles_Licenses','Table');
		
		if(!$row->bind($post)) {
			return JError::raiseWarning(500, $row->getError());
		}

		if ($row->store()) {
			$msg = JText::_('RSFL_LIC_SAVED' );
		} else {
			JError::raiseWarning(500, $row->getError());

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

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

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

	/**
	 * remove record(s)
	 * @return void
	 */
	function remove()
	{
		$model = $this->getModel('licenses');
		$row =& JTable::getInstance('Rsfiles_Licenses','Table');
		$cids=JRequest::getVar('cid',array(0),'post','array');
		
		if(!empty($cids))
		{
			foreach($cids as $cid) 
			{
				if(!$row->delete($cid)) {
					$msg = JText::_('RSFL_LIC_ERROR_DELETE' );
				} else {
					$row->reorder();
					$msg = JText::_( 'RSFL_LIC_DELETED' );
				}
			}
		} else
		{
			$msg = JText::_('RSFL_SELECT_LIC' );
		}
		$this->setRedirect( 'index.php?option=com_rsfiles&task=licenses', $msg ); 
	}

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

		$db 	=& JFactory::getDBO();

		$cid		= JRequest::getVar( 'cid', array(), '', 'array' );
		$publish	= ( $this->getTask() == 'publish' ? 1 : 0 );

		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1)
		{
			$action = $publish ? 'publish' : 'unpublish';
			JError::raiseError(500, JText::_('RSFL_LIC_ERROR_PUBLISH'.' '.$action, true ) );
		}

		$cids = implode( ',', $cid );
		
		$query = 'UPDATE #__rsfiles_licenses'
		. ' SET published = ' . (int) $publish
		. ' WHERE IdLicense IN ( '. $cids .' )'
		;
		$db->setQuery( $query );
		if (!$db->query())
		{
			JError::raiseError(500, $db->getErrorMsg() );
		}

		$mainframe->redirect( 'index.php?option=com_rsfiles&task=licenses' );
	}	
}