<?php

/**
 * @package         Smile Pack
 * @version         1.2.3 Pro
 * 
 * @author          Tassos Marinos <info@tassos.gr>
 * @link            http://www.tassos.gr
 * @copyright       Copyright © 2019 Tassos Marinos All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
*/

defined('_JEXEC') or die('Restricted access');

use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Factory;

class SPGalleryHelper
{
	/**
	 * Prepares the Gallery Manager Widget uploaded files prior to being passed
	 * to the Gallery Widget to display the Gallery on the front-end.
	 * 
	 * @param   array  $items
	 * @param   array  $tags
	 * 
	 * @return  array
	 */
	public static function prepareItems($items = [], $tags = [])
	{
		foreach ($items as $key => &$item)
		{
			// Skip items that have not saved properly(items were still uploading and we saved the item)
			if ($key === 'ITEM_ID')
			{
				unset($items[$key]);
				continue;
			}

			$itemTags = [];

			$stored_item_tags = isset($item['tags']) ? $item['tags'] : [];
			if (is_array($stored_item_tags) && count($stored_item_tags))
			{
				foreach ($stored_item_tags as $tagId)
				{
					if (!array_key_exists($tagId, $tags))
					{
						continue;
					}

					$itemTags[] = $tags[$tagId];
				}
			}

			$url = Uri::root() . ($item['image'] ? $item['image'] : $item['source']);
			
			$item = array_merge($item, [
				'url' =>  $url,
				'slideshow' =>  isset($item['slideshow']) && $item['slideshow'] ? Uri::root() . $item['slideshow'] : $url,
				'thumbnail_url' => $item['thumbnail'] ? Uri::root() . $item['thumbnail'] : '',
				'tags' => $itemTags
			]);
		}

		return $items;
	}

	
	/**
	 * Get the tags in the correct order.
	 * 
	 * @param   array  $items
	 * 
	 * @return  array
	 */
	public static function getOrderedTags($items)
	{
		$tags = [];

		foreach ($items as $key => &$item)
		{
			// Skip items that have not saved properly(items were still uploading and we saved the item)
			if ($key === 'ITEM_ID')
			{
				unset($items[$key]);
				continue;
			}

			$item_tags = isset($item['tags']) ? $item['tags'] : [];
			if (is_array($item_tags) && count($item_tags))
			{
				foreach ($item_tags as $tagId)
				{
					if (in_array($tagId, $tags))
					{
						continue;
					}

					$tags[] = $tagId;
				}
			}
		}

		if (!$tags)
		{
			return [];
		}
		
		// Once we have the tag IDs, we need to get them via the correct order
		$db = Factory::getDbo();
		$query = $db->getQuery(true)
            ->select(
                [
                    $db->quoteName('a.id'),
                    $db->quoteName('a.title')
                ]
            )
            ->from($db->quoteName('#__tags', 'a'))
            ->where($db->quoteName('a.lft') . ' > 0')
			->where($db->quoteName('a.id') . ' IN (' . implode(',', $tags) . ')')
            ->order($db->quoteName('a.lft') . ' ASC');
        
        $db->setQuery($query);

		// Get tags from the database
		$db_tags = $db->loadAssocList();

		// Return only the tag titles
		$tags = array_fill_keys(array_column($db_tags, 'id'), '');

		// Populate the tags list
		foreach ($tags as $id => &$value)
		{
			$tag = array_filter($db_tags, function($item) use ($id) {
				return $item['id'] == $id;
			});
			$tag = reset($tag);

			$value = isset($tag['title']) ? $tag['title'] : '';
		}

		$tags = array_filter($tags);

		return $tags;
	}
	
}