<?php
/**
 * @package DJ-Events
 * @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
 * @developer Szymon Woronowski - szymon.woronowski@design-joomla.eu
 *
 */

defined('_JEXEC') or die('Restricted access');

use Joomla\Utilities\ArrayHelper;

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

class DJEventsModelLocations extends JModelList
{
	public function __construct($config = array())
	{
		if (empty($config['filter_fields'])) {
			$config['filter_fields'] = array(
				'a.id',
                'a.name',
                'a.post_code',
                'a.address',
                'a.latitude',
                'a.longitude',
                'a.created',
                'a.published',
                'c.name',
                'a.post_code',
                'a.address',
                'events_count'
			);
		}

		parent::__construct($config);
	}
	protected function populateState($ordering = null, $direction = null)
	{
		// List state information.
		parent::populateState('a.name', 'asc');

		// Initialise variables.
		$app = JFactory::getApplication();
		$session = JFactory::getSession();

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

        $city = $this->getUserStateFromRequest($this->context.'.filter.city', 'filter_city');
        $this->setState('filter.city', $city);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_djevents');
		$this->setState('params', $params);
	}

	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id	.= ':'.$this->getState('filter.search');
		$id	.= ':'.$this->getState('filter.published');
        $id	.= ':'.serialize($this->getState('filter.city'));

		return parent::getStoreId($id);
	}

	protected function getListQuery()
	{
		// Create a new query object.
		$app = JFactory::getApplication();
		$user = JFactory::getUser();
		$db = $this->getDbo();
		$query = $db->getQuery(true);
		$params = JComponentHelper::getParams('com_djevents');
		
		// Select the required fields from the table.
		$select_default = 'a.*, c.name as city_name';

		$query->select($this->getState('list.select', $select_default));
        $query->select('( SELECT COUNT(e.id) FROM #__djev_events AS e WHERE e.location_id = a.id) AS events_count');
		$query->from('#__djev_locations AS a');

		// Join over the users for the checked out user.
		$query->join('LEFT', '#__users AS uc ON uc.id=a.checked_out');
		$query->join('LEFT', '#__djev_cities AS c ON c.id = a.city_id');

		// Filter by search in title.
		$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).'%');
                $searchCols = array('a.name', 'a.alias');
				$query->where('('.implode(' LIKE '.$search.' OR ', $searchCols).' LIKE '.$search.')');
			}
		}
		
		$state = $this->getState('filter.published', false);
		if (is_numeric($state)) {
			$query->where('a.published='.(int)$state);
		} else if ($state == '') {
			$query->where('(a.published = 0 OR a.published = 1)');
		}

        $city = $this->getState('filter.city', false);
        if ($city) {
            if (is_array($city)) {
                ArrayHelper::toInteger($city);
                $query->where('a.city_id IN ('.implode(',', $city).')');
            } else {
                $query->where('a.city_id='.(int)$city);
            }
        }

		// Add the list ordering clause.
		$orderCol	= $this->state->get('list.ordering', 't.start');
		$orderDirn	= $this->state->get('list.direction', 'asc');
		
		$query->order($db->escape($orderCol .' '.$orderDirn));

		return $query;
	}

    public function getCities() {
        $this->_db->setQuery('SELECT id as value, name as text FROM #__djev_cities ORDER BY name ASC');
        $cities = $this->_db->loadObjectList();
        return $cities;
    }

}
