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

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

			'fields' => [

				'productcategory' => [
					'type' => [
						'listOf'  => 'CategoryProduct',
					],
					'args' => [
						'catid' => [
							'type' => [
								'listOf' => 'Int',
							],
						],
						'onlyChildren' => [
							'type' => 'Boolean'
						],
					],

					'metadata' => [
						'label' => 'Categories',
						'group' => 'DJ-Catalog2',
						'fields' => [
							'_catid' => [
								'type' => 'grid',
								'width' => '1',
								'fields' => [
									'catid' => [
										'description' => "Select from which categories products should be displayed.",
										'label' => 'Limit by categories',
										'type' => 'select',
										'default' => '0',
										'options' => self::getCategoriesList(),
										'attrs' => [
											'multiple' => true,
											'class' => 'uk-select  uk-resize-vertical',
										],
									],
								],
							],
							'_onlyChildren' => [
								'type' => 'grid',
								'width' => '1',
								'fields' => [
									'onlyChildren' => [
										'description' => 'Show only children categories',
										'label' => 'Only children',
										'type' => 'checkbox'
									]
								]
							]
						],
					],
					'extensions' => [
						'call' => __CLASS__ . '::resolve',
					],
				],
			],
		];
	}

	public static function resolve($root, array $args)
	{
		$cats = self::getCategories($args);
		return $cats;
	}

	static function getCategoriesList()
	{
		if (!class_exists('Djc2Categories')) {
			\JLoader::register('Djc2Categories', JPATH_ADMINISTRATOR.DS.'components'.DS.'com_djcatalog2'.DS.'lib'.DS.'categories.php');
		}
		$categories = \Djc2Categories::getInstance();
		$productCategoriesHierarchy = $categories->getOptionList('- '.\JText::_('Select Category').' -');
		$list = array();

		foreach ($productCategoriesHierarchy as $cat) {

			$name = str_replace(array('&#34;', '&#38;'), array("'", "&"), $cat->text);
			$list[$name] = $cat->value;
		}
		return $list;
	}

	static function getCategories($cids){
		//Get categories to provided cids from Query
		return CategoryHelper::query($cids);

	}
}
