<?php
/** 
 *------------------------------------------------------------------------------
 * @package       T4 Page Builder for Joomla!
 *------------------------------------------------------------------------------
 * @copyright     Copyright (C) 2004-2020 JoomlArt.com. All Rights Reserved.
 * @license       GNU General Public License version 2 or later; see LICENSE.txt
 * @authors       JoomlArt, JoomlaBamboo, (contribute to this project at github 
 *                & Google group to become co-author)
 *------------------------------------------------------------------------------
 */

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\BaseController;

JLoader::registerNamespace('JPB', JPATH_ADMINISTRATOR . '/components/com_t4pagebuilder/libs', false, false, 'psr4');
JLoader::register('T4pagebuilderHelper', JPATH_COMPONENT_ADMINISTRATOR . '/helpers/t4pagebuilder.php');
JLoader::register('FrontEndT4pagebuilderHelper', __DIR__ . '/helpers/helpers.php');
// required define
if (file_exists(JPATH_ADMINISTRATOR . '/components/com_t4pagebuilder/define.php')) {
	require_once JPATH_ADMINISTRATOR . '/components/com_t4pagebuilder/define.php';
}

$input = Factory::getApplication()->input;

// by pass other task
$input->set('view', 'page');

$user  = Factory::getUser();

$checkCreateEdit = ($input->get('view') === 'pages' && $input->get('layout') === 'modal') || ($input->get('view') === 'page' && $input->get('layout') === 'pagebreak');

if ($checkCreateEdit)
{
	// Can create in any category (component permission) or at least in one category
	$canCreateRecords = $user->authorise('core.create', 'com_t4pagetbuilder')
		|| count($user->getAuthorisedCategories('com_t4pagetbuilder', 'core.create')) > 0;

	// Instead of checking edit on all records, we can use **same** check as the form editing view
	$values = (array) Factory::getApplication()->getUserState('com_t4pagetbuilder.edit.page.id');
	$isEditingRecords = count($values);

	$hasAccess = $canCreateRecords || $isEditingRecords;

	if (!$hasAccess)
	{
		Factory::getApplication()->enqueueMessage(Text::_('JERROR_ALERTNOAUTHOR'), 'warning');

		return;
	}
}
Factory::getDocument()->addScriptDeclaration('var site_root_url = "' . Uri::root() . '"; ');
$controller = BaseController::getInstance('t4pagebuilder');
$controller->execute(Factory::getApplication()->input->get('task'));
$controller->redirect();
