<?php
/**
 * @package DJ-Catalog2-Yootheme
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 */

namespace DJExtensions\DJCatalog2\YOOtheme\Builder\Source;
defined('_JEXEC') or die;
use Joomla\CMS\Application\CMSApplication;
use Joomla\CMS\Factory;
use Joomla\CMS\Helper\TagsHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Model\BaseDatabaseModel;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\User\User;
use Joomla\Component\Content\Site\Helper\RouteHelper;
use Joomla\Input\Input;
use YOOtheme\Builder;
use YOOtheme\Config;
use YOOtheme\Http\Request;
use YOOtheme\Http\Response;
use YOOtheme\Metadata;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Language\Multilanguage;
use YOOtheme\Path;
use YOOtheme\Url;
use YOOtheme\Builder\Joomla\ContentListener;

class ProducerListener
{
	const PATTERN = '/^<!-- (\{.*\}) -->/';

	/**
	 * @var User
	 */
	protected $user;

	public function prepareContent(Config $config, CMSApplication $application, Session $session, Builder $builder, $event)
	{
		list($producer, $params) = $event->getArguments();
		static $first = true;
		if (!$first || !static::isProducerView()) {
			return;
		}
		// Make sure this is executed only once
		$first = false;

		if ($this->user) {
			$session->set('user', $this->user);
		}
		if(isset($producer->producer_layout))
			$content = preg_match(self::PATTERN, $producer->producer_layout, $matches) ? $matches[1] : null;
		else $content = '';

		if ($config('app.isCustomizer')) {

			if ($page = $config('req.customizer.page')) {
				if ($producer->id === $page['id']) {
					$content = !empty($page['content']) ? json_encode($page['content']) : null;
				} else {
					unset($page);
				}
			}

			$modified = !empty($page);
			$config->add('customizer.page', [
				'id' => $producer->id,
				'title' => $producer->name,
				'content' => $content ? $builder->load($content) : $content,
				'modified' => $modified,
				'collision' => $this->getCollisionInfo($producer),
			]);

		}
		if ($content) {
			// Render builder output
			$producer->producer_layout = $builder->render($content, [
				'prefix' => 'page',
				'producer' => $producer,
			]);

			// Used to determine active builder layout in html/helpers.php
			$config->set('app.isBuilder', true);
		}
	}

	public static function loadTemplate(Config $config, $event)
	{
		if (!$config('app.isBuilder')) {
			return;
		}
		list($view) = $event->getArguments();

		$layout = $view->getLayout();
		$context = $view->get('context');
		if ($context !== 'com_djcatalog2.producer' || $layout !== 'default') {
			return;
		}


		$producer = $view->get('item');

		$content = $producer->producer_layout;

		$view->set('_output', $content);
	}

	public function savePage(Request $request, Response $response, Builder $builder)
	{
		$request->abortIf(!$page = $request('page'), 400)
			->abortIf(!$page = base64_decode($page), 400)
			->abortIf(!$page = json_decode($page), 400);

		\JTable::addIncludePath(JPATH_ROOT.'/administrator/components/com_djcatalog2/tables');
		if (!class_exists('DJCatalog2ImageHelper')) {
			require_once JPATH_ADMINISTRATOR . '/components/com_djcatalog2/helpers/image.php';
		}
		if (!class_exists('DJCatalog2TableProducers')) {
			require_once JPATH_ADMINISTRATOR . '/components/com_djcatalog2/tables/producers.php';
		}
		if (!class_exists('DJCatalog2ModelProducer')) {
			require_once JPATH_ADMINISTRATOR . '/components/com_djcatalog2/models/producer.php';
		}

		$model = new \Djcatalog2ModelProducer(['ignore_request' => true]);
		$producer = $model->getItem((int)$page->id); // $page->page->id is producer's id
		$data = [
			'id' => $page->id,
			'producer_layout' => '',
			'alias' => $producer->alias
		];
		if ((array) $page->content) {
			if(!isset($page->content->type)){
				$content = '';
				$data['producer_layout'] = '';
			}else {
				$content = json_encode($page->content);
				$fulltext = json_encode($builder->withParams(['context' => 'save'])->load($content));
				$data['producer_layout'] = "<!-- {$fulltext} -->";
			}
		}

		// JPATH_COMPONENT constant isn't set yet
		if (!defined('JPATH_COMPONENT')) {
			define('JPATH_COMPONENT', JPATH_BASE . '/components/com_ajax');
		}

		$request->abortIf(!$this->allowEdit($producer), 403, 'Insufficient User Rights.');

		$collision = self::getCollisionInfo($producer);

		$model->save($data);

		// reload article after save
		$producer = $model->getItem($page->id);

		return $response->withJSON([
			'id' => $page->id,
			'collision' => self::getCollisionInfo($producer),
		]);
	}

	protected static function getCollisionInfo($producer)
	{
		$user = Factory::getUser($producer->created_by);
		$modifiedBy = $user ? $user->username : '';
		if(isset($producer->producer_layout))
			return [
				'contentHash' => md5($producer->producer_layout . $producer->description),
				'modifiedBy' => $modifiedBy,
			];
	}

	protected function allowEdit($producer)
	{
		$user = Factory::getUser();
		$asset = "com_djcatalog2.producer.{$producer->id}";

		return $user->authorise('core.edit', $asset)
			|| $user->authorise('core.edit.own', $asset)
			&& $user->get('id') == $producer->created_by;
	}

	protected function isProducerView() {
		$input = Factory::getApplication()->input;

		return $input->getCmd('option') === 'com_djcatalog2' && $input->getCmd('view') === 'producer' && is_null($input->getCmd('task'));
	}
}
