<?php
/**
 * @version    SVN: <svn_id>
 * @package    Tjfields
 * @author     Techjoomla <extensions@techjoomla.com>
 * @copyright  Copyright (c) 2009-2015 TechJoomla. All rights reserved.
 * @license    GNU General Public License version 2 or later.
 */

// No direct access
defined('_JEXEC') or die();
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Model\ListModel;

/**
 * Methods supporting a list of cities records.
 *
 * @package     Tjfields
 * @subpackage  com_tjfields
 * @since       2.2
 */
class TjfieldsModelCities extends ListModel
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @since   1.6
	 * @see     JController
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'state', 'state',
				'city', 'a.city',
				'country_id', 'a.country_id',
				'region_id', 'a.region_id',
				'city_jtext', 'a.city_jtext',
				'country', 'a.country',
				'region', 'a.region',
				'state', 'a.state'
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		// Initialise variables.
		$app = Factory::getApplication('administrator');

		// Set ordering.
		$orderCol = $this->getUserStateFromRequest($this->context . '.filter_order', 'filter_order');

		if (!in_array($orderCol, $this->filter_fields))
		{
			$orderCol = 'a.id';
		}

		$this->setState('list.ordering', $orderCol);

		// Set ordering direction.
		$listOrder = $this->getUserStateFromRequest($this->context . 'filter_order_Dir', 'filter_order_Dir');

		if (!in_array(strtoupper($listOrder), array('ASC', 'DESC', '')))
		{
			$listOrder = 'ASC';
		}

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

		// Load the filter state
		$published = $this->getUserStateFromRequest($this->context . 'filter.state', 'filter_state', '', 'string');
		$this->setState('filter.state', $published);

		// Load the filter country
		$country = $this->getUserStateFromRequest($this->context . 'filter.country', 'filter_country', '', 'string');
		$this->setState('filter.country', $country);

		// Load the filter country
		$region = $this->getUserStateFromRequest($this->context . 'filter.region', 'filter_region', '', 'string');
		$this->setState('filter.region', $region);

		// Load the parameters.
		$params = ComponentHelper::getParams('com_tjfields');
		$this->setState('params', $params);

		// List state information.
		parent::populateState('a.country_id', 'asc');
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 *
	 * @since   1.6
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('filter.search');
		$id .= ':' . $this->getState('filter.state');

		return parent::getStoreId($id);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery
	 *
	 * @since   1.6
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);
		$client = Factory::getApplication()->input->get('client', '', 'STRING');

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

		$query->from('`#__tj_city` AS a');
		$query->select('a.' . $client .' AS state');

		$query->select('c.country');
		$query->join('LEFT', '`#__tj_country` AS c ON c.id=a.country_id');
		$query->where('c.' . $client .' = 1');

		$query->select('r.region');
		$query->join('LEFT', '`#__tj_region` AS r ON r.id=a.region_id');
		//$query->where('r.' . $client .' = 1');

		// 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) . '%');
				$query->where('( a.city LIKE ' . $search .
					'  OR  a.city_jtext LIKE ' . $search . ' )'
				);
			}
		}

		// Filter by published state.
		$published = $this->getState('filter.state');

		if (is_numeric($published))
		{
			$query->where('a.' . $client .' = ' . (int) $published);
		}
		elseif ($published === '')
		{
			$query->where('(a.' . $client .' IN (0, 1))');
		}

		// Filter by country
		$country = $this->getState('filter.country');

		if (is_numeric($country))
		{
			$query->where('a.country_id = ' . (int) $country);

			// Apply regions filter only when country is selected
			// Filter by region
			$region = $this->getState('filter.region');

			if (is_numeric($region))
			{
				$query->where('a.region_id = ' . (int) $region);
			}
		}



		// 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 . ', a.city ' . $orderDirn));
		}

		return $query;
	}

	/**
	 * Method to get a list of cities.
	 *
	 * @return  mixed  An array of data items on success, false on failure.
	 *
	 * @since   1.6.1
	 */
	public function getItems()
	{
		$items = parent::getItems();

		return $items;
	}
}
