<?php
/**
 * @version        1.23.0
 * @package        Joomla
 * @subpackage     EDocman
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2011 - 2024 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */
// no direct access
defined('_JEXEC') or die();

use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Multilanguage;
use Joomla\CMS\Menu\MenuItem;

require_once JPATH_ROOT.'/components/com_edocman/helper/helper.php';

class EDocmanHelperRoute
{
    protected static $config;
	protected static $lookup;
    protected static $documents;
	protected static $items;
	/**
	 * 
	 * Function to get Document Route
	 * @param int $id
	 * @param int $catId
	 * @return string
	 */
	public static function getDocumentRoute($id, $catId = 0, $itemId = 0, $extra=null, $language = null, $find_menu_item = true)
	{
		$db = Factory::getContainer()->get('db');
        $query = $db->getQuery(true);
		$needles = array (
			'document'  => array((int) $id)
		);
		$link = 'index.php?option=com_edocman&view=document&id=' . $id.$extra;
		if (!$catId)
        {
            //Find the main category of the document
            $query->select('category_id')
                ->from('#__edocman_document_category AS a')
                ->where('document_id='.(int)$id)
                ->where('is_main_category=1');
            $db->setQuery($query);
            $catId = (int)$db->loadResult();
        }
		if ($catId)
		{
			$needles['category'] = self::getCategoriesPath($catId, 'id', false);
			$needles['categories'] = $needles['category'];
			$link .= '&catid=' . $catId;

			$query->clear()->select('menu_id')->from('#__edocman_categories')->where('id='.$catId);
			$db->setQuery($query);
			$menu_id = $db->loadResult();
			//EdocmanHelper::logData(JPATH_ROOT . '/components/com_edocman/itemidlog.txt', [], '#'.$menu_id .' - '.$id.'.');
		}
		
		
		if ($language && $language !== '*' && Multilanguage::isEnabled())
		{
			$needles['language']  = $language;
			$link                .= '&lang=' . $language;
		}
		elseif (Multilanguage::isEnabled())
		{
			$needles['language'] = Factory::getLanguage()->getTag();
		}
		if($find_menu_item === true)
		{
			if($menu_id > 0)
			{
				$link .= '&Itemid='.$menu_id;
			}
			elseif ($item = self::findItem($needles, $itemId))
			{
				//EdocmanHelper::logData(JPATH_ROOT . '/components/com_edocman/itemidlog.txt', [], '#'.$item .' - '.$id.'.');
				$link .= '&Itemid='.$item;
			}
		}
		return $link;
	}


    public static function getDocumentMenuId($id, &$catId = 0, $itemId = 0)
    {
        $needles = array (
            'document'  => array((int) $id)
        );
        if (!$catId)
        {
            //Find the first category which has lowest ordering of this event
            $db = Factory::getContainer()->get('db');
            $query = $db->getQuery(true);
            $query->select('category_id')
                ->from('#__edocman_document_category AS a')
                ->where('document_id='.(int)$id)
                ->where('is_main_category=1');
            $db->setQuery($query);
            $catId = (int)$db->loadResult();
        }
        if ($catId)
        {
            $needles['category'] = self::getCategoriesPath($catId, 'id', false);
            $needles['categories'] = $needles['category'];
        }

		if (Multilanguage::isEnabled())
		{
			$needles['language'] = Factory::getLanguage()->getTag();
		}

        if ($item = self::findItem($needles, $itemId))
        {
            return $item;
        }
        else
        {
            $itemId;
        }
    }
	
	/**
	 * 
	 * Function to get Category Route
	 * @param int $id
	 * @return string
	 */
	public static function getCategoryRoute($id, $itemId = 0)
	{	
		$db = Factory::getContainer()->get('db');
		if(!$id)
		{
			$link = '';
		}
		else
		{
			//Create the link
			$link = 'index.php?option=com_edocman&view=category&id='.$id;
			$catIds = self::getCategoriesPath($id, 'id', false);
			$needles = array (
					'category' => $catIds,
					'categories' => $catIds
			);

			if (Multilanguage::isEnabled())
			{
				$needles['language'] = Factory::getLanguage()->getTag();
			}

			if ($item = self::findItem($needles, $itemId))
			{
				$link .= '&Itemid='.$item;

				$db->setQuery("Update #__edocman_categories set menu_id = '$item' where id = '$id'");
				$db->execute();
			}
		}

		return $link;
	}

	/**
	 * 
	 * Function to get View Route
	 * @param string $view (cart, checkout)
	 * @return string
	 */
	public static function getViewRoute($view, $itemId)
	{
		//Create the link
		$link = 'index.php?option=com_edocman&view='.$view;
		if ($item = self::findView($view, $itemId))
        {
            $link .= '&Itemid='.$item;
        }

		return $link;
	}

    /**
     * Get event title, used for building the router
     *
     * @param $id
     * @return mixed
     */
    public static function getDocumentTitle($id)
    {
        if (self::$config == null)
        {
            self::$config = EDocmanHelper::getConfig();
        }
        if (!isset(self::$documents[$id]))
        {
            $db = Factory::getContainer()->get('db');
            $query = $db->getQuery(true);
            $query->select('alias')
                ->from('#__edocman_documents')
                ->where('id=' . $id);
            $db->setQuery($query);
            if (self::$config->insert_document_id)
            {
                self::$documents[$id] = $id.'-'.$db->loadResult();
            }
            else
            {
                self::$documents[$id] = $db->loadResult();
            }
        }

        return self::$documents[$id];
    }

