<?php
/** 
 * @package     VikRestaurants
 * @subpackage  core
 * @author      E4J s.r.l.
 * @copyright   Copyright (C) 2023 E4J s.r.l. All Rights Reserved.
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @link        https://vikwp.com
 */

// No direct access
defined('ABSPATH') or die('No script kiddies please!');

/**
 * VikRestaurants cron jobs view.
 *
 * @since 1.10
 */
class VikRestaurantsViewcronjobs extends JViewVRE
{
	/**
	 * VikRestaurants view display method.
	 *
	 * @return  void
	 */
	function display($tpl = null)
	{
		$app = JFactory::getApplication();
		$dbo = JFactory::getDbo();

		// set the toolbar
		$this->addToolBar();

		$filters = [];
		$filters['search'] = $app->getUserStateFromRequest($this->getPoolName() . '.search', 'search', '', 'string');
		$filters['class']  = $app->getUserStateFromRequest($this->getPoolName() . '.class', 'class', '', 'string');
		$filters['status'] = $app->getUserStateFromRequest($this->getPoolName() . '.status', 'status', '', 'string');

		$this->filters = $filters;

		$this->ordering = $app->getUserStateFromRequest($this->getPoolName() . '.ordering', 'filter_order', 'j.createdon', 'string');
		$this->orderDir = $app->getUserStateFromRequest($this->getPoolName() . '.orderdir', 'filter_order_Dir', 'ASC', 'string');

		$lim 	= $app->getUserStateFromRequest($this->getPoolName() . '.limit', 'limit', $app->get('list_limit'), 'int');
		$lim0 	= $this->getListLimitStart($filters + ['limit' => $lim]);
		$navbut	= "";

		$rows = [];

		$q = $dbo->getQuery(true);

		$q->select('SQL_CALC_FOUND_ROWS j.*')
			->from($dbo->qn('#__vikrestaurants_cronjob', 'j'))
			->order($dbo->qn($this->ordering) . ' ' . $this->orderDir);

		if (strlen($filters['search']))
		{
			$q->where($dbo->qn('j.name') . ' LIKE ' . $dbo->q("%{$filters['search']}%"));
		}

		if (!empty($filters['class']))
		{
			$q->where($dbo->qn('j.class') . ' = ' . $dbo->q($filters['class']));
		}

		if (strlen($filters['status']))
		{
			$q->where($dbo->qn('j.published') . ' = ' . (int) $filters['status']);
		}

		/**
		 * It is possible to lean on the "onBeforeListQueryCronjobs" plugin event
		 * to manipulate the query used to load the list of records.
		 *
		 * @since 1.10
		 */
		$this->onBeforeListQuery($q);

		$dbo->setQuery($q, $lim0, $lim);
		$dbo->execute();

		// assert limit used for list query
		$this->assertListQuery($lim0, $lim);
		
		if ($dbo->getNumRows())
		{
			$rows = $dbo->loadAssocList();
			$dbo->setQuery('SELECT FOUND_ROWS();');
			jimport('joomla.html.pagination');
			$pageNav = new JPagination($dbo->loadResult(), $lim0, $lim);
			$navbut = JLayoutHelper::render('blocks.pagination', ['pageNav' => $pageNav]);
		}

		// get logs

		foreach ($rows as $k => $r)
		{
			$q = $dbo->getQuery(true)
				->select('*')
				->from($dbo->qn('#__vikrestaurants_cronjob_log'))
				->where($dbo->qn('id_cronjob') . ' = ' . (int) $r['id'])
				->order($dbo->qn('id') . ' DESC');

			$dbo->setQuery($q, 0, 1);
			$rows[$k]['lastlog'] = $dbo->loadAssoc() ?: [];
		}

		$this->rows   = $rows;
		$this->navbut = $navbut;

		/** @var E4J\VikRestaurants\Cron\Dispatcher */
		$this->cronDispatcher = VREFactory::getCronDispatcher();
		
		// display the template (default.php)
		parent::display($tpl);
	}

	/**
	 * Setting the toolbar.
	 *
	 * @return  void
	 */
	protected function addToolBar()
	{
		// add menu title and some buttons to the page
		JToolBarHelper::title(JText::translate('VREMAINTITLEVIEWCRONJOBS'), 'vikrestaurants');

		$user = JFactory::getUser();

		JToolBarHelper::back('JTOOLBAR_BACK', 'index.php?option=com_vikrestaurants&view=editconfigapp');
		
		if ($user->authorise('core.create', 'com_vikrestaurants'))
		{
			JToolBarHelper::addNew('cronjob.add');
		}

		if ($user->authorise('core.edit', 'com_vikrestaurants'))
		{
			JToolBarHelper::editList('cronjob.edit');
		}

		if ($user->authorise('core.delete', 'com_vikrestaurants'))
		{
			JToolBarHelper::deleteList(VikRestaurants::getConfirmSystemMessage(), 'cronjob.delete');
		}
	}

	/**
	 * Checks for advanced filters set in the request.
	 *
	 * @return  bool  True if active, otherwise false.
	 */
	protected function hasFilters()
	{
		return (!empty($this->filters['class'])
			|| strlen($this->filters['status']));
	}
}
