<?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 job management view.
 *
 * @since 1.10
 */
class VikRestaurantsViewmanagecronjob extends JViewVRE
{
	/**
	 * VikRestaurants view display method.
	 *
	 * @return  void
	 */
	function display($tpl = null)
	{
		$app = JFactory::getApplication();
		
		$ids  = $app->input->getUint('cid', []);
		$type = $ids ? 'edit' : 'new';
		
		// set the toolbar
		$this->addToolBar($type);
		
		/** @var \stdClass */
		$this->cron = JModelVRE::getInstance('cronjob')->getItem($ids ? $ids[0] : 0, $blank = true);

		// use cron job data stored in user state
		$this->injectUserStateData($this->cron, 'vre.cronjob.data');

		if ($this->cron->class)
		{
			// get cron job configuration
			$this->config = VREFactory::getCronDispatcher()->getCron($this->cron->class, $this->cron->id)->getForm();
		}
		else
		{
			// no selected cron, use an empty array of configuration fields
			$this->config = [];
		}

		// fetch list of supported cron drivers
		$this->cronjobs = JHtml::fetch('vrehtml.admin.crondrivers', '');

		/** @var E4J\VikRestaurants\Platform\Form\FormFactory */
		$this->formFactory = VREFactory::getPlatform()->getFormFactory();

		// display the template
		parent::display($tpl);
	}

	/**
	 * Setting the toolbar.
	 *
	 * @return  void
	 */
	protected function addToolBar($type)
	{
		// add menu title and some buttons to the page
		if ($type == 'edit')
		{
			JToolBarHelper::title(JText::translate('VREMAINTITLEEDITCRONJOB'), 'vikrestaurants');
		}
		else
		{
			JToolBarHelper::title(JText::translate('VREMAINTITLENEWCRONJOB'), 'vikrestaurants');
		}
		
		$user = JFactory::getUser();
		
		if ($user->authorise('core.edit', 'com_vikrestaurants')
			|| $user->authorise('core.create', 'com_vikrestaurants'))
		{
			JToolbarHelper::apply('cronjob.save', JText::translate('VRSAVE'));
			JToolbarHelper::save('cronjob.saveclose', JText::translate('VRSAVEANDCLOSE'));
		}

		if ($user->authorise('core.edit', 'com_vikrestaurants')
			&& $user->authorise('core.create', 'com_vikrestaurants'))
		{
			JToolbarHelper::save2new('cronjob.savenew', JText::translate('VRSAVEANDNEW'));
		}

		if ($type == 'edit' && $user->authorise('core.create', 'com_vikrestaurants'))
		{
			JToolbarHelper::save2copy('cronjob.savecopy', JText::translate('VRSAVEASCOPY'));
		}
		
		JToolbarHelper::cancel('cronjob.cancel', $type == 'edit' ? 'JTOOLBAR_CLOSE' : 'JTOOLBAR_CANCEL');
	}
}
