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

defined('_JEXEC') or die;
use Joomla\CMS\Form\FormHelper;
use Joomla\CMS\Form\FormField;
use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;


jimport('joomla.html.html');
jimport('joomla.form.formfield');
jimport('joomla.form.helper');

if (version_compare(JVERSION, '4.4.99', '>'))
{
	JLoader::registerAlias('JFormFieldList', '\\Joomla\\CMS\\Form\\Field\\ListField');
}
else
{
	FormHelper::loadFieldClass('list');
}


/**
 * Supports an HTML select list of categories
 *
 * @package     Joomla.Platform
 * @subpackage  Form
 * @since       11.1
 */
class JFormFieldEdocmanCategory extends FormField
{
	/**
	 * @var    string    The form field type.
	 * @since  11.1
	 */
	public $type = 'EdocmanCategory';

	/**
	 * Method to get the field options.
	 *
	 * @return  array    The field option objects.
	 */
	protected function getInput()
	{
		// Initialise variables.
		require_once JPATH_ROOT . '/components/com_edocman/helper/helper.php';
		$app    = Factory::getApplication();
		$db		= Factory::getContainer()->get('db');
		$user   = Factory::getApplication()->getIdentity();

		$userId = $user->id;
		$config = EDocmanHelper::loadConfig();
		$query  = $db->getQuery(true);
		$query->select('id, title, parent_id')
			->from('#__edocman_categories AS tbl')
			//->where('published = 1')
			->order('ordering');
		if (!$app->isClient('administrator'))
		{
			if (!$user->authorise('core.admin'))
			{
                $usergroup          = $user->groups;
                $usergroupArr       = [];
                $usergroupSql       = "";
                if(count($usergroup) > 0)
				{
                    foreach ($usergroup as $group)
					{
                        $usergroupArr[] = " (`groups`='$group' OR `groups` LIKE '$group,%' OR `groups` LIKE '%,$group,%' OR `groups` LIKE '%,$group') AND `data_type` = 0";
                    }
                    $usergroupSql = implode(" OR ",$usergroupArr);
                    $usergroupSql = " tbl.id in (Select item_id from #__edocman_levels where $usergroupSql) ";
                    $usergroupSql = " OR ((tbl.user_ids = '' or tbl.user_ids = 0) AND tbl.accesspicker = '1' AND $usergroupSql ) ";
                }

				//$query->where("(((tbl.user_ids = '' OR tbl.user_ids = 0) AND tbl.access IN (" . implode(',', $user->getAuthorisedViewLevels()) . ")) $usergroupSql OR tbl.user_ids='$userId' OR tbl.user_ids LIKE '$userId,%' OR tbl.user_ids LIKE '%,$userId,%' OR tbl.user_ids LIKE '%,$userId' OR (tbl.created_user_id=$userId AND tbl.created_user_id > 0))");

				if($config->user_group_ids)
				{
					$groupQuery = EdocmanHelper::buildUserGroupQuery('tbl.owner_group_ids');
					$query->where("(((tbl.user_ids = '' OR tbl.user_ids is NULL OR tbl.user_ids = 0) AND tbl.owner_group_ids = '' AND tbl.access IN (" . implode(',', $user->getAuthorisedViewLevels()) . ")) $usergroupSql ".$groupQuery." OR tbl.user_ids='$userId' OR tbl.user_ids LIKE '$userId,%' OR tbl.user_ids LIKE '%,$userId,%' OR tbl.user_ids LIKE '%,$userId' OR (tbl.created_user_id=$userId AND tbl.created_user_id > 0))");
				}
				else
				{
					$query->where("(((tbl.user_ids = '' OR tbl.user_ids is NULL OR tbl.user_ids = 0) AND tbl.access IN (" . implode(',', $user->getAuthorisedViewLevels()) . ")) $usergroupSql OR tbl.user_ids='$userId' OR tbl.user_ids LIKE '$userId,%' OR tbl.user_ids LIKE '%,$userId,%' OR tbl.user_ids LIKE '%,$userId' OR (tbl.created_user_id=$userId AND tbl.created_user_id > 0))");
				}

			}
			if ($config->get('activate_multilingual_feature') && $app->getLanguageFilter())
			{
				$query->where('tbl.language IN (' . $db->Quote(Factory::getApplication->getLanguage()->getTag()) . ',' . $db->Quote('*') . ', "")');
			}
		}
		$parentId = 0;
		$catId    = 0;
		if (!$app->isClient('administrator'))
		{
			$query->where('published = 1');

			$catId = $app->getInput()->getInt('catid', 0);
			if ($catId)
			{
				$query->where('id IN (' . implode(',', EdocmanHelper::getChildrenCategories($catId)) . ')');
				$sql = 'SELECT parent_id FROM #__edocman_categories WHERE id=' . $catId;
				$db->setQuery($sql);
				$parentId = (int) $db->loadResult();
			}

		}
		$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_push($list, $v);
				$children[$pt] = $list;
			}
		}
		$list      = HTMLHelper::_('menu.treerecurse', $parentId, '',[], $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);
			}
		}

		if ($action = (string) $this->element['action'])
		{
			// Get the current user object.
			$user = Factory::getApplication()->getIdentity();

			foreach ($options as $i => $option)
			{
				if ($i == 0)
				{
					continue;
				}
				// To take save or create in a category you need to have create rights for that category
				// unless the item is already in that category.
				// Unset the option if the user isn't authorised for it. In this field assets are always categories.
				if ($user->authorise('core.create', 'com_edocman.category.' . $option->value) != true)
				{
					unset($options[$i]);
				}
			}

		}
		if ($this->element['readonly'])
		{
			$disabled = ' disabled="true" ';
		}
		else
		{
			$disabled = '';
		}

		if ($this->element['multiple'] == 'true')
		{
			$multiple = ' multiple="multiple "';
		}
		else
		{
			$multiple = '';
		}

		if ($this->element['class'])
		{
			$class = 'class="'.$this->element['class'].'" ';
		}
		else
		{
			$class = 'class="input-large form-select ilarge" ';
		}


		if ($disabled)
		{
			return HTMLHelper::_('select.genericlist', $options, $this->name, array(
				'option.text.toHtml' => false,
				'list.attr'          => $class. $disabled . $multiple,
				'option.text'        => 'text',
				'option.key'         => 'value',
				'list.select'        => $this->value
			)) . '<input type="hidden" name="' . $this->name . '" value="' . $catId . '" />';
		}
		else
		{
			return HTMLHelper::_('select.genericlist', $options, $this->name, array(
				'option.text.toHtml' => false,
				'list.attr'          => $class . $multiple,
				'option.text'        => 'text',
				'option.key'         => 'value',
				'list.select'        => $this->value
			));
		}
	}
}
