<?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;
class ItemReviewsQueryType
{
	/**
	 * @return array
	 */
	public static function config()
	{
		return [

			'fields' => [
				'itemReviews' => [
					'type' => [
						'listOf' => 'ItemReviews',
					],
					'args' => [
						'offset' => [
							'type' => 'Int',
						],
						'limit' => [
							'type' => 'Int',
						],
					],
					'extensions' => [
						'call' => __CLASS__ . '::resolve',
					],
					'metadata' => [
						'label' => 'Product Reviews',
						'group' => 'DJ-Catalog2',
						'fields' => [
							'_offset' => [
								'description' => 'Set the starting point and limit the number of reviews.',
								'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,
										],
									],
								],
							],
						],
					],
				],
			],
		];
	}

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

		if (isset($root['item'])) {
			$item = $root['item'];
			$reviews = $item->_reviews;
			foreach($reviews as $r ){
				$r->rating_count = $item->rating_count;
				$r->item_name = $item->name;
			}


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

			return $reviews;
		}
	}
}
