<?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 jegroupbuyModelproducts extends JModelList
{
	public function __construct($config = array())
	{
		if (empty($config['filter_fields'])) {
			$config['filter_fields'] = array(
				'id', 'p.id',
				'title', 'p.title',
				'shop_name', 's.shop_name',
				'alias', 'p.alias',
				'deal_price', 'p.deal_price',
				'published', 'p.published',
				'featured', 'p.featured',
				'catid', 'p.catid', 'category_title',
				'access', 'p.access', 'access_level',
				'ordering', 'p.ordering',
				'language', 'p.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',
				'p.id AS id, p.title, p.alias,'.
				'p.catid,p.deal_price,' .
				'p.published, p.ordering,'.
				'p.language,p.featured, s.shop_name'
			) );
		// From the hello table
		$query->from('#__jegroupbuy_product AS p');
		// Join over the categories.
			$query->select( 'cat.title AS category_title' );
			$query->join( 'LEFT', '#__categories AS cat ON cat.id = p.catid' );

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

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

		// Join over the Shop Name
			$query->select( 's.shop_name AS shop_name' );
			$query->join( 'LEFT', '`#__jegroupbuy_stores` AS s ON s.id = p.store_id' );

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

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

		// Filter by a single or group of categories.
			$categoryId		= $this->getState('filter.category_id');
			if (is_numeric($categoryId)) {
				$query->where('p.catid = '.(int) $categoryId);
			} else if (is_array($categoryId)) {
				JArrayHelper::toInteger($categoryId);
				$categoryId	= implode(',', $categoryId);
				$query->where('p.catid IN ('.$categoryId.')');
			}

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

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

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

			if ($orderCol == 'p.ordering' || $orderCol == 'category_title') {
				$orderCol	= 'category_title '. $orderDirn .', p.ordering';
			}
			$query->order($db->getEscaped($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('p.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_product');
			$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);
	}
}
