<?php
/**
 * @version        1.11.2
 * @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\Toolbar\Toolbar;
use Joomla\CMS\Toolbar\ToolbarHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\Registry\Registry;
use Joomla\Filesystem\Folder;
use Joomla\Filesystem\Path;

class EDocmanViewDocumentsHtml extends OSViewList
{
	/**
	 * Prepare data for the view before displaying
	 */
	protected function prepareView()
	{
		parent::prepareView();
		require_once JPATH_ROOT . '/components/com_edocman/helper/file.class.php';
        $orphan_state = $this->input->getInt('filter_orphan_state',0);
        $this->state->filter_orphan_state = $orphan_state;
		$db = Factory::getContainer()->get('db');
		$query = $db->getQuery(true);
		$query->select('id, title, parent_id');
		$query->from('#__edocman_categories');
		$query->where('published=1');
		$db->setQuery($query);
		$rows     = $db->loadObjectList();
		$children = [];
		// first pass - collect children
		if (count($rows))
		{
			foreach ($rows as $v)
			{
				$pt   = $v->parent_id;
				$list = @$children[$pt] ? $children[$pt] : array();
				array_push($list, $v);
				$children[$pt] = $list;
			}
		}

		$list      = HTMLHelper::_('menu.treerecurse', 0, '', array(), $children, 9999);
		$options   = [];
		$options[] = HTMLHelper::_('select.option', 0, Text::_('EDOCMAN_SELECT_CATEGORY'));
		if (count($list))
		{
			foreach ($list as $row)
			{
				$row->treename = str_replace("&#160;", "", $row->treename);
				$options[] = HTMLHelper::_('select.option', $row->id, $row->treename);
			}
		}
		$this->lists['filter_category_id'] = HTMLHelper::_('select.genericlist', $options, 'filter_category_id',
			array(
				'option.text.toHtml' => false,
				'list.attr'          => 'class="form-select" onchange="submit();" style="width:250px;display:inline;" ',
				'option.text'        => 'text',
				'option.key'         => 'value',
				'list.select'        => (int) $this->state->filter_category_id));

        $this->lists['moving_category_id'] = HTMLHelper::_('select.genericlist', $options, 'moving_category_id',
            array(
                'option.text.toHtml' => false,
                'list.attr'          => 'class="form-select" ',
                'option.text'        => 'text',
                'option.key'         => 'value',
                'list.select'        => (int) $this->state->moving_category_id));

		$this->lists['moving_category_id1'] = HTMLHelper::_('select.genericlist', $options, 'moving_category_id1',
            array(
                'option.text.toHtml' => false,
                'list.attr'          => 'class="form-select" ',
                'option.text'        => 'text',
                'option.key'         => 'value',
                'list.select'        => (int) $this->state->moving_category_id1));

		// Upload New Document Form
		$layout = $this->getLayout();
		if ($layout == 'modal')
		{
			// Upload new document form options
			$this->lists['category_id'] = HTMLHelper::_('select.genericlist', $options, 'category_id',
				array(
					'option.text.toHtml' => false,
					'list.attr'          => 'class="form-select" required="required"',
					'option.text'        => 'text',
					'option.key'         => 'value',
					'list.select'        => $this->input->getInt('category_id', 0)));

			$documentLinkPlugin                    = PluginHelper::getPlugin('editors-xtd', 'edocman');
			$params                                = new Registry($documentLinkPlugin->params);
			$options                               = [];
			$options[]                             = HTMLHelper::_('select.option', 0, Text::_('EDOCMAN_CHOOSE_EXISTING_DOCUMENT'));
			$options[]                             = HTMLHelper::_('select.option', 1, Text::_('EDOCMAN_UPLOAD_NEW_DOCUMENT'));
			$this->lists['choose_document_option'] = HTMLHelper::_('select.radiolist', $options, 'choose_document_option', ' class="inputbox" onclick="changeOption(this.value)" ', 'value', 'text', $this->input->getInt('choose_document_option', $params->get('default_insert_option', 0)));

			$this->lists['published'] = HTMLHelper::_('select.booleanlist', 'published', ' class="inputbox input-small form-select" ', $this->input->getInt('published', 1));
			//Access
			$this->lists['access'] = HTMLHelper::_('access.level', 'access', $this->input->getInt('access', 1), 'class="form-select"', true);
		}

        $optionArr = [];
        $optionArr[] = HTMLHelper::_('select.option','',Text::_('EDOCMAN_SELECT_ORPHAN'));
        $optionArr[] = HTMLHelper::_('select.option','1', Text::_('EDOCMAN_SHOW_ONLY_ORPHAN_DOCUMENTS'));
        $this->lists['filter_orphan_state'] = HTMLHelper::_('select.genericlist',$optionArr,'filter_orphan_state','class="input-large form-select" onChange="javascript:document.adminForm.submit();"','value','text',$this->input->getInt('filter_orphan_state', ''));

		$optionArr = [];
        $optionArr[] = HTMLHelper::_('select.option','-1', Text::_('EDOCMAN_SHOW_MISSING_FILES'));
		$optionArr[] = HTMLHelper::_('select.option','0',Text::_('JNO'));
        $optionArr[] = HTMLHelper::_('select.option','1',Text::_('JYES'));
        $this->lists['filter_missing_files'] = HTMLHelper::_('select.genericlist',$optionArr,'filter_missing_files','class="input-large form-select ilarge" onChange="javascript:document.adminForm.submit();"','value','text',$this->input->getInt('filter_missing_files', ''));


		$optionArr = [];
        $optionArr[] = HTMLHelper::_('select.option','0',Text::_('EDOCMAN_CREATED_ON'));
        $optionArr[] = HTMLHelper::_('select.option','1','1 '.Text::_('EDOCMAN_DAYS_GO'));
		$optionArr[] = HTMLHelper::_('select.option','3','3 '.Text::_('EDOCMAN_DAYS_GO'));
		$optionArr[] = HTMLHelper::_('select.option','7','7 '.Text::_('EDOCMAN_DAYS_GO'));
		$optionArr[] = HTMLHelper::_('select.option','14','14 '.Text::_('EDOCMAN_DAYS_GO'));
		$optionArr[] = HTMLHelper::_('select.option','30','30 '.Text::_('EDOCMAN_DAYS_GO'));
		$optionArr[] = HTMLHelper::_('select.option','60','60 '.Text::_('EDOCMAN_DAYS_GO'));
        $this->lists['filter_created_on'] = HTMLHelper::_('select.genericlist',$optionArr,'filter_created_on','class="input-large form-select" onChange="javascript:document.adminForm.submit();"','value','text',$this->input->getInt('filter_created_on', ''));

		$this->config = EDocmanHelper::loadConfig();

		$query = $db->getQuery(true);
		$query->select('count(extension_id)');
		$query->from('#__extensions');
		$query->where('`element` like "indexer" and `folder` like "edocman" and enabled=1');
		$db->setQuery($query);
		$count = $db->loadResult();
		if($count > 0 && is_dir(Path::clean(JPATH_ROOT.'/plugins/edocman/indexer')))
		{
			$this->indexer = 1;
		}
		else
		{
			$this->indexer = 0;
		}

		$query->clear();
		$query->select('distinct a.id as value, a.name as text')->from('#__users as a')->join('inner','#__edocman_documents as b on a.id = b.created_user_id');
		$db->setQuery($query);
		$creator                = $db->loadObjectList();
		$optionArr              = [];
		$optionArr[]            = HTMLHelper::_('select.option','',Text::_('EDOCMAN_FILTER_USERS'));
		$optionArr              = array_merge($optionArr,$creator);
		$this->lists['creator'] = HTMLHelper::_('select.genericlist',$optionArr,'creator','class="input-large form-select" onChange="Joomla.submitform();" style="width:220px;display:inline;"','value','text', $this->input->getInt('creator',0));

		$this->bootstrapHelper	= new EDocmanHelperBootstrap(EDocmanHelperHtml::getAdminBootstrapHelper());

		$optionArr				= [];
		$optionArr[]			= HTMLHelper::_('select.option','',Text::_('EDOCMAN_SELECT_STATE'));
		$optionArr[]			= HTMLHelper::_('select.option','1',Text::_('JPUBLISHED'));
		$optionArr[]			= HTMLHelper::_('select.option','0',Text::_('JUNPUBLISHED'));
		$optionArr[]			= HTMLHelper::_('select.option','2',Text::_('JARCHIVED'));
		$this->lists['filter_state'] = HTMLHelper::_('select.genericlist', $optionArr, 'filter_state', 'class="form-select" onChange="Joomla.submitform();"','value','text', $this->state->filter_state);

		if($this->input->getInt('creator',0) > 0 || (int) $this->state->filter_category_id > 0 || $this->state->filter_state != "" || $this->state->filter_orphan_state > 0 || $this->state->filter_missing_files > 0 || $this->state->start_date != "" || $this->state->end_date != "" )
		{
			$this->showFilterForm = "js-stools-container-filters-visible";
		}
		else
		{
			$this->showFilterForm = "";
		}

		// We don't need toolbar in the modal window.
		if (version_compare(JVERSION, '3.0', 'ge')) {
			if ($this->getLayout() !== 'modal')
			{
				////EdocmanHelper::addSideBarmenus('documents');
				//$this->sidebar = JHtmlSidebar::render();
			}
		}
	}

    protected function addToolbar()
	{
        $layout = $this->getLayout();
		if($layout != "remove_orphan")
		{
			if(EdocmanHelper::isJoomla4())
			{
				$toolbar = Toolbar::getInstance('toolbar');
				$helperClass = $this->classPrefix . 'Helper';
				if (is_callable($helperClass . '::getActions'))
				{
					$canDo = call_user_func(array($helperClass, 'getActions'), $this->name, $this->state);
				}
				else
				{
					$canDo = call_user_func(array('OSHelper', 'getActions'), $this->option, $this->name, $this->state);
				}
				ToolbarHelper::title(Text::_(strtoupper($this->languagePrefix . '_MANAGE_' . $this->name)), 'link ' . $this->name);

				if (in_array($this->name, array('categories', 'documents')))
				{
					if ($canDo->get('core.create') || count(EDocmanHelper::getAuthorisedCategories('core.create')))
					{
						ToolbarHelper::addNew('add', 'JTOOLBAR_NEW');
					}
				}
				else
				{
					if ($canDo->get('core.create'))
					{
						ToolbarHelper::addNew('add', 'JTOOLBAR_NEW');
					}
				}

				$dropdown = $toolbar->dropdownButton('status-group')
					->text('JTOOLBAR_CHANGE_STATUS')
					->toggleSplit(false)
					->icon('icon-ellipsis-h')
					->buttonClass('btn btn-action')
					->listCheck(true);

				$childBar = $dropdown->getChildToolbar();

				if (($canDo->get('core.edit') || $canDo->get('core.edit.own')) && isset($this->items[0]))
				{
					$childBar->edit('edit', 'JTOOLBAR_EDIT')->listCheck(true);
				}

				if ($canDo->get('core.delete') && isset($this->items[0]))
				{
					$childBar->delete('delete')->message(Text::_($this->languagePrefix . '_DELETE_CONFIRM'))->listCheck(true);
				}

				if ($canDo->get('core.edit.state'))
				{
					if (isset($this->items[0]->published) || isset($this->items[0]->state))
					{
						$childBar->publish('publish')->listCheck(true);
						$childBar->unpublish('unpublish')->listCheck(true);
					}
					if (isset($this->items[0]->checked_out))
					{
						$childBar->checkin('checkin')->listCheck(true);
					}
				}

				$childBar->standardButton('document.move_category')
					->text('EDOCMAN_MOVE')
				    ->icon('icon-move')
					->task('document.move_category')
					->listCheck(true);
				$childBar->standardButton('document.duplicate')
					->text('EDOCMAN_COPY')
				    ->icon('icon-copy')
					->task('document.duplicate')
					->listCheck(true);
				$childBar->standardButton('document.move_subcategory')
					->text('EDOCMAN_MOVE_ADD_CAT')
				    ->icon('icon-move')
					->task('document.move_subcategory')
					->listCheck(true);
				$childBar->standardButton('document.excluding_indexing')
					->text('EDOCMAN_EXCLUDE_INDEXING')
				    ->icon('icon icon-remove')
					->task('document.excluding_indexing')
					->listCheck(true);
				if(!EDocmanHelper::isDropBoxTurnedOn() && !EDocmanHelper::isGdriveTurnedOn() && !EDocmanHelper::isAmazonS3TurnedOn())
                {
					$childBar->standardButton('document.massdownload')
						->text('EDOCMAN_MASS_DOWNLOAD')
						->icon('icon-download')
						->task('document.massdownload')
						->listCheck(true);
				}

				if ($canDo->get('core.admin'))
				{
					ToolbarHelper::preferences($this->option);
				}
			}
			else
			{	
				$helperClass = $this->classPrefix . 'Helper';
				if (is_callable($helperClass . '::getActions'))
				{
					$canDo = call_user_func(array($helperClass, 'getActions'), $this->name, $this->state);
				}
				else
				{
					$canDo = call_user_func(array('OSHelper', 'getActions'), $this->option, $this->name, $this->state);
				}
				ToolbarHelper::title(Text::_(strtoupper($this->languagePrefix . '_MANAGE_' . $this->name)), 'link ' . $this->name);

				if (in_array($this->name, array('categories', 'documents')))
				{
					if ($canDo->get('core.create') || count(EDocmanHelper::getAuthorisedCategories('core.create')))
					{
						ToolbarHelper::addNew('add', 'JTOOLBAR_NEW');
					}
				}
				else
				{
					if ($canDo->get('core.create'))
					{
						ToolbarHelper::addNew('add', 'JTOOLBAR_NEW');
					}
				}

				if (($canDo->get('core.edit') || $canDo->get('core.edit.own')) && isset($this->items[0]))
				{
					ToolbarHelper::editList('edit', 'JTOOLBAR_EDIT');
				}

				if ($canDo->get('core.delete') && isset($this->items[0]))
				{
					ToolbarHelper::deleteList(Text::_($this->languagePrefix . '_DELETE_CONFIRM'), 'delete');
				}

				if ($canDo->get('core.edit.state'))
				{
					if (isset($this->items[0]->published) || isset($this->items[0]->state))
					{
						ToolbarHelper::publish('publish', 'JTOOLBAR_PUBLISH', true);
						ToolbarHelper::unpublish('unpublish', 'JTOOLBAR_UNPUBLISH', true);
					}
					if (isset($this->items[0]->checked_out))
					{
						ToolbarHelper::checkin('checkin');
					}
				}
				if(!EDocmanHelper::isDropBoxTurnedOn() && !EDocmanHelper::isGdriveTurnedOn() && !EDocmanHelper::isAmazonS3TurnedOn())
                {
					ToolbarHelper::custom('document.massdownload','download.png','download.png',Text::_('EDOCMAN_MASS_DOWNLOAD'));
				}
				if ($canDo->get('core.admin'))
				{
					ToolbarHelper::preferences($this->option);
				}
			}
		}
    }
}
