<?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
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Toolbar\ToolbarHelper;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Updater\Updater;
use Joomla\Component\Installer\Administrator\Model\UpdateModel;
use Joomla\CMS\MVC\Model\BaseDatabaseModel;


class EDocmanViewDashboardHtml extends OSViewHtml
{

	public $hasModel = false;
	/**
	 * Display.
	 */
	public function display()
	{
		$app		= Factory::getApplication();
		$input		= $app->getInput();
		HTMLHelper::_('jquery.framework');
		$model = OSModel::getInstance('Documents', 'EDocmanModel', array('ignore_request' => TRUE));
		$latestDocuments = $model->filter_state('P')
			->filter_order('created_time')
			->filter_order_Dir('DESC')
			->limit(5)
			->getData();
		
		$latestUpdatedDocuments = $model->reset()
			->filter_order('modified_time')
			->filter_order_Dir('DESC')
			->limit(5)
			->getData();
		
		$topHitDocuments = $model->reset()
			->filter_order('hits')
			->filter_order_Dir('DESC')
			->limit(5)
			->getData();
		
		$topDownloadDocuments = $model->reset()
			->filter_order('downloads')
			->filter_order_Dir('DESC')
			->limit(5)
			->getData();

        $noactiviesDocuments = $model->reset()
            ->filter_no_activies('1')
            ->limit(5)
            ->getData();

		$rangeOption				= [];
		
		$rangeOption[]				= HTMLHelper::_('select.option','5',Text::_('EDOCMAN_THIS_MONTH'));
		$rangeOption[]				= HTMLHelper::_('select.option','4',Text::_('EDOCMAN_LAST_MONTH'));
		$rangeOption[]				= HTMLHelper::_('select.option','3',Text::_('EDOCMAN_LAST_3_MONTHS'));
		$rangeOption[]				= HTMLHelper::_('select.option','2',Text::_('EDOCMAN_LAST_6_MONTHS'));
		$rangeOption[]				= HTMLHelper::_('select.option','1',Text::_('EDOCMAN_LAST_9_MONTHS'));
		$rangeOption[]				= HTMLHelper::_('select.option','0',Text::_('EDOCMAN_LAST_12_MONTHS'));
		$rangeOption[]				= HTMLHelper::_('select.option','6',Text::_('EDOCMAN_LAST_5_YEARS'));
		$lists['initial_range']     = HTMLHelper::_('select.genericlist',$rangeOption,'range_option','onChange="javascript:showGraph(this.value)" class="input-medium form-select imedium"','value','text', $input->getInt('range_option', 0));

		$this->user                     = Factory::getApplication()->getIdentity();
		$this->latestDocuments          = $latestDocuments;
		$this->latestUpdatedDocuments   = $latestUpdatedDocuments;
		$this->topHitDocuments          = $topHitDocuments;
		$this->topDownloadDocuments     = $topDownloadDocuments;
		$this->config                   = EDocmanHelper::loadConfig();
		$this->bootstrapHelper			= new EDocmanHelperBootstrap(EDocmanHelperHtml::getAdminBootstrapHelper());
		$this->lists					= $lists;
		$this->addToolbar();
		EDocmanHelperHtml::renderSubmenu('dashboard');

		$this->updateResult = $this->checkUpdate();

		if ($this->updateResult['status'] == 2 && $this->config->show_update_available_message_in_dashboard == 1)
		{
			Factory::getApplication()->enqueueMessage(
				Text::sprintf('EDOCMAN_UPDATE_AVAILABLE', 'index.php?option=com_installer&view=update', $this->updateResult['version'])
			);
		}


		parent::display();
	}

	/**
	 * Add toolbar to the view
	 */
	protected function addToolbar()
	{
		ToolbarHelper::title('EDOCMAN - '.Text::_('EDOCMAN_DASHBOARD'), 'dashboard.png');
		$canDo = EdocmanHelper::getActions();
		if ($canDo->get('core.admin'))
		{
			ToolbarHelper::preferences('com_edocman');
		}
	}

	/**
	 * Creates the buttons view.
	 * 
	 * @param string $link
	 *        	targeturl
	 * @param string $image
	 *        	path to image
	 * @param string $text
	 *        	image description
	 */
	protected function quickiconButton($link, $image, $text, $id = null, $extra_class = '', $color = '')
	{
		// initialise variables
		$lang = Factory::getLanguage();
        if($text == Text::_('EDOCMAN_HELP')){
            $target = "target='_blank'";
        }else{
            $target = "";
        }
		$extraStyle = '';
		if($color != "")
		{
			$extraStyle = "style='color:".$color.";'";
		}
	?>
		<a href="<?php echo $link; ?>" class="dashboard-item <?php echo $extra_class; ?>">
			<div class="icon"><i class="<?php echo $image; ?>" <?php echo $extraStyle; ?>></i></div>
			<div class="title"><?php echo $text; ?></div>
		</a>
	<?php
	}


	/**
	 * Check to see the installed version is up to date or not
	 *
	 * @return int 0 : error, 1 : Up to date, 2 : outof date
	 */
	public function checkUpdate()
	{
		// Get the caching duration.
		$params        = ComponentHelper::getComponent('com_installer')->getParams();
		$cache_timeout = (int) $params->get('cachetimeout', 6);
		$cache_timeout = 3600 * $cache_timeout;

		// Get the minimum stability.
		$minimum_stability = (int) $params->get('minimum_stability', Updater::STABILITY_STABLE);

		if (EDocmanHelper::isJoomla4())
		{
			/* @var UpdateModel $model */
			$model = Factory::getApplication()->bootComponent('com_installer')->getMVCFactory()
				->createModel('Update', 'Administrator', ['ignore_request' => true]);
		}
		else
		{
			BaseDatabaseModel::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_installer/models');

			/** @var InstallerModelUpdate $model */
			$model = BaseDatabaseModel::getInstance('Update', 'InstallerModel');
		}

		$model->purge();

		$db = Factory::getContainer()->get('db');
		$query = $db->getQuery(true)
			->select('extension_id')
			->from('#__extensions')
			->where('`type` = "package"')
			->where('`element` = "pkg_edocman"');
		$db->setQuery($query);
		$eid = (int) $db->loadResult();

		$result['status']  = 0;
		$result['version'] = '';

		if ($eid)
		{
			$ret = Updater::getInstance()->findUpdates($eid, $cache_timeout, $minimum_stability);

			if ($ret)
			{
				$model->setState('list.start', 0);
				$model->setState('list.limit', 0);
				$model->setState('filter.extension_id', $eid);
				$updates          = $model->getItems();
				$result['status'] = 2;

				if (count($updates))
				{
					$result['message'] = Text::sprintf('EDOCMAN_UPDATE_CHECKING_UPDATEFOUND', $updates[0]->version);
					$result['version'] = $updates[0]->version;
				}
				else
				{
					$result['message'] = Text::sprintf('EDOCMAN_UPDATE_CHECKING_UPDATEFOUND', null);
				}
			}
			else
			{
				$result['status']  = 1;
				$result['message'] = Text::_('EDOCMAN_UPDATE_CHECKING_UPTODATE');
			}
		}

		return $result;
	}
}
