<?php
/**
 * @package    VP Email Manager
 * @copyright  Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @author     Abhishek Das <info@virtueplanet.com>
 * @link       https://www.virtueplanet.com
 */

defined('_JEXEC') or die;

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

/**
 * Methods supporting a list of Vpem records.
 */
class VpemModelTemplates extends \Joomla\CMS\MVC\Model\ListModel
{
/**
	* Constructor.
	*
	* @param   array  $config  An optional associative array of configuration settings.
	*
	* @see    JController
	*/
	public function __construct($config = [])
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = [
				'id', 'a.id',
				'state', 'a.state',
				'name', 'a.name',
				'type', 'a.type',
				'body', 'a.body',
				'css_style', 'a.css_style',
				'created_by', 'a.created_by',
				'created_on', 'a.created_on',
				'modified_by', 'a.modified_by',
				'modified_on', 'a.modified_on',
			];
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   Elements order
	 * @param   string  $direction  Order direction
	 *
	 * @return void
	 *
	 * @throws Exception
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		// List state information.
		parent::populateState('a.type', 'ASC');

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

		// Split context into component and optional section
		$parts = FieldsHelper::extract($context);

		if ($parts)
		{
			$this->setState('filter.component', $parts[0]);
			$this->setState('filter.section', $parts[1]);
		}
	}

	/**
	 * 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.
	 */
	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
	 */
	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', 'DISTINCT a.*'));
		$query->from($db->quoteName('#__vpem_templates') . ' AS '. $db->quoteName('a'));

		// Join over the users for the checked out user
		$query->select($db->quoteName('uc.name') . ' AS ' . $db->quoteName('uEditor'));
		$query->join('LEFT', $db->quoteName('#__users') . ' AS ' . $db->quoteName('uc') . ' ON ' . $db->quoteName('uc.id') . ' = ' . $db->quoteName('a.checked_out'));

		// Join over the user field 'created_by'
		$query->select($db->quoteName('created_by.name') . ' AS ' . $db->quoteName('created_by'));
		$query->join('LEFT', $db->quoteName('#__users') . ' AS '. $db->quoteName('created_by') . ' ON '. $db->quoteName('created_by.id') . ' = ' . $db->quoteName('a.created_by'));

		// Join over the user field 'modified_by'
		$query->select($db->quoteName('modified_by.name') . ' AS ' . $db->quoteName('modified_by'));
		$query->join('LEFT', $db->quoteName('#__users') . ' AS ' . $db->quoteName('modified_by') . ' ON ' . $db->quoteName('modified_by.id') . ' = ' . $db->quoteName('a.modified_by'));

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

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

		// Filter by search in title
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where($db->quoteName('a.id') . ' = ' . (int) substr($search, 3));
			}
			else
			{
				$search = $db->quote('%' . $db->escape($search, true) . '%');
				$query->where($db->quoteName('a.name'). ' LIKE ' . $search);
			}
		}

		// Filtering type
		$filter_type = $this->state->get('filter.type');

		if ($filter_type !== null && (is_numeric($filter_type) || !empty($filter_type)))
		{
			$query->where($db->quoteName('a.type') . ' = ' . $db->quote($db->escape($filter_type)));
		}
		
		// Add the list ordering clause.
		$orderCol  = $this->state->get('list.ordering', $db->quoteName('a.type'));
		$orderDirn = $this->state->get('list.direction', 'ASC');

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

		return $query;
	}

	/**
	 * Get an array of data items
	 *
	 * @return mixed Array of data items on success, false on failure.
	 */
	public function getItems()
	{
		$items = parent::getItems();

		foreach ($items as $oneItem)
		{
			$oneItem->type = JText::_('COM_VPEM_TEMPLATES_TYPE_OPTION_' . strtoupper($oneItem->type));
		}

		return $items;
	}
}
