<?php

/**
 * @version         1.9.7
 * @package        Joomla
 * @subpackage     EDocman
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2011 - 2024 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();
use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Language\Text;
use Joomla\Registry\Registry;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Filesystem\File;
use Joomla\CMS\Router\Route;

class EDocmanViewCategoryHtml extends OSViewHtml
{

	function display($tpl = null)
	{
		$config         = EDocmanHelper::getConfig();
		$userId         = Factory::getApplication()->getIdentity()->id;
		$model          = $this->getModel();
		$state          = $model->getState();
		$menus          = Factory::getApplication()->getMenu();
        $menu           = $menus->getActive();
        $document       = Factory::getApplication()->getDocument();
		$content_plugin = $this->input->getInt('content_plugin');
		$option			= Factory::getApplication()->getInput()->getString('option','');
		if ($state->id && !EDocmanHelper::canAccessCategory($state->id))
		{
			if (!$userId)
			{
				// Give not logged in users to login
				$return = base64_encode(Uri::getInstance()->toString());
				Factory::getApplication()->redirect('index.php?option=com_users&view=login&return=' . $return);
			}
			else
			{
				Factory::getApplication()->enqueueMessage(Text::_('EDOCMAN_INVALID_CATEGORY'));
				Factory::getApplication()->redirect('index.php');

				return;
			}
		}
		$items          = $model->getData();
		$category		= new stdClass();
		if ($state->id > 0) 
		{
			$categoryId     = $state->id;
			$category       = EDocmanHelper::getCategory($categoryId);
		}
		if ($config->show_sort_options)
		{
			if ($state->id > 0) 
			{
				$sort_option    = $category->sort_option;
				$sort_direction = $category->sort_direction;
				if($sort_option != "")
				{
					$state->filter_order = $sort_option;
				}
				if($sort_direction != "")
				{
					$state->filter_order_Dir = strtoupper($sort_direction);
				}
			}

			$options               = [];
			$options[]             = HTMLHelper::_('select.option', '', Text::_('EDOCMAN_SORT_BY'));
			$options[]             = HTMLHelper::_('select.option', 'tbl.title', Text::_('EDOCMAN_TITLE'));
			$options[]             = HTMLHelper::_('select.option', 'tbl.created_time', Text::_('EDOCMAN_DATE'));
			$options[]             = HTMLHelper::_('select.option', 'tbl.ordering', Text::_('EDOCMAN_ORDERING'));
			$lists['filter_order'] = HTMLHelper::_('select.genericlist', $options, 'filter_order', ' class="input-medium form-select" onchange="submit();" ', 'value', 'text', $state->filter_order);

			$options                   = [];
			$options[]                 = HTMLHelper::_('select.option', 'ASC', Text::_('EDOCMAN_ASC'));
			$options[]                 = HTMLHelper::_('select.option', 'DESC', Text::_('EDOCMAN_DESC'));
			$lists['filter_order_Dir'] = HTMLHelper::_('select.genericlist', $options, 'filter_order_Dir', ' class="input-medium form-select" onchange="submit();" ', 'value', 'text', $state->filter_order_Dir);
			$this->lists               = $lists;			
		}

		if($state->id > 0)
		{
			//$category       = EDocmanHelper::getCategory($state->id);
			$setmetakeyword = 0;
			$setmetadescription = 0;
			$setrobots      = 0;
			$showPageTitle  = 0;

			if (is_object($menu) && $content_plugin == 0)
			{
				$menuquery = $menu->query;
				$option = $menuquery['option'];
				$category_id = $menuquery['id'];
				if($state->id == $category_id)
				{
					$params = new Registry() ;
					$params->loadString($menu->getParams()) ;
					if ($params->get('menu-meta_description'))
					{
						$document->setDescription($params->get('menu-meta_description'));
						$setmetadescription = 1;
					}

					if ($params->get('menu-meta_keywords'))
					{
						$document->setMetadata('keywords', $params->get('menu-meta_keywords'));
						$setmetakeyword     = 1;
					}

					if ($params->get('robots'))
					{
						$document->setMetadata('robots', $params->get('robots'));
						$setrobots          = 1;
					}

					$page_title = $params->get('page_title', '');
					if($page_title != "")
					{
						$document->setTitle($page_title);
						$showPageTitle      = 1;
					}

					$page_heading = $params->get('page_heading','');
					if($page_heading != "")
					{
						$category->title = $page_heading;
					}
				}
				else
				{
					if($option == "com_edocman")
					{
						$document->setTitle(EdocmanHelper::getSiteTitle().$category->title);
						$showPageTitle      = 1;
					}
				}
			}
			else
			{
				if($content_plugin == 0)
				{
					$document->setTitle(EdocmanHelper::getSiteTitle().$category->title);
					$showPageTitle      = 1;
				}
			}
			if ($category && $option != "com_content" && $content_plugin == 0)
			{
				$document        = Factory::getApplication()->getDocument();
				$metaKey         = $category->metakey;
				$metaDescription = $category->metadesc;
				if ($metaKey && $setmetakeyword == 0)
				{
					$document->setMetaData('keywords', $metaKey);
				}

				if ($metaDescription && $setmetadescription == 0)
				{
					$document->setMetaData('description', $metaDescription);
				}
				if($showPageTitle  == 0)
				{
					$document->setTitle(EdocmanHelper::getSiteTitle().$category->title);
				}

				if ($config->process_plugin)
				{
					$category->description = HTMLHelper::_('content.prepare', $category->description);
				}
			}
		}
		else
		{
			if (is_object($menu) && $content_plugin == 0)
			{
				$menuquery = $menu->query;
				$option = $menuquery['option'];
				
				$params = new Registry() ;
				$params->loadString($menu->getParams()) ;
				if ($params->get('menu-meta_description'))
				{
					$document->setDescription($params->get('menu-meta_description'));
					$setmetadescription = 1;
				}

				if ($params->get('menu-meta_keywords'))
				{
					$document->setMetadata('keywords', $params->get('menu-meta_keywords'));
					$setmetakeyword     = 1;
				}

				if ($params->get('robots'))
				{
					$document->setMetadata('robots', $params->get('robots'));
					$setrobots          = 1;
				}

				$page_title = $params->get('page_title', '');
				if($page_title != "")
				{
					$document->setTitle($page_title);
					$showPageTitle      = 1;
				}

				$page_heading = $params->get('page_heading','');
				if($page_heading != "")
				{
					$category->title = $page_heading;
				}
			}
		}
		
		if ($config->process_plugin && count($items))
		{
			foreach ($items as $item)
			{
				$item->short_description = HTMLHelper::_('content.prepare', $item->short_description);
			}
		}

		if ($config->show_view_button && count($items))
		{
			$extsForView = explode(',', $config->exts_for_view);
			for ($i = 0, $n = count($extsForView); $i < $n; $i++)
			{
				$extsForView[$i] = strtolower(trim($extsForView[$i]));
			}
			foreach ($items as $item)
			{
				$fileName = $item->filename;
				$fileExt  = strtolower(EdocmanHelper::getExt($fileName));
				if (in_array($fileExt, $extsForView) || ($item->view_url != ''))
				{
					$item->canView = 1;
				}
				else
				{
					$item->canView = 0;
				}
			}
		}

		if ($config->day_for_new > 0 && count($items))
		{
			EDocmanHelper::setNewIndicator($items, (int) $config->day_for_new);
		}

		if ($config->day_for_update > 0 && count($items))
		{
			EDocmanHelper::setUpdateIndicator($items, (int) $config->day_for_update);
		}

		if($state->id && $category->category_layout == "")
		{
			$category->category_layout = "default";
		}

		if ($state->id && $category->category_layout)
		{
			$needles = array(
				'category' => array((int) $state->id)
			);
			//if (!EDocmanHelperRoute::findItem($needles))
			//{
				$this->setLayout($category->category_layout);
			//}
		}
		if ($config->enable_rss)
		{
			$document = Factory::getApplication()->getDocument();
			$link     = '&format=feed&limitstart=';
			$attribs  = array('type' => 'application/rss+xml', 'title' => 'RSS 2.0');
			$document->addHeadLink(Route::_($link . '&type=rss'), 'alternate', 'rel', $attribs);
			$attribs = array('type' => 'application/atom+xml', 'title' => 'Atom 1.0');
			$document->addHeadLink(Route::_($link . '&type=atom'), 'alternate', 'rel', $attribs);
		}

		// Load children categories of the current category
		if ($state->id > 0)
		{
			JLoader::register('EDocmanModelCategories', JPATH_ROOT . '/components/com_edocman/model/categories.php');
			$this->categories = OSModel::getInstance('Categories', 'EDocmanModel', array('ignore_session' => true, 'ignore_request' => true))
				->limitstart(0)
				->limit(0)
				->filter_order($config->default_category_sort_option != "" ? $config->default_category_sort_option : 'tbl.ordering')
				->filter_order_Dir($config->default_categoty_sort_direction)
				->id($state->id)
				->getData();
		}
		else
		{
			$this->categories = [];
		}

		//Handle breadcrumbs
		$app      = Factory::getApplication();
		$menuItem = $app->getMenu()->getActive();
		if ($menuItem)
		{
			if (isset($menuItem->query['view']) && ($menuItem->query['view'] == 'categories' || $menuItem->query['view'] == 'category'))
			{
				if($menuItem->query['view'] == 'category' && $menuItem->query['option'] == 'com_content')
				{
					//do nothing
				}
				else
				{
					$parentId = (int) $menuItem->query['id'];
					if ($state->id)
					{
						$pathway = $app->getPathway();
						$paths   = EDocmanHelper::getCategoriesBreadcrumb($state->id, $parentId);
						for ($i = count($paths) - 1; $i >= 0; $i--)
						{
							$path    = $paths[$i];
							$pathUrl = EDocmanHelperRoute::getCategoryRoute($path->id, $this->Itemid);
							$pathway->addItem($path->title, $pathUrl);
						}
					}
				}
			}
		}
		$pagination = $model->getPagination();
		if ($state->filter_order && ($state->filter_order != $state->getDefault('filter_order')))
		{
			$pagination->setAdditionalUrlParam('filter_order', $state->filter_order);
		}
		if ($state->filter_order_Dir == 'DESC' && ($state->filter_order_Dir != $state->getDefault('filter_order_Dir')))
		{
			$pagination->setAdditionalUrlParam('filter_order_Dir', $state->filter_order_Dir);
		}

		$show_subcat = 1;
		if($this->input->get('content_plugin') == 1){
			$show_subcat = $this->input->get('show_subcat',1);
		}

		$this->combine_categories = $this->input->get('combine_categories',0);

		if ($state->id && $config->process_plugin )
		{
			$category->description = HTMLHelper::_('content.prepare', $category->description);
		}

		//load modal && jQuery color box
		EDocmanHelperHtml::initModal();

		$this->userId     = $userId;
		$this->items      = $items;
		$this->pagination = $pagination;
		$this->config     = $config;
		$this->category   = $category;
		$this->state      = $state;
		$this->show_subcat= $show_subcat;
		$this->categoryId = $state->id;
		$menus			  = Factory::getApplication()->getMenu();
		$this->menu		  = $menus->getActive();
		$this->params     = Factory::getApplication()->getParams();
		$this->bootstrapHelper = new EDocmanHelperBootstrap($config->twitter_bootstrap_version);
		parent::display($tpl);
	}
}
