<?php
/**
 * @version        1.9.10
 * @package        Joomla
 * @subpackage     EDocman
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2011-2018 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */
// no direct access
defined('_JEXEC') or die;
use Joomla\CMS\Factory;

class EDocmanModelCategories extends OSModelList
{
	public function __construct($config = array())
	{
		parent::__construct($config);

		$this->state->insert('id', 'int', 0);

		//Set default value for states
		$listLength = EDocmanHelper::getConfigValue('number_categories');
		if (!$listLength)
		{
			$listLength = Factory::getConfig()->get('list_limit');
		}
		$default_category_sort_option = EdocmanHelper::getConfigValue('default_category_sort_option');
		$default_categoty_sort_direction = EdocmanHelper::getConfigValue('default_categoty_sort_direction');
		$this->state->setDefault('limit', $listLength);
		$this->state->setDefault('filter_order', $default_category_sort_option);
		$this->state->setDefault('filter_order_Dir', $default_categoty_sort_direction);
	}

	/**
	 * Method to get categories data
	 *
	 * @access public
	 * @return array
	 */
	public function getData()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->data))
		{
			$rows = parent::getData();
			for ($i = 0, $n = count($rows); $i < $n; $i++)
			{
				$row                  = $rows[$i];
				$row->total_documents = EDocmanHelper::countDocuments($row->id);
			}
			$this->data = $rows;
		}

		return $this->data;
	}

	/**
	 * Builds WHERE clauses for the query
	 *
	 * @param JDatabaseQuery $query
	 *
	 * @return $this
	 */
	protected function _buildQueryWhere(JDatabaseQuery $query)
	{
		$config             = EDocmanHelper::getConfig();
		$user               = Factory::getApplication()->getIdentity();
		$usergroup          = $user->groups;
        $usergroupArr       = array();
        $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 is NULL OR tbl.user_ids = 0) AND tbl.accesspicker = '1' AND $usergroupSql ) ";
        }
		$userId = $user->get('id');
		$query->where('tbl.published=1')
			->where('tbl.parent_id=' . $this->state->id);

		//update from version 1.9.10
		if (!$user->authorise('core.admin'))
		{
			//$query->where("(((tbl.user_ids = '' OR tbl.user_ids is NULL OR tbl.user_ids = 0) AND tbl.accesspicker = '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->activate_multilingual_feature && Factory::getApplication()->getLanguageFilter())
		{
			$db = $this->getDbo();
			$query->where('tbl.language IN (' . $db->Quote(Factory::getLanguage()->getTag()) . ',' . $db->Quote('*') . ', "")');
		}

		return $this;
	}

	/**
     * Builds a generic ORDER BY clause based on the model's state
     *
     * @param JDatabaseQuery $query
     *
     * @return $this
     */
    public function _buildQueryOrder(JDatabaseQuery $query)
    {
        $sort      			= $this->state->filter_order;
        $direction 			= strtoupper($this->state->filter_order_Dir);
		$allowed_direction 	= array('ASC','DESC');
		if(!in_array($direction, $allowed_direction))
		{
			$direction 		= "ASC";
		}
        if ($this->state->id) {
            $categoryId     = $this->state->id;
            $category       = EDocmanHelper::getCategory($categoryId);
            $sort_option    = $category->sort_option;
            $sort_direction = $category->sort_direction;
            if($sort_option != "")
            {
                $sort       = $sort_option;
            }
            if($sort_direction != "")
            {
                $direction  = strtoupper($sort_direction);
            }
        }
        if ($sort)
        {
            $query->order($sort . ' ' . $direction);
        }

        return $this;
    }
}
