<?php
/**
 * JE GroupBuy package
 * @author J-Extension <contact@jextn.com>
 * @link http://www.jextn.com
 * @copyright (C) 2011 - 2012 J-Extension
 * @license GNU/GPL, see LICENSE.php for full license.
**/

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

// import the Joomla modellist library
jimport('joomla.application.component.modellist');

/**
 * JE GroupBuy Model
 */
class jegroupbuyModelstores extends JModelList
{
	public function __construct($config = array())
	{
		if (empty($config['filter_fields'])) {
			$config['filter_fields'] = array(
				'id', 's.id',
				'shop_name', 's.shop_name',
				'owner', 's.owner',
				'contact_number', 's.contact_number',
				'published', 's.published',
				'email', 's.email',
				'access', 's.access', 'access_level',
				'ordering', 's.ordering',
				'language', 's.language',
			);
		}

		parent::__construct($config);
	}
	/**
	 * Method to build an SQL query to load the list data.
	 *
	 * @return	string	An SQL query
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);

		// Select some fields
		$query->select( $this->getState(
				'list.select',
				's.id AS id, s.shop_name, s.owner,s.email,s.contact_number,'.
				's.published, s.ordering,'.
				's.language'
			) );
		// From the hello table
		$query->from('#__jegroupbuy_stores AS s');

		// Join over the asset groups.
			$query->select( 'ag.title AS access_level' );
			$query->join( 'LEFT', '#__viewlevels AS ag ON ag.id = s.access' );

		// Join over the language
			$query->select( 'l.title AS language_title' );
			$query->join( 'LEFT', '`#__languages` AS l ON l.lang_code = s.language' );

		// Filter by published state
			$published		= $this->getState('filter.published');
			if (is_numeric($published)) {
				$query->where('s.published = ' . (int) $published);
			} else if ($published === '') {
				$query->where('(s.published = 0 OR s.published = 1)');
			}

		// Filter by search in title & microblog.
			$search			= $this->getState('filter.search');
			if (!empty($search)) {
				if (stripos($search, 'id:') === 0) {
					$query->where('s.id = '.(int) substr($search, 3));
				} else {
					$search = $db->Quote('%'.$db->escape($search, true).'%');
					$query->where('(s.shop_name LIKE '.$search.')');
				}
			}


		// Filter by access level.
			if ($access = $this->getState('filter.access')) {
				$query->where('s.access = ' . (int) $access);
			}

		// Filter on the language.
			if ($language = $this->getState('filter.language')) {
				$query->where('s.language = '.$db->quote($language));
			}

		// Add the list ordering clause.
			$orderCol		= $this->state->get('list.ordering');
			$orderDirn		= $this->state->get('list.direction');

			if ($orderCol == 's.ordering' || $orderCol == 's.shop_name') {
				$orderCol	= 's.shop_name '. $orderDirn .', s.ordering';
			}

			$query->order($db->escape($orderCol.' '.$orderDirn));

		return $query;
	}
	/**
	 * Method to auto-populate the model state.
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		// Initialise variables.
			$app		= JFactory::getApplication();

		// Adjust the context to support modal layouts.
			if ($layout = JRequest::getVar('layout')) {
				$this->context .= '.'.$layout;
			}

		$search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');
		$this->setState('filter.search', $search);

		$published		= $this->getUserStateFromRequest($this->context.'.filter.published', 'filter_published', '');
		$this->setState('filter.published', $published);

		$categoryId		= $this->getUserStateFromRequest($this->context.'.filter.category_id', 'filter_category_id');
		$this->setState('filter.category_id', $categoryId);

		$access			= $this->getUserStateFromRequest($this->context.'.filter.access', 'filter_access', 0, 'int');
		$this->setState('filter.access', $access);

		$language		= $this->getUserStateFromRequest($this->context.'.filter.language', 'filter_language', '');
		$this->setState('filter.language', $language);

		// List state information.
			parent::populateState('s.ordering', 'asc');
	}
	/**
	 * Method to get the maximum ordering value for each category.
	 */
	function &getCategoryOrders()
	{
		if (!isset($this->cache['categoryorders'])) {
			$db		= $this->getDbo();
			$query	= $db->getQuery(true);
			$query->select('MAX(ordering) as `max`, catid');
			$query->select('catid');
			$query->from('#__jegroupbuy_stores');
			$query->group('catid');
			$db->setQuery($query);
			$this->cache['categoryorders'] = $db->loadAssocList('catid', 0);
		}
		return $this->cache['categoryorders'];
	}

	protected function getStoreId($id = '')
	{
		// Compile the store id.
			$id	.= ':'.$this->getState('filter.search');
			$id	.= ':'.$this->getState('filter.state');
			$id	.= ':'.$this->getState('filter.category_id');
			$id	.= ':'.$this->getState('filter.access');
			$id	.= ':'.$this->getState('filter.language');

		return parent::getStoreId($id);
	}

	protected function _getList($query, $limitstart=0, $limit=0)
	{
		$ordering = $this->getState('list.ordering', 'ordering');
		if (in_array($ordering, array('pages', 'name'))) {
			$this->_db->setQuery($query);
			$result = $this->_db->loadObjectList();
			$this->translate($result);
			$lang = JFactory::getLanguage();
			JArrayHelper::sortObjects($result, $ordering, $this->getState('list.direction') == 'desc' ? -1 : 1, true, $lang->getLocale());
			$total = count($result);
			$this->cache[$this->getStoreId('getTotal')] = $total;
			if ($total < $limitstart) {
				$limitstart = 0;
				$this->setState('list.start', 0);
			}
			return array_slice($result, $limitstart, $limit ? $limit : null);
		}
		else {
			if ($ordering == 'ordering') {
				$query->order('s.catid ASC');
				$ordering = 's.ordering';
			}

			$query->order($this->_db->quoteName($ordering) . ' ' . $this->getState('list.direction'));
			if ($ordering == 'cat') {
				$query->order('s.ordering ASC');
			}
			$result = parent::_getList($query, $limitstart, $limit);
			return $result;
		}
	}

}
