<?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
 */

defined('_JEXEC') or die;

use Joomla\CMS\Plugin\CMSPlugin;
use YOOtheme\Application;
use Joomla\Registry\Registry;
use DJExtensions\DJCatalog2\YOOtheme\Builder\Source\DJC2YooHelper;
class plgSystemDjc2yootheme extends CMSPlugin
{
	public function onAfterInitialise()
	{
		JLoader::registerNamespace('DJExtensions\DJCatalog2\YOOtheme;', JPATH_ROOT . "/plugins/system/djc2yootheme");
		// check if YOOtheme Pro is loaded
		if (!class_exists(Application::class, false)) {
			return;
		}
		$this->loadLanguage();
		
		/* Load Needed Classes */
		require __DIR__ . '/modules/builder-djcatalog2-source/src/SourceListener.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/SourceController.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/CategoryHelper.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/ProducerHelper.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/ItemHelper.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/ItemListener.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/ProducerListener.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/TemplateListener.php';

		//Type - Producer
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Producer/ProducerCategoryType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Producer/ProducerType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Producer/ProducerImagesType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Producer/ProducerFieldsType.php';

		//QueryType - Producer
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Producer/ProducerCategoryQueryType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Producer/CustomProducerQueryType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Producer/ProducerQueryType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Producer/ProducersQueryType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Producer/ProducerImagesQueryType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Producer/ProducerFieldsQueryType.php';

		//Type - Item
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Item/ItemType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Item/ItemFilesType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Item/ItemImagesType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Item/ItemLabelsType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Item/ItemExtraFieldsType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Item/ItemSectionsType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Item/ItemReviewsType.php';

		//QueryType - Item
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Item/ItemQueryType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Item/ItemFilesQueryType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Item/ItemImagesQueryType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Item/ItemLabelsQueryType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Item/ItemExtraFieldsQueryType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Item/ItemSectionsQueryType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Item/ItemReviewsQueryType.php';

		//QueryType - Items
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Item/ItemsListQueryType.php';

		//Type - Category
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Category/CategoryProductType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Category/SingleCategoryProductType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Category/CategoryImagesType.php';

		//QueryType - Category
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Category/CategoryQueryType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Category/CategoryProductQueryType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/Category/CategoryImagesQueryType.php';


		//Type - [Other]
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/UserType.php';
		require __DIR__ . '/modules/builder-djcatalog2-source/src/UserHelper.php';

		//QueryType - [Other]
		require __DIR__ . '/modules/builder-djcatalog2-source/src/Type/SiteQueryType.php';

		//Elements
		require __DIR__ . '/modules/builder-djcatalog2-source/src/ElementHelper.php';

		//Presets
		require __DIR__ . '/modules/djcatalog2-presets/src/Presets.php';
		require __DIR__ . '/modules/djcatalog2-presets/src/Cache.php';
		require __DIR__ . '/modules/djcatalog2-presets/src/Type.php';
		require __DIR__ . '/modules/djcatalog2-presets/src/PresetTransform.php';
		require __DIR__ . '/modules/djcatalog2-presets/src/PresetsListener.php';
		require __DIR__ . '/modules/djcatalog2-presets/src/PresetSaveTransform.php';
		require __DIR__ . '/modules/djcatalog2-presets/src/PresetsController.php';

		//Layouts
		require __DIR__ . '/modules/djcatalog2-layouts/src/Layouts.php';
		require __DIR__ . '/modules/djcatalog2-layouts/src/Cache.php';
		require __DIR__ . '/modules/djcatalog2-layouts/src/Type.php';
		require __DIR__ . '/modules/djcatalog2-layouts/src/LayoutTransform.php';
		require __DIR__ . '/modules/djcatalog2-layouts/src/LayoutsListener.php';
		require __DIR__ . '/modules/djcatalog2-layouts/src/LayoutSaveTransform.php';
		require __DIR__ . '/modules/djcatalog2-layouts/src/LayoutsController.php';

		//Config
		require  __DIR__ . '/modules/config/src/ConfigListener.php';
		require __DIR__ . '/modules/config/src/ExtraFieldsController.php';
		require __DIR__ . '/modules/config/src/FormTransform.php';

		require __DIR__ .'/helper.php';
		// bootstrap modules
		$app = Application::getInstance();
		$app->load(__DIR__ . '/modules/*/bootstrap.php');
	}
	public function onBeforeRender()
	{
		$app = JFactory::getApplication();
		if ($app->isClient('site')){
			$doc = JFactory::getDocument();
			//DJ-Catalog2 Filters
			$doc->addStyleSheet(JUri::root() . '/plugins/system/djc2yootheme/assets/custom.css');
			$doc->addScript(JUri::root() . '/plugins/system/djc2yootheme/assets/custom.js');
			$doc->addScript(JUri::root() . '/plugins/system/djc2yootheme/assets/script_filters.js');
		}

	}
	public function onAfterRoute()
	{
		require_once(JPATH_ROOT.'/components/com_djcatalog2/helpers/html.php');
		require_once(JPATH_ROOT.'/components/com_djcatalog2/helpers/djcatalog2.php');
		\Djcatalog2Helper::loadComponentLanguage();

		$app = \JFactory::getApplication();
		$menu = $app->getMenu()->getActive();
		$jinput = $app->input;



		if (!$app->isClient('site') || $app->input->get('view') != 'items') return;

		$option = $jinput->get('option');
		$view = $jinput->get('view');
		$cntid = $jinput->get('cntid');
		$stid = $jinput->get('stid');
		$cid = $jinput->getInt('cid');


		$cats = DJC2YooHelper::getCategoriesFlat($cid);
		$catIds = array_keys($cats);
		$catIds = ((count($catIds)) ? $catIds : array($cid));





		if ($option !== 'com_djcatalog2' && $view !== 'items') {
			return false;
		}

		$params = new Registry();
		$params->set('catsw', 1);
		$params->set('categories', $catIds);

		$attributes = DJC2YooHelper::getData($params, false);
		$urlVarNames = array();
		$urlVarValues = array();
		$request = array();

		foreach ($attributes as $group) {
			foreach ($group->attributes as $attribute) {
				$urlVarNames[$attribute->alias] = $attribute->id;
			}
		}


		foreach ($urlVarNames as $attributeAlias => $attributeId) {
			$tmpValue = $app->input->getRaw($attributeAlias);
			if(is_array($tmpValue))continue;
			if ($tmpValue) {
				$filteredValue = array_filter(explode(',', $tmpValue));
				$request[$attributeAlias] = $filteredValue;
				$urlVarValues[$attributeId] = $filteredValue;
			}
		}

		$search = trim($app->input->getRaw('search'));

		if (count($urlVarValues) || $search) {
			// Search categories
			$db = \JFactory::getDbo();
			$query = $db->getQuery(true);

			$user = \JFactory::getUser();
			$levels = $user->getAuthorisedViewLevels();
			$lang = \JFactory::getLanguage();
			$tag = $lang->getTag();


			$query
				->select('i.id, i.cat_id ')
				->from($db->quoteName('#__djc2_categories', 'cat'))
				->join('INNER', $db->quoteName('#__djc2_items', 'i') . ' ON i.cat_id = cat.id')
				->where('cat.published = 1')
				->where('cat.access IN (' . implode(',', $levels) . ')')
				->where('(cat.language = ' . $db->quote('*') . ' OR cat.language = ' . $db->quote($tag) . ')')
				->where('i.published = 1')
				->where('i.access IN (' . implode(',', $levels) . ')')
				->where('(i.language = ' . $db->quote('*') . ' OR i.language = ' . $db->quote($tag) . ')');

			if ($search) {
				$like = $db->quote('%' . $db->escape($search) . '%');
				$query->where('(i.name LIKE ' . $like . ' OR i.description LIKE ' . $like . ' OR i.sections LIKE ' . $like . ')');
			}


			if (count($urlVarValues)) {
				foreach ($urlVarValues as $attributeId => $attributeValues) {
					$or = array();
					foreach ($attributeValues as $attributeValue) {
						$or[] = 'f' . $attributeId . '.value = ' . $attributeValue;
					}

					$query->select('f' . $attributeId . '.value AS val_' . $attributeId);
					$query->join('INNER', $db->quoteName('#__djc2_items_extra_fields_values_int', 'f' . $attributeId) . ' ON f' . $attributeId . '.item_id = i.id AND f' . $attributeId . '.field_id = ' . $attributeId . ((count($or)) ? ' AND (' . implode(' OR ', $or) . ')' : ''));
				}
			}


			$db->setQuery($query);
			$items = $db->loadObjectList('id');


			$categories = array();
			$itemIds = array_keys($items);

			if (count($itemIds)) {
				foreach ($items as $item) {


					if (!in_array($item->cat_id, $categories)) $categories[] = $item->cat_id;
				}

			}


			$currentLevelCategories = $categories;
			$reversed = false;
			do {
				$tmpCategories = array();

				foreach ($currentLevelCategories as $category) {
					if (isset($cats[$category])) {
						if (!in_array($cats[$category]->parent_id, $categories)) {
							$categories[] = $cats[$category]->parent_id;
							$tmpCategories[] = $cats[$category]->parent_id;
						}
					}
				}

				if (count($tmpCategories)) {
					$currentLevelCategories = $tmpCategories;
				} else {
					$reversed = true;
				}

			} while (!$reversed);


			$filters = $request;
			$request = DJC2YooHelper::buildUrlRequest($request);


			$app->input->set($menu->id . '.djcatalog2.request', $request);
			$app->input->set($menu->id . '.djcatalog2.filters', $filters);
			$app->input->set($menu->id . '.djcatalog2.cid', $categories);
			$app->input->set($menu->id . '.djcatalog2.ids', $itemIds);

		}

		$app->input->set($menu->id . '.djcatalog2.attributes', json_encode($attributes));
		$app->input->set($menu->id . '.djcatalog2.variables', json_encode($urlVarValues));
	}
}