<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_notifly
 *
 * @copyright   Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;
/**
 * Feature model.
 *
 * @since  1.6
 */
class NotiflyModelEvents extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @since   1.6
	 * @see     JControllerLegacy
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'template_id', 'a.template_id',
				'extension_id', 'a.extension_id',
				'url', 'a.url',
				'image_url', 'a.image_url',
				'title', 'a.title',
				'message', 't.message',
				'name', 'a.name',
				'email', 'a.email',
				'ip', 'a.ip',
				'city', 'a.city',
				'state', 'a.state',
				'country', 'a.country',
				'created', 'a.created',
				'checked_out', 'a.checked_out',
				'checked_out_time', 'a.checked_out_time',
				'state', 'a.state',
				'access', 'a.access', 'access_level',
				'ordering', 'a.ordering',
			);
		}

		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 = 'a.id', $direction = 'desc')
	{
		$app = JFactory::getApplication();

		// Adjust the context to support modal layouts.
		if ($layout = $app->input->get('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);

		$formSubmited = $app->input->post->get('form_submited');

		$access     = $this->getUserStateFromRequest($this->context . '.filter.access', 'filter_access');

		// $extension_id = $app->input->post->get('');
		$extension_id = $this->getUserStateFromRequest($this->context . '.filter.extension_id', 'filter_extension_id');

		if ($formSubmited)
		{
			$access = $app->input->post->get('access');
			$this->setState('filter.access', $access);
		}

		// List state information.
		parent::populateState($ordering, $direction);
	}

	/**
	 * 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 .= ':' . serialize($this->getState('filter.access'));
		$id .= ':' . serialize($this->getState('filter.access'));
		$id .= ':' . serialize($this->getState('filter.extension_id'));
		$id .= ':' . $this->getState('filter.published');

		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);
		$user  = JFactory::getUser();

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

		// Join over the extensions.
		$query->select('t.name AS template, t.message')
			->join('LEFT', '#__notifly_templates AS t ON t.id = a.template_id');

		$query->select('ex.element AS integration')
			->join('LEFT', '#__extensions AS ex ON ex.extension_id = a.extension_id')
			->where('ex.type="plugin" and ex.folder="notifly"');

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

		// show only the items enabled
		$query->where('ex.enabled = 1');
		
		// Filter by access level.
		$extension_id = $this->getState('filter.extension_id');
		if ($extension_id)
		{
			$query->where('ex.element = ' . $db->quote($extension_id));
		}
		
		$access = $this->getState('filter.access');
		if (is_numeric($access))
		{
			$query->where('a.access = ' . (int) $access);
		}
		elseif (is_array($access))
		{
			$access = ArrayHelper::toInteger($access);
			$access = implode(',', $access);
			$query->where('a.access IN (' . $access . ')');
		}

		// Filter by access level on categories.
		if (!$user->authorise('core.admin'))
		{
			$groups = implode(',', $user->getAuthorisedViewLevels());
			$query->where('a.access IN (' . $groups . ')');
			$query->where('c.access IN (' . $groups . ')');
		}

		// 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('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));
		// 		$query->where('(a.name LIKE ' . $search . ' OR a.alias LIKE ' . $search . ')');
		// 	}
		// }

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

		$query->order($db->escape($orderCol) . ' ' . $db->escape($orderDirn));
		// echo $query->__toString();die;
		return $query;
	}

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

		if (JFactory::getApplication()->isClient('site'))
		{
			$groups = JFactory::getUser()->getAuthorisedViewLevels();

			foreach (array_keys($items) as $x)
			{
				// Check the access level. Remove articles the user shouldn't see
				if (!in_array($items[$x]->access, $groups))
				{
					unset($items[$x]);
				}
			}
		}

		return $items;
	}
}
