<?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\Item;
defined('_JEXEC') or die;
require_once JPATH_ROOT . '/components/com_djcatalog2/helpers/djcatalog2.php';

use DJExtensions\DJCatalog2\YOOtheme\Builder\Source\Djcatalog2ModelProducers;
use DJExtensions\DJCatalog2\YOOtheme\Builder\Source\ItemHelper;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use DJExtensions\DJCatalog2\YOOtheme\Builder\Source\ProducerHelper;

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

			'fields' => [
				'itemList' => [
					'type' => [
						'listOf' => 'Item',
					],
					'args' => [
						'ids' => [
							'type' => [
								'listOf' => 'String',
							],
						],
						'idsChosen' => [
							'type' => 'String',
						],
						'catid' => [
							'type' => [
								'listOf' => 'Int',
							],
						],
						'pids' => [
							'type' => [
								'listOf' => 'Int',
							],
						],
						'order' => [
							'type' => 'String',
						],
						'order_dir' => [
							'type' => 'String',
						],
						'offset' => [
							'type' => 'Int',
						],
						'limit' => [
							'type' => 'Int',
						],
						'featured' => [
							'type' => 'Boolean',
						],
						'skip_context' => [
							'type' => 'Boolean',
						],
						'recent' => [
							'type' => 'Boolean',
						],
						'children' => [
							'type' => 'Boolean',
						],
						'related' => [
							'type' => 'Boolean',
						],
						'relatedOptions' => [
							'type' => [
								'listOf' => 'String',
							],
						],
					],
					'metadata' => [
						'label' => 'Products - List View',
						'group' => 'DJ-Catalog2',
						'fields' => [
							'_skip_context' => [
								'description' => 'Skip dynamic context',
								'type'=>'grid',
								'width'=>'auto',
								'fields' => [
									'skip_context' => [
										'label' => 'Skip context',
										'type' => 'checkbox',
										'text' => 'Yes',
									]
								]
							],
							'_offset' => [
								'description' => 'Set the starting point and limit the number of products.',
								'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,
										],
									],

								],
							],
							'_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::getProductCategoriesList(),
										'attrs' => [
											'multiple' => true,
											'class' => 'uk-select  uk-resize-vertical',
										],
									],
								],
							],
							'_idsChosen' => [
								'type' => 'grid',
								'width' => '1',
								'fields' => [
									'idsChosen' => [
										'description' => "Limit products by given id.",
										'label' => 'Limit by ids',
										'type' => 'text',

									],
								],
							],
							'_pids' => [
								'type' => 'grid',
								'width' => '1',
								'fields' => [
									'pids' => [
										'description' => "Select from which producers products should be displayed.",
										'label' => 'Limit by producers',
										'type' => 'select',
										'default' => '0',
										'options' => self::getProducersList(),
										'attrs' => [
											'multiple' => false,
											'class' => 'uk-select  uk-resize-vertical',
										],
									],
								],
							],
							'_order' => [
								'type' => 'grid',
								'width' => '1',
								'fields' => [
									'order' => [
										'description' => "Select an order for products.",
										'label' => 'Order by',
										'type' => 'select',
										'default' => '0',
										'options' => [
											'Default' => '0',
											'Name' => 'i.name',
											'Price' => 'i.price',
											'Date' => 'i.created',
											'Modify date' => 'i.modified',
											'Visits' => 'i.hits',
											'Random' => 'random',
											'Best-selling' => 'bestsellers.bestcount',
											'Rating' => 'rating'
										],
										'attrs' => [
											'multiple' => false,
											'class' => 'uk-select  uk-resize-vertical',
										],
									],
								],
							],
							'_order_dir' => [
								'type' => 'grid',
								'width' => '1',
								'fields' => [
									'order_dir' => [
										'label' => 'Order direction',
										'type' => 'select',
										'default' => 'asc',
										'options' => [
											'Ascending' => 'asc',
											'Descending' => 'desc'
										],
										'attrs' => [
											'multiple' => false,
											'class' => 'uk-select  uk-resize-vertical',
										],
									],
								],
							],
							'_featured' => [
								'description' => 'Select if featured products should be displayed.',
								'type' => 'grid',
								'width' => 'auto',
								'fields' => [
									'featured' => [
										'label' => 'Featured only',
										'type' => 'checkbox',
										'text' => 'Yes',
									],
									'recent' => [
										'label' => 'Recently viewed',
										'type' => 'checkbox',
										'text' => 'Yes',
										'show' => '!related',
									],
									'related' => [
										'label' => 'Only related products',
										'type' => 'checkbox',
										'text' => 'Yes',
										'show' => '!recent',
									],
									'children' => [
										'label' => 'Only children products',
										'type' => 'checkbox',
										'text' => 'Yes',
										'show' => '!recent && !related && !featured'
									],
								],
							],
							'_relatedOptions' => [
								'description' => 'By default only products actually assigned as `related` will be shown on a product page. However, you can bypass this behaviour and list products simply from the same category as displayed product.',
								'type' => 'grid',
								'width' => 'auto',
								'fields' => [
									'relatedOptions' => [
										'label' => 'Actually marked as related',
										'type' => 'select',
										'show' => 'related',
										'default' => '0',
										'options' => [
											'Actually marked as related' => '0',
											'Same category' => '1',
											'Same producer' => '2',
											'Same category and producer' => '3',
										],
										'attrs' => [
											'multiple' => false,
											'class' => 'uk-select',
										],
									],
								],
							],
						],
					],
					'extensions' => [
						'call' => __CLASS__ . '::resolve',
					],
				],
			],
		];
	}

	public static function resolve($root, array $args)
	{
		$args += [
			'offset' => 0,
			'limit' => null,
			'featured' => 0,
			'catid' => null,
			'pids' => null,
			'idsChosen' => null,
			'order' => 0,
			'order_dir' => 'asc',
			'skip_context' => 0,
		];

		if (isset($root['items']) && empty($args['skip_context'])) {
			$items = $root['items'];
			//Filter by choosen ids
			$itemsChosen = array();
			if(!empty($args['idsChosen'])) {
				$idsChosen = explode(',',$args['idsChosen']);
				foreach($items as $item){
					if(in_array($item->id,$idsChosen)){
						array_push($itemsChosen, $item);
					}else continue;
				}
				$items = $itemsChosen;
			}

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

			//Filter by choosen producers
			$producersChosen = array();
			if(!empty($args['pids']) && !in_array(0,$args['pids'])) {
				foreach($items as $item){
					if(in_array($item->producer_id,$args['pids'])){
						array_push($producersChosen, $item);
					}else continue;
				}
				$items = $producersChosen;
			}

			//Select only featured products if this option is checked
			if ($args['featured'] == 1) {
				$featuredItems = array();
				foreach ($items as $item) {
					if ($item->featured == $args['featured']) {
						$featuredItems[] = $item;
					}
				}
				$items = $featuredItems;
			}

			foreach ($items as $item) {
				$gallery = array();
				if (empty($item->images)) {
					$images = \DJCatalog2ImageHelper::getImages('item', $item->id);
					$url =  DJCATIMGPATH;
					foreach ($images as $image) {
						$urlX = $image->fullpath;
						$gallery[] =  $url.'/'.$urlX;
					}
					$item->images = $gallery;
				}
			}

			if ($args['offset'] || $args['limit']) {
				$items = array_slice($items, (int)$args['offset'], (int)$args['limit'] ?: null);
			}

			return $items;
		} else {
			// For using dynamic content in theme (ex. article)
			$items = ItemHelper::query($args);
			//Assing images
			foreach ($items as $item) {
				if(!isset($item->id)) {
					unset($items);
					break;
				}
				$gallery = array();
				if (empty($item->images) ) {
					$images = \DJCatalog2ImageHelper::getImages('item', $item->id);
					$url =  DJCATIMGPATH;
					foreach ($images as $image) {
						$urlX = $image->fullpath;
						$gallery[] =  $url.'/'.$urlX;
					}
					$item->images = $gallery;
				}
			}

			return $items;
		}
	}

	static function getProducers()
	{
		$producers = ProducerHelper::query([null]);

		return $producers;
	}

	static function getProductCategoriesList()
	{
		$categories = \Djc2Categories::getInstance();
		$cats = $categories->categories;
		$productCategoriesHierarchy = $categories->getOptionList('- '.\JText::_('Select Category').' -');


		$catsAlias = [];
		$catsLang = [];

		foreach($cats as $c){
			if($c->published == 1){
				$catsAlias[$c->id] = $c->alias;
				$catsLang[$c->id] = $c->language;
			}

		}
		$name = '';
		$listCat = array();
		$listCat['- Select Category -'] = 0;
		foreach ($productCategoriesHierarchy as $cat) {
			if(!isset($catsAlias[$cat->value])) continue;
			$name = str_replace(array('&#34;', '&#38;'), array("'", "&"), $cat->text);
			$lang =   (($catsLang[$cat->value] != '*' && !empty($catsLang[$cat->value])) ? (' (' . $catsLang[$cat->value] . ')') : '');
			$c = new \stdClass();

			// For duplicate names provide additional alias
			if(isset($listCat[$name.' '.$lang])){
				$listCat[$name.' '. ' |'.$catsAlias[$cat->value].'|'.' '.$lang] = $cat->value;
			}else $listCat[$name.' '.$lang] = $cat->value;
		}
		return $listCat;
	}

	static function getProducersList()
	{
		$producers = static::getProducers();
		$listProd = array();
		//Sort by order
		usort($producers, function($a, $b) {
			return $a->id <=> $b->id;
		});
		$listProd['--All--'] = 0;
		foreach ($producers as $producer) {
			$name = str_replace(array('&#34;', '&#38;'), array("'", "&"), $producer->name);
			$lang =   (($producer->language != '*' && !empty($producer->language)) ? (' (' . $producer->language . ')') : '');
			$listProd[$name.' '.$lang] = $producer->id;
		}
		return $listProd;
	}
}