    public static function getCategoriesPath($id, $type = 'id', $reverse = true, $parentId = 0)
    {
        static $categories;
        if (self::$config == null)
        {
            self::$config = EDocmanHelper::getConfig();
        }
        $db = Factory::getContainer()->get('db');
        if (empty($categories))
        {
            $query = $db->getQuery(true);
            $query->select('id, alias, parent_id')->from('#__edocman_categories');
            $db->setQuery($query);
            $categories = $db->loadObjectList('id');
        }
        $paths = [];
        if ($type == 'id' || self::$config->insert_category == 0)
        {
            do
            {
                if (!isset($categories[$id]))
                {
                    break;
                }
                if ($type == 'alias' &&  self::$config->insert_category_id)
                {
                    $paths[] = $categories[$id]->id.'-'.$categories[$id]->alias;
                }
                else
                {
                    $paths[] = $categories[$id]->{$type};
                }
                $id = $categories[$id]->parent_id;
            }
            while ($id != $parentId);
            if ($reverse)
            {
                $paths = array_reverse($paths);
            }
        }
        else
        {
            $paths[] = $categories[$id]->{$type};
        }
        return $paths;
    }

    /**
     * Find item id variable corresponding to the view
     *
     * @param $view
     * @return int
     */
    public static function findView($view, $itemId)
    {
        $needles = array (
            $view => array(0)
        );
		if (Multilanguage::isEnabled())
		{
			$needles['language'] = Factory::getLanguage()->getTag();
		}
        if ($item = self::findItem($needles, $itemId))
        {
            return $item;
        }
        else
        {
            return 0;
        }
    }

    /**
     * Find upload document menu id
     *
     * @param int $itemId
     *
     * @return int
     * @throws Exception
     */
    public static function findUploadMenuId($itemId = 0)
    {
        $app       = Factory::getApplication();
        //$menus     = $app->getMenu('site');
        //$component = ComponentHelper::getComponent('com_edocman');
        //$items     = $menus->getItems('component_id', $component->id);
		$items		 = self::getMenuItems();
        foreach ($items as $item)
        {
            if (isset($item->query) && isset($item->query['view']) && isset($item->query['layout']) && $item->query['view'] == 'document' && $item->query['layout'] == 'edit')
            {
                return $item->id;
            }
        }

        return $itemId;
    }
	/**
	 * 
	 * Function to find Itemid
	 * @param string $needles
	 * @return int
	 */
	public  static function findItem($needles = null, $itemId = 0)
	{

		$app		= Factory::getApplication();
		/*
		if ($app instanceof \Joomla\CMS\Application\CMSApplication)
		{
			$menus = $app->getMenu('site');
		}
		else
		{
			$menus = Factory::getContainer()->get(\Joomla\CMS\Menu\SiteMenu::class);
		}
		*/
		//$menus		= $app->getMenu('site');

		$language   = $needles['language'] ?? '*';

		// Prepare the reverse lookup array.
		if (!isset(self::$lookup[$language]))
		{
			self::$lookup[$language] = [];

			$items = self::getMenuItems($language);

			//EdocmanHelper::logData(JPATH_ROOT . '/components/com_edocman/itemidlog.txt', [], '#'. $itemId .' - '.$item->id.'.');

			foreach ($items as $item)
			{
				if (!empty($item->query['view']))
				{
					$view = $item->query['view'];

					if (!isset(self::$lookup[$language][$view]))
					{
						self::$lookup[$language][$view] = [];
					}

					if (isset($item->query['id']))
					{
						self::$lookup[$language][$view][$item->query['id']] = $item->id;
					}
					else
					{
						self::$lookup[$language][$view][0] = $item->id;
					}
				}
			}
		}

		foreach ($needles as $view => $ids)
		{
			if (isset(self::$lookup[$language][$view]))
			{
				foreach ($ids as $id)
				{
					$id = (int) $id;

					if (isset(self::$lookup[$language][$view][(int) $id]))
					{
						return self::$lookup[$language][$view][(int) $id];
					}
				}
			}
		}
        //Return default item id
		if($itemId == 0)
		{
			$itemId = self::getDefaultMenuItem($language);
		}

		
        return $itemId;
	}

	/**
	 * Get default menu item
	 *
	 * @param   string  $language
	 *
	 * @return int
	 */
	public static function getDefaultMenuItem($language = null)
	{

		if (Multilanguage::isEnabled())
		{
			$language = Factory::getLanguage()->getTag();
		}

		$items = self::getMenuItems($language);

		$defaultViews = ['categories'];

		foreach ($items as $item)
		{
			if (!empty($item->query['view']) && in_array($item->query['view'], $defaultViews))
			{
				return $item->id;
			}
		}


		return 0;
	}

	/**
	 * Get component menu items for given language
	 *
	 * @param   string  $language
	 *
	 * @return MenuItem[]
	 */
	protected static function getMenuItems($language = '*')
	{
		if (!isset(self::$items[$language]))
		{
			$component  = ComponentHelper::getComponent('com_edocman');
			$attributes = ['component_id'];
			$values     = [$component->id];

			if ($language != '*')
			{
				$attributes[] = 'language';
				$values[]     = [$language, '*'];
			}

			//self::$items[$language] = Factory::getApplication()->getMenu('site')->getItems($attributes, $values);
			if (PHP_SAPI !== 'cli')
            {
                // For web requests, use the existing method
                self::$items[$language] = Factory::getApplication()->getMenu('site')->getItems($attributes, $values);
            }
            else
            {
                // For CLI, return an empty array or null
                self::$items[$language] = [];
            } 
		}

		return self::$items[$language];
	}
}