<?php
/**
 * @version        4.3.0
 * @package        Joomla
 * @subpackage     Helpdesk Pro
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2013 - 2021 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */

namespace OSSolution\HelpdeskPro\Site\View\Tickets;

use HelpdeskProHelperBootstrap;
use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Uri\Uri;
use Joomla\Registry\Registry;
use Joomla\Utilities\ArrayHelper;
use OSL\View\ListView;
use OSSolution\HelpdeskPro\Site\Helper\Database as HelpdeskproHelperDatabase;
use OSSolution\HelpdeskPro\Site\Helper\Helper as HelpdeskproHelper;
use OSSolution\HelpdeskPro\Site\Helper\Html as HelpdeskproHelperHtml;

defined('_JEXEC') or die;

/**
 * Class Html
 *
 * @property-read \OSSolution\HelpdeskPro\Admin\Model\Tickets $model
 */
class Html extends ListView
{
	protected $lists = array();

	protected function beforeRender()
	{
		parent::beforeRender();

		$user = $this->container->user;

		if (!$user->id)
		{
			$redirectUrl = Route::_('index.php?option=com_users&view=login&return=' . base64_encode(Uri::getInstance()->toString()));
			$this->container->app->enqueueMessage(Text::_('HDP_PLEASE_LOGIN_TO_CONTINUE'));
			$this->container->app->redirect($redirectUrl);
		}

		$config = HelpdeskproHelper::getConfig();

		// Category filter
		$filters = array();

		$role = 'admin';

		if (!$user->authorise('core.admin', 'com_helpdeskpro'))
		{
			$userId = $user->get('id');
			$email  = $user->get('email');

			$role               = HelpdeskproHelper::getUserRole();
			$managedCategoryIds = HelpdeskproHelper::getTicketCategoryIds($user->get('username'));
			$managedCategoryIds = ArrayHelper::toInteger($managedCategoryIds);

			if (count($managedCategoryIds))
			{
				$filters[] = '(id IN (' . implode(',', $managedCategoryIds) . ') OR id IN (SELECT DISTINCT category_id FROM #__helpdeskpro_tickets AS t WHERE t.staff_id =' . $userId . '))';
			}
			elseif ($role == 'staff')
			{
				$filters[] = 'id IN (SELECT DISTINCT category_id FROM #__helpdeskpro_tickets AS t WHERE t.staff_id =' . $userId . ')';
			}
			else
			{

				$db        = $this->model->getDbo();
				$filters[] = 'id IN (SELECT DISTINCT category_id FROM #__helpdeskpro_tickets AS t WHERE t.user_id = ' . $userId . ' OR t.email = ' . $db->quote($email) . ')';
			}

			$filters[] = '`access` IN (' . implode(',', $user->getAuthorisedViewLevels()) . ')';
		}

		$fieldSuffix = HelpdeskproHelper::getFieldSuffix();

		$rows = HelpdeskproHelperDatabase::getAllCategories('ordering', $filters, $fieldSuffix);

		$this->lists['filter_category_id'] = HelpdeskproHelperHtml::buildCategoryDropdown($this->state->filter_category_id, 'filter_category_id', 'class="input-large form-select" onchange="submit();"', $rows);

		// Ticket status filter
		$rowStatuses = HelpdeskproHelperDatabase::getAllStatuses('ordering', $fieldSuffix);

		if (count($rowStatuses))
		{
			$options   = array();
			$options[] = HTMLHelper::_('select.option', -1, Text::_('HDP_TICKET_STATUS'), 'id', 'title');
			$options[] = HTMLHelper::_('select.option', 0, Text::_('HDP_ALL_STATUSES'), 'id', 'title');
			$options   = array_merge($options, $rowStatuses);

			$this->lists['filter_status_id'] = HTMLHelper::_('select.genericlist', $options, 'filter_status_id',
				array(
					'option.text.toHtml' => false,
					'option.text'        => 'title',
					'option.key'         => 'id',
					'list.attr'          => 'class="input-medium form-select" onchange="submit();"',
					'list.select'        => $this->state->filter_status_id));
		}

		$statusList = array();

		foreach ($rowStatuses as $status)
		{
			$statusList[$status->id] = $status->title;
		}

		// Ticket priority filter
		$rowPriorities = HelpdeskproHelperDatabase::getAllPriorities('ordering', $fieldSuffix);

		if (count($rowPriorities))
		{
			$options   = array();
			$options[] = HTMLHelper::_('select.option', 0, Text::_('HDP_ALL_PRIORITIES'), 'id', 'title');
			$options   = array_merge($options, $rowPriorities);

			$this->lists['filter_priority_id'] = HTMLHelper::_('select.genericlist', $options, 'filter_priority_id',
				array(
					'option.text.toHtml' => false,
					'option.text'        => 'title',
					'option.key'         => 'id',
					'list.attr'          => 'class="input-medium form-select" onchange="submit();"',
					'list.select'        => $this->state->filter_priority_id));
		}

		$priorityList = array();

		foreach ($rowPriorities as $priority)
		{
			$priorityList[$priority->id] = $priority->title;
		}

		if (PluginHelper::isEnabled('helpdeskpro', 'assignticket') && in_array($role, ['admin', 'manager']))
		{
			$staffDisplayField = $config->get('staff_display_field', 'username') ?: 'username';

			$staffs                         = HelpdeskproHelperDatabase::getAllStaffs($config->staff_group_id);
			$options                        = array();
			$options[]                      = HTMLHelper::_('select.option', 0, Text::_('HDP_SELECT_STAFF'), 'id', $staffDisplayField);
			$options                        = array_merge($options, $staffs);
			$this->lists['filter_staff_id'] = HTMLHelper::_('select.genericlist', $options, 'filter_staff_id', ' class="input-medium form-select" onchange="submit();" ', 'id', $staffDisplayField, $this->state->filter_staff_id);

			$rowStaffs = array();

			foreach ($staffs as $staff)
			{
				$rowStaffs[$staff->id] = $staff->{$staffDisplayField};
			}

			$this->staffs          = $rowStaffs;
			$this->showStaffColumn = true;
		}

		$active = Factory::getApplication()->getMenu()->getActive();

		if ($active && isset($active->query['view']) && $active->query['view'] == 'tickets')
		{
			$params = $active->getParams();
		}
		else
		{
			$params = new Registry;
		}

		$this->fields          = HelpdeskproHelperDatabase::getFieldsOnListView($fieldSuffix);
		$this->fieldValues     = $this->model->getFieldsData($this->fields);
		$this->statusList      = $statusList;
		$this->priorityList    = $priorityList;
		$this->config          = $config;
		$this->params          = $params;
		$this->bootstrapHelper = HelpdeskProHelperBootstrap::getInstance();
	}
}