<?php
/**
 * @version    CVS: 1.0
 * @package    Com_Vpem
 * @author     Abhishek Das <info@virtueplanet.com>
 * @copyright  Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 */

// No direct access
defined('_JEXEC') or die;

jimport('joomla.application.component.controllerform');

/**
 * Template controller class.
 *
 * @since  1.6
 */
class VpemControllerTemplate extends \Joomla\CMS\MVC\Controller\FormController
{
	/**
	 * Constructor
	 *
	 * @throws Exception
	 */
	public function __construct()
	{
		$this->view_list = 'templates';
		parent::__construct();
	}
	
	public function setType()
	{
		// Check for request forgeries.
		$this->checkToken();

		$app   = JFactory::getApplication();
		$model = $this->getModel();
		$table = $model->getTable();
		$data  = $this->input->post->get('jform', array(), 'array');
		$checkin = property_exists($table, $table->getColumnAlias('checked_out'));
		$context = "$this->option.edit.$this->context";

		// Determine the name of the primary key for the data.
		if (empty($key))
		{
			$key = $table->getKeyName();
		}

		// To avoid data collisions the urlVar may be different from the primary key.
		if (empty($urlVar))
		{
			$urlVar = $key;
		}

		$recordId = $this->input->getInt($urlVar);

		// Populate the row id from the session.
		$data[$key] = $recordId;
		
		$form = $model->getForm($data, false);
		
		/**
		 * We need the filtered value of calendar fields because the UTC normalision is
		 * done in the filter and on output. This would apply the Timezone offset on
		 * reload. We set the calendar values we save to the processed date.
		 */
		$filteredData = $form->filter($data);

		foreach ($form->getFieldset() as $field)
		{
			if ($field->type === 'Calendar')
			{
				$fieldName = $field->fieldname;

				if (isset($filteredData[$fieldName]))
				{
					$data[$fieldName] = $filteredData[$fieldName];
				}
			}
		}

		// Save the data in the session.
		$app->setUserState($context . '.data', $data);
		
		// Redirect back to the edit screen.
		$this->setRedirect(
			\JRoute::_(
				'index.php?option=' . $this->option . '&view=' . $this->view_item
				. $this->getRedirectToItemAppend($recordId, $urlVar), false
			)
		);
	}
}
