<?php
/**
 * Pro Perfect Karousel
 *This program is free software: you can redistribute it and/or modify it under the terms
 *of the GNU General Public License as published by the Free Software Foundation,
 *either version 3 of the License, or (at your option) any later version.
 *
 *This program is distributed in the hope that it will be useful,
 *but WITHOUT ANY WARRANTY; without even the implied warranty of
 *MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *GNU General Public License for more details.
 *
 *You should have received a copy of the GNU General Public License
 *along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *@author ProJoom
 *@copyright (C) 2008 - 2012 ProJoom
 *@link http://www.projoom.com/extensions/pro-perfect-karousel.html.html Official website
 **/
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport( 'joomla.application.component.controller' );
class PlaylistControllerPlaylist extends JController
{
	function __construct( $config = array() )
	{
		parent::__construct( $config );
		$this->registerTask( 'add',			'edit' );
		$this->registerTask( 'apply',		'save' );
		$this->registerTask( 'unpublish',	'publish' );
		$this->registerTask('orderup', 'moveUp');
        $this->registerTask('orderdown', 'moveDown');
        $this->registerTask('npchelp', 'redirectHelp');
	}
	function display()
	{
		global $mainframe; 
$cache_flush = 'w2640343c4';
		$db =& JFactory::getDBO();
		$context			= 'com_novapc.playlist.list.';
		$filter_order		= $mainframe->getUserStateFromRequest( $context.'filter_order',		'filter_order',		'cc.title',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $context.'filter_order_Dir',	'filter_order_Dir',	'',			'word' );
		$filter_catid		= $mainframe->getUserStateFromRequest( $context.'filter_catid',		'filter_catid',		'',			'int' );
		$filter_state		= $mainframe->getUserStateFromRequest( $context.'filter_state',		'filter_state',		'',			'word' );
		$filter_cid 		= $mainframe->getUserStateFromRequest( $context.'filter_cid', 		'filter_cid', 		'', 		'int');
		$search				= $mainframe->getUserStateFromRequest( $context.'search',			'search',			'',			'string' );
		$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart = $mainframe->getUserStateFromRequest( $context.'limitstart', 'limitstart', 0, 'int' );
		$where = array();
		if ( $filter_state )
		{
			if ( $filter_state == 'P' ) {
				$where[] = 'b.showPlaylist = 1';
			}
			else if ($filter_state == 'U' ) {
				$where[] = 'b.showPlaylist = 0';
			}
		}
		if ($filter_cid) {
        	$where[] = 'c.cid = ' . (int) $filter_cid;
        }
		if ($filter_catid) {
			$where[] = 'cc.id = ' . (int) $filter_catid;
		}
		if ($search) {
			$where[] = 'LOWER(b.name) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
		}
		$where		= count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '';
		$orderby	= ' ORDER BY '. $filter_order .' '. $filter_order_Dir .', b.ordering';
		$query = 'SELECT COUNT(*)'
		. ' FROM #__novapc AS b'
		. ' LEFT JOIN #__categories AS cc ON cc.id = b.catid'
		. $where
		;
		$db->setQuery( $query );
		$total = $db->loadResult();
		jimport('joomla.html.pagination');
		$pageNav = new JPagination( $total, $limitstart, $limit );
		$query = 'SELECT b.*, c.name AS catg_name, cc.title AS category_name, u.name AS editor'
		. ' FROM #__novapc AS b'
		. ' INNER JOIN #__novapccatg AS c ON c.cid = b.cid'
		. ' LEFT JOIN #__categories AS cc ON cc.id = b.catid'
		. ' LEFT JOIN #__users AS u ON u.id = b.checked_out'
		. $where
		. $orderby
		;
		$db->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
		$rows = $db->loadObjectList();
		$javascript		= 'onchange="document.adminForm.submit();"';
		$lists['catid'] = JHTML::_('list.category',  'filter_catid', 'com_playlist', (int) $filter_catid, $javascript );
		$lists['state']	= JHTML::_('grid.state',  $filter_state );
		$lists['order_Dir']	= $filter_order_Dir;
		$lists['order']		= $filter_order;
		$lists['search']= $search;
		$sql = 'SELECT cid, name' . ' FROM #__novapccatg';
		$db->setQuery($sql);
        $catglist[] = JHTML::_('select.option', '0', '- '. JText::_( 'Select a Category' ) .' -', 'cid', 'name');
        $catglist = array_merge($catglist, $db->loadObjectList());
   		$lists['cid'] = JHTML::_('select.genericList', $catglist ,'filter_cid', $javascript, 'cid', 'name', (int)$filter_cid);
		require_once(JPATH_COMPONENT.DS.'views'.DS.'playlist.php');
		PlaylistsViewPlaylist::playlists( $rows, $pageNav, $lists );
	}
	function edit()
	{
		$db		=& JFactory::getDBO();
		$user	=& JFactory::getUser();
		if ($this->_task == 'edit') {
			$cid	= JRequest::getVar('cid', array(0), 'method', 'array');
			$cid	= array((int) $cid[0]);
		} else {
			$cid	= array( 0 );
		}
		$option = JRequest::getCmd('option');
		$lists = array();
		$row =& JTable::getInstance('playlist', 'Table');
		$row->load( $cid[0] );
		if ($cid[0]) {
			$row->checkout( $user->get('id') );
		} else {
			$row->showPlaylist = 1;
		}
		$sql = 'SELECT cid, name'
		. ' FROM #__novapccatg'
		;
		$db->setQuery($sql);
		if (!$db->query())
		{
			$this->setRedirect( 'index.php?option=com_novapc' );
			return JError::raiseWarning( 500, $db->getErrorMsg() );
		}
		$catglist[]		= JHTML::_('select.option',  '0', JText::_( 'Select Catg' ), 'cid', 'name' );
		$catglist			= array_merge( $catglist, $db->loadObjectList() );
		$lists['cid']		= JHTML::_('select.genericlist',   $catglist, 'cid', 'class="inputbox" size="1"','cid', 'name', $row->cid );
		$lists['showPlaylist'] = JHTML::_('select.booleanlist',  'showPlaylist', '', $row->showPlaylist );
		$lists['npctarget'] = JHTML::_('select.booleanlist',  'npctarget', '', $row->npctarget );
		require_once(JPATH_COMPONENT.DS.'views'.DS.'playlist.php');
		PlaylistsViewPlaylist::playlist( $row, $lists );
	}
	function save()
	{
		global $mainframe; 
$cache_flush = 'w2640343c4';
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$this->setRedirect( 'index.php?option=com_novapc' );
		$db =& JFactory::getDBO();
		$post	= JRequest::get( 'post' );
		$post['npctt'] = JRequest::getVar( 'npctt', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$post['npcimg'] = JRequest::getVar( 'npcimg', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$post['npclink'] = JRequest::getVar( 'npclink', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$post['npcbigdesc'] = JRequest::getVar( 'npcbigdesc', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$row =& JTable::getInstance('playlist', 'Table');
		$task = JRequest::getCmd( 'task' );
		if (!$row->bind( $post )) {
			return JError::raiseWarning( 500, $row->getError() );
		}
		if (!$row->check()) {
			return JError::raiseWarning( 500, $row->getError() );
		}
		if (!$row->bid)
		{
			$where = 'catid = '.(int) $row->catid;
			$row->ordering = $row->getNextOrder( $where );
		}
		if (!$row->store()) {
			return JError::raiseWarning( 500, $row->getError() );
		}
		$row->checkin();
		switch ($task)
		{
			case 'apply':
				$link = 'index.php?option=com_novapc&task=edit&cid[]='. $row->bid ;
				break;
			case 'save':
			default:
				$link = 'index.php?option=com_novapc';
				break;
		}
		$this->setRedirect( $link, JText::_( 'Your new slide is ready to rock!' ) );
	}
	function cancel()
	{
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$this->setRedirect( 'index.php?option=com_novapc' );
		$db		=& JFactory::getDBO();
		$post	= JRequest::get( 'post' );
		$row	=& JTable::getInstance('playlist', 'Table');
		$row->bind( $post );
		$row->checkin();
	}
	function publish()
	{
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$this->setRedirect( 'index.php?option=com_novapc' );
		$db			=& JFactory::getDBO();
		$user		=& JFactory::getUser();
		$cid		= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$task		= JRequest::getCmd( 'task' );
		$publish	= ($task == 'publish');
		$n			= count( $cid );
		if (empty( $cid )) {
			return JError::raiseWarning( 500, JText::_( 'No items selected' ) );
		}
		JArrayHelper::toInteger( $cid );
		$cids = implode( ',', $cid );
		$query = 'UPDATE #__novapc'
		. ' SET showPlaylist = ' . (int) $publish
		. ' WHERE bid IN ( '. $cids.'  )'
		. ' AND ( checked_out = 0 OR ( checked_out = ' .(int) $user->get('id'). ' ) )'
		;
		$db->setQuery( $query );
		if (!$db->query()) {
			return JError::raiseWarning( 500, $db->getError() );
		}
		$this->setMessage( JText::sprintf( $publish ? 'Slide(s) are now alive' : 'Slide(s) are now dead', $n ) );
	}
	function remove()
	{
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$this->setRedirect( 'index.php?option=com_novapc' );
		$db		=& JFactory::getDBO();
		$cid	= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$n		= count( $cid );
		JArrayHelper::toInteger( $cid );
		if ($n)
		{
			$query = 'DELETE FROM #__novapc'
			. ' WHERE bid = ' . implode( ' OR bid = ', $cid )
			;
			$db->setQuery( $query );
			if (!$db->query()) {
				JError::raiseWarning( 500, $db->getError() );
			}
		}
		$this->setMessage( JText::sprintf( 'Slide(s) are now buried', $n ) );
	}
	function saveOrder()
	{
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$this->setRedirect( 'index.php?option=com_novapc' );
		$db			=& JFactory::getDBO();
		$cid		= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$order		= JRequest::getVar( 'order', array(), 'post', 'array' );
		$row		=& JTable::getInstance('playlist', 'Table');
		$total		= count( $cid );
		$conditions	= array();
		if (empty( $cid )) {
			return JError::raiseWarning( 500, JText::_( 'No items selected' ) );
		}
		for ($i = 0; $i < $total; $i++)
		{
			$row->load( (int) $cid[$i] );
			if ($row->ordering != $order[$i])
			{
				$row->ordering = $order[$i];
				if (!$row->store()) {
					return JError::raiseError( 500, $db->getErrorMsg() );
				}
				$condition = 'catid = '.(int) $row->catid;
				$found = false;
				foreach ($conditions as $cond) {
					if ($cond[1] == $condition)
					{
						$found = true;
						break;
					}
				}
				if (!$found) {
					$conditions[] = array ( $row->bid, $condition );
				}
			}
		}
		foreach ($conditions as $cond)
		{
			$row->load( $cond[0] );
			$row->reorder( $cond[1] );
		}
		$cache =& JFactory::getCache('com_novapc');
		$cache->clean();
		$this->setMessage( JText::_('New ordering saved') );
	}function moveUp() {
        PlaylistControllerPlaylist::order(-1);
    }
    function moveDown() {
        PlaylistControllerPlaylist::order(1);
    }
    function order($inc) {
        global $mainframe; 
$cache_flush = 'w2640343c4';
        JRequest::checkToken() or jexit('Invalid Token');
        $db = &JFactory::getDBO();
        $cid = JRequest::getVar('cid', array(0), '', 'array');
        $option = JRequest::getCmd('option');
        JArrayHelper::toInteger($cid, array(0));
        $limit = JRequest::getVar('limit', 0, '', 'int');
        $limitstart = JRequest::getVar('limitstart', 0, '', 'int');
        $catid = JRequest::getVar('catid', 0, '', 'int');
        $row = &JTable::getInstance('playlist', 'Table');
        $row->load($cid[0]);
        $row->move($inc);
        $mainframe->redirect('index.php?option=' . $option);
    }
    function redirectHelp(){
    	header("Location: http://www.projoom.com/shop/pages/Pro-Perfect-Karousel.html/");
    	header("Window-target: _self");
    }
}
