<?php

/**
 * @version        1.10.0
 * @package        Joomla
 * @subpackage     EDocman
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2011-2018 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */
defined('_JEXEC') or die();
use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Language\Text;
use Joomla\CMS\HTML\HTMLHelper;

class EDocmanViewTreelistHtml extends OSViewHtml
{

	function display()
	{
		$model  = $this->getModel();
		$state  = $model->getState();
		$config = EDocmanHelper::getConfig();
		$items  = $model->getData();
		$category_ids = $this->input->getString('category_ids','');
		$state->set('category_ids', $category_ids);
		if ($state->id && !EDocmanHelper::canAccessCategory($state->id))
		{
			$user = Factory::getApplication()->getIdentity();
			if (!$user->id)
			{
				// 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()->redirect('index.php', Text::_('EDOCMAN_INVALID_CATEGORY'));

				return;
			}
		}
		if ($state->id)
		{
			$document = Factory::getApplication()->getDocument();
			$category = EDocmanHelper::getCategory($state->id);
			if ($category->metakey)
			{
				$document->setMetaData('keywords', $category->metakey);
			}
			if ($category->metadesc)
			{
				$document->setMetaData('description', $category->metadesc);
			}
			if ($config->process_plugin)
			{
				$category->description = HTMLHelper::_('content.prepare', $category->description);
			}
			$this->category = $category;
			$document->setTitle($category->title . ' - ' . Factory::getConfig()->get('sitename'));
		}

		// Trigger content plugin in category description
		if ($config->process_plugin && count($items))
		{
			foreach ($items as $item)
			{
				$item->description = HTMLHelper::_('content.prepare', $item->description);
			}
		}

		if(count($items))
        {
            foreach($items as $item)
            {
                JLoader::register('EDocmanModelList', JPATH_ROOT . '/components/com_edocman/model/list.php');
                $documentsModel    = OSModel::getInstance('List','EDocmanModel');
                $documentsModel->set('id',$item->id);
                $documentsModel->set('limit',0);
                $documents         = $documentsModel->getData();
                $item->documents   = $documents;
            }
        }

		$this->bootstrapHelper = new EDocmanHelperBootstrap($config->twitter_bootstrap_version);
		$this->config     = $config;
		$this->items      = $items;
		$this->pagination = $model->getPagination();
		$this->categoryId = $state->id;
		$this->params	  = Factory::getApplication()->getParams();

		parent::display();
	}
}
