<?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@m.herzberg
 */

namespace DJExtensions\DJCatalog2\YOOtheme\Builder\Source;

use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Multilanguage;
use Joomla\CMS\Object\CMSObject;
use YOOtheme\Str;

class CategoryHelper
{
	/**
	 * Gets the producers.
	 *
	 * @param int[] $ids
	 * @param array $args
	 *
	 * @return CMSObject[]
	 */
	public static function getItem($id){

		if (!class_exists('DJCatalog2ModelCategory')) {
			require_once JPATH_ADMINISTRATOR . '/components/com_djcatalog2/models/category.php';
		}

		$model = new \Djcatalog2ModelCategory(['ignore_request' => true]);
		$category = $model->getItem($id);
		return $category;
	}
	public static function get($ids, array $args = [])
	{
		if (!class_exists('DJCatalog2ModelCategories')) {
			require_once JPATH_ADMINISTRATOR . '/components/com_djcatalog2/models/categories.php';
		}

		$model = new DJCatalog2ModelCategories(['ignore_request' => true]);
		$model->setState('params', ComponentHelper::getParams('com_djcatalog2'));
		$model->setState('filter.id', (array) $ids);
		$model->setState('filter.access', true);
		$model->setState('filter.published', 1);
		$model->setState('filter.language', Multilanguage::isEnabled());

		foreach ($args as $name => $value) {
			$model->setState($name, $value);
		}

		$items = $model->getItems();
		return $items;
	}
	/**
	 * Query producers.
	 *
	 * @param array $args
	 *
	 * @return array
	 */
	public static function query(array $args = [])
	{
		$model = new Djcatalog2ModelCategories(['ignore_request' => true]);
		$model->setState('params', ComponentHelper::getParams('com_djcatalog2'));
		$model->setState('filter.access', true);
		$model->setState('filter.published', 1);
		$model->setState('filter.language', Multilanguage::isEnabled());
		if (!empty($args['order'])) {

			if ($args['order'] === 'rand') {
				$args['order'] = Factory::getDbo()->getQuery(true)->Rand();
			} elseif ($args['order'] === 'front') {
				$args['order'] = 'fp.ordering';
			} else {
				$args['order'] = "a.{$args['order']}";
			}
		}

		$props = [
			'offset' => 'list.start',
			'limit' => 'list.limit',
			'order' => 'list.ordering',
			'order_direction' => 'list.direction',
			'order_alphanum' => 'list.alphanum',
		];

		foreach (array_intersect_key($props, $args) as $key => $prop) {
			$model->setState($prop, $args[$key]);
		}

		if (!empty($args['catid']) && (is_array($args['catid']) && !in_array(0,$args['catid']))) {
			$filter_catid = $args['catid'];
		}
		// Filter only children categories
		if(!empty($args['onlyChildren']) && $args['onlyChildren'] == 1){
			$model->setState('filter.onlychildrencats',$args['catid'][0]);
			$filter_onlychild = $args['onlyChildren'];
		}
		if(!empty($filter_catid)  && empty($filter_onlychild)){
			$model->setState('filter.id', $filter_catid);
		}
		$cats = $model->getItems();

		if (!class_exists('DJCatalog2ImageHelper')) {
			require_once JPATH_ADMINISTRATOR . '/components/com_djcatalog2/helpers/image.php';
		}

		$gallery = array();
		$imgnames = array();
		$thumbs = array();
		$captions = array();
		//Get images for categories
		foreach ($cats as $key => $cat) {
			if(!empty($filter_onlychild)){

				if($cat->parent_id != $args['catid'][0]){
					unset($cats[$key]);
					continue;
				}
			}
			if (empty($cat->images)) {
				$images = \DJCatalog2ImageHelper::getImages('category', $cat->id);
				$url =  DJCATIMGPATH;
				foreach ($images as $image) {
					$urlX = $image->fullpath;
					$gallery[] =  $url.'/'.$urlX;
					$imgnames[] = $image->name;
					$thumbs[] = $image->thumb;
					$captions[] = $image->caption;
				}
				$cat->images = $gallery;
				$cat->img_thumbs = $thumbs;
				$cat->img_captions = $captions;
				$cat->img_names = $imgnames;
			}
		}
		return $cats;
	}
}

if (!class_exists('Djcatalog2ModelCategories')) {
	require_once JPATH_ADMINISTRATOR . '/components/com_djcatalog2/models/categories.php';
}

class Djcatalog2ModelCategories extends \Djcatalog2ModelCategories
{
	protected function getListQuery()
	{
		\JLoader::register('Djcatalog2Helper', JPATH_SITE . '/components/com_djcatalog2/helpers/djcatalog2.php');
		$id = false;
		$ordering = $this->getState('list.ordering');
		$filter_id = $this->getState('filter.id');
		$query = parent::getListQuery();
		//Change order if selected
		if ($this->getState('list.alphanum') && $ordering != 'RAND()') {
			$ordering = $this->getState('list.ordering', 'a.ordering');
			$order = $this->getState('list.direction', 'ASC');
			$query->clear('order');
			$query->order("(substr({$ordering}, 1, 1) > '9') {$order}, {$ordering}+0 {$order}, {$ordering} {$order}");

		}
		//Choose only selected cats
		if(!empty($filter_id))
			$cids = implode(',', $filter_id);
		else $cids = '';

		if(!empty($cids) ){
			$query->where('a.id IN ('. ($cids) . ')');
		}

		$query->where('a.published = 1');


		return $query;
	}
}
