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

defined('_JEXEC') or die;

/**
 * View to edit
 *
 * @since  1.0
 */
class VPAdvancedUserViewCustomfield extends JViewLegacy
{
	protected $state;

	protected $item;

	protected $form;

	/**
	 * Display the view
	 *
	 * @param   string  $tpl  Template name
	 *
	 * @return void
	 *
	 * @throws Exception
	 */
	public function display($tpl = null)
	{
		$this->state = $this->get('State');
		$this->item  = $this->get('Item');
		$this->form  = $this->get('Form');

		// Check for errors.
		if (count($errors = $this->get('Errors')))
		{
			throw new Exception(implode("\n", $errors));
		}

		$this->addToolbar();
		
		parent::display($tpl);
	}

	/**
	 * Add the page title and toolbar.
	 *
	 * @return void
	 *
	 * @throws Exception
	 */
	protected function addToolbar()
	{
		JFactory::getApplication()->input->set('hidemainmenu', true);

		$user       = JFactory::getUser();
		$isNew      = ($this->item->id == 0);
		$canDo      = VPAdvancedUserHelper::getActions();
		$checkedOut = !($this->item->checked_out == 0 || $this->item->checked_out == $user->get('id'));

		if($isNew)
		{
			JToolBarHelper::title(JText::_('COM_VPADVANCEDUSER') . ': ' . JText::_('COM_VPADVANCEDUSER_TITLE_ADD_CUSTOMFIELD'), 'pencil customfield');
		}
		else
		{
			JToolBarHelper::title(JText::_('COM_VPADVANCEDUSER') . ': ' . JText::_('COM_VPADVANCEDUSER_TITLE_EDIT_CUSTOMFIELD') . ' - ' . JText::_($this->item->label), 'pencil customfield');
		}

		// If not checked out, can save the item.
		if (!$checkedOut && ($canDo->get('core.edit') || ($canDo->get('core.create'))))
		{
			JToolBarHelper::apply('customfield.apply', 'JTOOLBAR_APPLY');
			JToolBarHelper::save('customfield.save', 'JTOOLBAR_SAVE');
		}

		if (!$checkedOut && ($canDo->get('core.create')))
		{
			JToolbarHelper::save2new('customfield.save2new');
		}

		// If an existing item, can save to a copy.
		if (!$isNew && $canDo->get('core.create'))
		{
			JToolbarHelper::save2copy('customfield.save2copy');
		}

		if (empty($this->item->id))
		{
			JToolBarHelper::cancel('customfield.cancel', 'JTOOLBAR_CANCEL');
		}
		else
		{
			JToolBarHelper::cancel('customfield.cancel', 'JTOOLBAR_CLOSE');
		}
	}
}
