<?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\Type\Producer;
defined('_JEXEC') or die;
use DJExtensions\DJCatalog2\YOOtheme\Builder\Source\ProducerHelper;

class ProducersQueryType
{
	/**
	 * @return array
	 */
	public static function config()
	{
		return [

			'fields' => [

				'producers' => [
					'type' => [
						'listOf' => 'Producer',
					],
					'args' => [
						'catid' => [
							'type' => [
								'listOf' => 'String',
							],
						],
						'offset' => [
							'type' => 'Int',
						],
						'limit' => [
							'type' => 'Int',
						],

					],
					'metadata' => [
						'label' => 'Producers',
						'group' => 'DJ-Catalog2',
						'fields' => [
							'_catid' => [
								'type' => 'grid',
								'width' => '1',
								'fields' => [
									'catid' => [
										'description' => "Select from which categories producers should be displayed.",
										'label' => 'Limit by categories',
										'type' => 'select',
										'default' => '0',
										'options' => self::getProducerCategoriesList(),
										'attrs' => [
											'multiple' => true,
											'class' => 'uk-select',
										],
									],
								],
							],
							'_offset' => [
								'description' => 'Set the starting point and limit the number of producers.',
								'type' => 'grid',
								'width' => '1-2',
								'fields' => [
									'offset' => [
										'label' => 'Start',
										'type' => 'number',
										'default' => 0,
										'modifier' => 1,
										'attrs' => [
											'min' => 1,
											'required' => true,
										],
									],
									'limit' => [
										'label' => 'Quantity',
										'type' => 'limit',
										'attrs' => [
											'placeholder' => 'No limit',
											'min' => 0,
										],
									],

								],
							],
						],
					],
					'extensions' => [
						'call' => __CLASS__ . '::resolve',
					],
				],

			],

		];
	}

	public static function resolve($root, array $args)
	{
		$args += [
			'offset' => 0,
			'limit' => null,
		];
		$categoriesChosen = array();

		//Handle using producers query type in itemList context
		$isProductsContext = false;
		foreach ($root['parent']->children as $child){
			if(isset($child->source))
				if($child->source->query->name == "itemList")
					$isProductsContext = true;

		}

		if (isset($root['items']) && $isProductsContext) {
			$list_products = $root['items'];
			$items = $list_products;

			//Filter by choosen categories
			if(!empty($args['catid'])) {
				foreach($items as $item){
					if(in_array($item->cat_id,$args['catid'])){
						array_push($categoriesChosen, $item);
					}else continue;
				}
			} else $categoriesChosen = $root['items'];

			//Limit producers if set
			if ($args['offset'] || $args['limit']) {
				$categoriesChosen = array_slice($categoriesChosen, (int)$args['offset'], (int)$args['limit'] ?: null);
			}
			return $categoriesChosen;
		} else{
			return ProducerHelper::query($args);
		}
	}

	static function getProducerCategories()
	{
		if (!class_exists('Djcatalog2ModelProducerCategories')) {
			require_once JPATH_ADMINISTRATOR . '/components/com_djcatalog2/models/producercategories.php';
		}
		$model = \JModelLegacy::getInstance('ProducerCategories', 'DJCatalog2Model', ['ignore_request' => true]);
		return $model->getItems();
	}


	//Create tree type array according to 'parent_id' value
	static function buildTree($items)
	{
		// TODO: zmiana/olo
		if (empty($items) || !is_array($items)) return array();

		$children = array();
		foreach($items as $item) {
			$children[$item->parent_id][] = $item;
		}
		foreach($items as $item) {
			if (isset($children[$item->id])) {
				$item->children = $children[$item->id];
			}
		}
		return $children[0];
	}

	//Generate levels for a tree type array
	static function generateLevel($items, $level,$order){
		// TODO: zmiana/olo
		if (empty($items) || !is_array($items)) return array();

		foreach($items as $item){
			$item->order = $order;
			$order++;
			if(!empty($item->children)){
				$item->level = $level;
				static::generateLevel($item->children,$level+1,$order);
			}else {
				$item->level = $level;
				continue;
			}
		}
		return $items;
	}

	//Used to flat the tree type array
	static function flatten($arr) {
		// TODO: zmiana/olo
		if (empty($arr) || !is_array($arr)) return array();

		$result = [];
		foreach($arr as $item) {
			if (isset($item->children))
				$result = array_merge($result, static::flatten($item->children));
			unset($item->children);
			$result[] = $item;
		}
		return $result;
	}


	static function getProducerCategoriesList()
	{
		$producerCategories = static::getProducerCategories();

		// TODO: zmiana/olo
		if (empty($producerCategories) || !is_array($producerCategories)) return array();

		$list = array();
		$producerCategories = static::buildTree($producerCategories);
		$producerCategoriesHierarchy = static::generateLevel($producerCategories,0,0);
		$producerCategoriesHierarchy = static::flatten($producerCategoriesHierarchy);

		//Sort by order
		usort($producerCategoriesHierarchy, function($a, $b) {
			return $a->order <=> $b->order;
		});
		foreach ($producerCategoriesHierarchy as $cat) {
			$newName = '';
			for($i = 0; $i< ($cat->level); $i++){
				$newName .= '|-';
			}
			$newName .= " ".$cat->name;
			$cat->name = $newName;
			$name = str_replace(array('&#34;', '&#38;'), array("'", "&"), $cat->name);
			$list[$name] = $cat->id;
		}
		return $list;
	}
}
