<?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;
defined('_JEXEC') or die;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Multilanguage;
use Joomla\CMS\Object\CMSObject;
use YOOtheme\Str;

class ItemHelper
{
	/**
	 * Gets the producers.
	 *
	 * @param int[] $ids
	 * @param array $args
	 *
	 * @return CMSObject[]
	 */
	public static function get($ids, array $args = [])
	{
		if (!class_exists('DJCatalog2ModelItems')) {
			require_once JPATH_ROOT . '/components/com_djcatalog2/models/items.php';
		}

		$model = new DJCatalog2ModelItems(['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 DJCatalog2ModelItems(['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());

		$order = $args['order'];
		$order_Dir = $args['order_dir'];
		$props = [
			'offset' => 'list.start',
			'limit' => 'list.limit',
			'order_alphanum' => 'list.alphanum',
		];


		foreach (array_intersect_key($props, $args) as $key => $prop) {
			$model->setState($prop, $args[$key]);
		}
		$model->setState('list.ordering',$args['order']);
		$model->setState('list.direction',$order_Dir);
		if ($order == 'bestsellers.bestcount') {
			$model->setState('filter.bestsellers', true);
		}
		if (!empty($args['catid']) && !in_array(0,$args['catid'])) {
			$filter_catid = $args['catid'];
		}

		if (!empty($args['featured'])) {
			$model->setState('filter.featured', $args['featured']);
		}

		if(!empty($args['idsChosen'])) {
			$ids = $args['idsChosen'];
			$filter_itemids = $ids;
		}

		//Recent | Related limitation

		if(!empty($args['recent'])){
			$recent = $args['recent'];
		}else{
			$recent = false;
		}

		if(!empty($args['related']))
		{
			$related = $args['related'];
		}else {
			$related = false;
		}

		if(!empty($args['pids']))
		{
			if($args['pids'][0] != 0)
				$filter_producerid = $args['pids'][0];
		}

		$db = \JFactory::getDbo();
		$app = \JFactory::getApplication();
		$id = $app->input->get('id', '', 'int');

		if ($recent) {
			$recentItems = \Djcatalog2Helper::getRecentItems();
			if (empty($recentItems)) {
				return array('items'=>array(), 'attributes'=> array());
			}
			$filter_itemids = implode(',', $recentItems);
		} else if ($related) {
			$s = $args['relatedOptions'][0];
			switch($s){
				case 0:
					$source = 'related';
					break;
				case 1:
					$source = 'category';
					break;
				case 2:
					$source = 'producer';
					break;
				case 3:
					$source = 'catnprod';
					break;
			}

			if ($source == 'category' || $source == 'catnprod') {
				if (!empty($args['catid']))
					$filter_catid = $app->input->getInt('cid');
			}

			if ($source == 'producer' || $source == 'catnprod') {
				$db->setQuery('select producer_id from #__djc2_items where id='.(int)$id);
				$filter_producerid = (int)$db->loadResult();
				if($filter_producerid == 0) unset($filter_producerid);

			}

			if ($source == 'related') {
				$db->setQuery('select related_item from #__djc2_items_related where item_id='.(int)$id);
				$relatedIds = $db->loadColumn();

				if (is_array($relatedIds) && count($relatedIds)) {
					$filter_itemids = implode(',', $relatedIds);
				} else {
					return array('items'=>array(), 'attributes'=> array());
				}
			}else {
				$model->setState('filter.not_item_ids', array($id));
			}
		}

		if (!empty($filter_itemids)) {
			$filter_itemids = explode(',', $filter_itemids);
			$ids = array();
			foreach($filter_itemids as $k=>$v) {
				$v = trim($v);
				if ((int)$v > 0) {
					$ids[] = (int)$v;
				}
			}
			if (!empty($ids)) {
				$ids = array_unique($ids);
				$model->setState('filter.item_ids', $ids);
			}
		}

		if(!empty($filter_catid)){
			$model->setState('filter.category', $filter_catid);
		}

		if(!empty($filter_producerid)){
			$model->setState('filter.producer', $filter_producerid);
		}


		$items = $model->getItems();
		if (!class_exists('DJCatalog2ImageHelper')) {
			require_once JPATH_ADMINISTRATOR . '/components/com_djcatalog2/helpers/image.php';
		}
		if(!empty($args['children'])){
			$modelItem = new \DJCatalog2ModelItem(['ignore_request' => true]);
			$id = $app->input->get('id', '', 'array');
			if(!empty($id)){
				$idString = $id[0];
				$id = explode(":",$idString);
				$id = $id[0];
			}
			$items = $modelItem->getChildren($id);
		}
		return $items;
	}

	static function getExtraFields($item = null)
	{
		if (!class_exists('Djcatalog2Modelitem')) {
			require_once JPATH_SITE . '/components/com_djcatalog2/models/item.php';
		}
		$model = \JModelLegacy::getInstance('item', 'DJCatalog2Model', ['ignore_request' => true]);
		if (!is_null($item))
			$model->setState('item.id', $item->id);

		//Gain all available extra fields for available item
		$extraFields = $model->getAttributes();
		return $extraFields;
	}

	static function getExtraFieldsOptionsList($fieldId){
		$db = \JFactory::getDbo();
		$db->setQuery('SELECT id,value,params FROM #__djc2_items_extra_fields_options WHERE field_id = '.$fieldId);
		$extraFieldsOptions = $db->loadObjectList();
		return $extraFieldsOptions;
	}

	static function getExtraField($fieldId){
		if(!isset($fieldId) && !$fieldId) return '';
		$db = \JFactory::getDbo();
		$db->setQuery('SELECT * FROM #__djc2_items_extra_fields WHERE id = '. $fieldId);
		$extraField = $db->loadObject();
		$extraField->options = self::getExtraFieldsOptionsList($fieldId);
		return $extraField;
	}

	static function getExtraFieldType($type){
		if($type == 'checkboxes'){
			$typeCheckbox = 'checkbox';
			$db = \JFactory::getDbo();
			$db->setQuery('SELECT * FROM #__djc2_items_extra_fields WHERE filter_type = "'.$typeCheckbox.'" 
			OR (type = "'.$typeCheckbox.'" AND filter_type = "checkbox_or" ) OR (type = "'.$typeCheckbox.'" AND filter_type = "")');
			$extraFieldType = $db->loadObjectList();
			return $extraFieldType;
		}elseif($type == 'color'){
			$db = \JFactory::getDbo();
			$db->setQuery('SELECT * FROM #__djc2_items_extra_fields WHERE type = "color" OR type = "multicolor"');
			$extraFieldType = $db->loadObjectList();
			return $extraFieldType;
		}
		else {
			$db = \JFactory::getDbo();
			$db->setQuery('SELECT * FROM #__djc2_items_extra_fields WHERE filter_type ="'.$type.'" 
			OR (type = "'.$type.'" AND filter_type = "")');
			$extraFieldType = $db->loadObjectList();
			return $extraFieldType;
		}
	}

	static function getExtraFieldsOptions()
	{
		$db = \JFactory::getDbo();
		$db->setQuery('SELECT id, name, language FROM #__djc2_items_extra_fields ORDER BY language');
		$extraFields = $db->loadObjectList();
		$list =  array();

		foreach ($extraFields as $extraField) {
			$fieldName = str_replace(array('&#34;', '&#38;'), array("'", "&"), $extraField->name) . (($extraField->language != '*') ? ' (' . $extraField->language . ')' : '');
			$list[$fieldName] = $extraField->id;
		}


		return $list;
	}

}

if (!class_exists('DJCatalog2ModelItems')) {
	require_once JPATH_ROOT . '/components/com_djcatalog2/models/items.php';
}

class DJCatalog2ModelItems extends \DJCatalog2ModelItems
{
	protected function getListQuery()
	{

		\JLoader::register('Djcatalog2Helper', JPATH_SITE . '/components/com_djcatalog2/helpers/djcatalog2.php');
		$id = false;
		$db = \JFactory::getDbo();
		$ordering = $this->getState('list.ordering');
		$order = $this->getState('list.direction');
		$query = parent::getListQuery();

		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}");
		}
		if($ordering == 'rating') {
			$query->join('LEFT', $db->quoteName('#__djc2_item_rating', 'ra') . 'ON' . $db->quoteName('i.id') . ' = ' . $db->quoteName('ra.item_id'));
			$query->clear('order');
			$query->order("ra.rating_sum {$order}");
		}
		return $query;
	}
}
