<?php
/**
 * @package DJ-Catalog2
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 */

// no direct access
defined('_JEXEC') or die;

jimport('joomla.application.component.modellist');

class Djcatalog2ModelQueries extends JModelList
{
	public function __construct($config = array())
	{
		if (empty($config['filter_fields'])) {
			$config['filter_fields'] = array(
					'a.id', 'a.created_date', 'a.status', 'a.modified'
			);
		}

		parent::__construct($config);
	}
	protected function populateState($ordering = null, $direction = null)
	{
		// List state information.
		parent::populateState('a.created_date', 'desc');
		
		// Initialise variables.
		$app = JFactory::getApplication();
		$session = JFactory::getSession();
		
		$search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');
		$this->setState('filter.search', $search);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_djcatalog2');
		$this->setState('params', $params);
	}
	
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id	.= ':'.$this->getState('filter.search');

		return parent::getStoreId($id);
	}

	protected function getListQuery()
	{
		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.*'
			)
		);
		$query->from('#__djc2_quotes AS a');

		$ids = $this->getState('filter.ids', false);
		if (!empty($ids)) {
			$query->where('a.id IN ('.$ids.')');
		}

		$search = $this->getState('filter.search');
		if (!empty($search)) {
			if (stripos($search, 'id:') === 0) {
				$query->where('a.id = '.(int) substr($search, 3));
			}
			else {
				$search = $db->quote('%'.$db->escape($search, true).'%');
				$query->where('(a.email LIKE '.$search.' OR a.firstname LIKE '.$search.' OR a.lastname LIKE '.$search.' OR a.company LIKE '.$search.')');
			}
		}
		
		// Add the list ordering clause.
		$orderCol	= $this->state->get('list.ordering');
		$orderDirn	= $this->state->get('list.direction');

		if($orderCol || $orderDirn) {
			$query->order($db->escape($orderCol.' '.$orderDirn));
		}
		return $query;
	}

	public function getItems()
	{
		// Get a storage key.
		$store = $this->getStoreId();

		// Try to load the data from internal storage.
		if (!empty($this->_cache[$store])) {
			return $this->_cache[$store];
		}

		// Load the list items.
		$query  = $this->getListQuery();
		
		try
		{
			$items  = $this->_getList((string) $query, $this->getState('list.start'), $this->getState('list.limit'));
		}
		catch (\RuntimeException $e)
		{
			$this->setError($e->getMessage());
			return false;
		}

		// Add the items to the internal cache.
		$this->_cache[$store] = $items;

		if($this->getState('quote_items')) {
			$this->bindQuoteItems($store);
		}

		return $this->_cache[$store];
	}

	private function bindQuoteItems($store) {
		if (!empty($this->_cache[$store])) {
			$ids = array_keys($this->_cache[$store]);

			if (empty($ids)) {
				return;
			}

			$quote_items = $this->getQuoteItems($ids);
			if(count($quote_items)) {
				foreach ($quote_items as $quote_item) {
					$this->_cache[$store][$quote_item->quote_id]->items[] = $quote_item;
				}
			}

		}
	}

	protected function _getList($query, $limitstart = 0, $limit = 0)
	{
		$this->_db->setQuery($query, $limitstart, $limit);
		$result = $this->_db->loadObjectList('id');

		return $result;
	}

	public function getQuoteItems($quote_id) {
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);

		$query->select('*');
		$query->from($db->quoteName('#__djc2_quote_items'));

		if(is_array($quote_id) && count($quote_id)) {
			$query->where($db->quoteName('quote_id') . ' IN ('. implode($quote_id, ",") .')');
		} elseif (is_int($quote_id)) {
			$query->where($db->quoteName('quote_id') . ' = '. (int)$quote_id);
		}


		$db->setQuery($query);

		return $db->loadObjectList();
	}
	
}