<?php
/**
 * @version     1.3.3
 * @package     sellacious
 *
 * @copyright   Copyright (C) 2012-2017 Bhartiy Web Technologies. All rights reserved.
 * @license     SPL Sellacious Private License; see http://www.sellacious.com/spl.html
 * @author      Izhar Aazmi <info@bhartiy.com> - http://www.bhartiy.com
 */
// no direct access
defined('_JEXEC') or die;

/**
 * Form Field class for the Joomla Platform.
 * Field for assigning permissions to groups for a given asset
 *
 * @see    JAccess
 * @since  11.1
 */
class JFormFieldRules extends JFormField
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  11.1
	 */
	protected $type = 'Rules';

	/**
	 * The section.
	 *
	 * @var    string
	 * @since  3.2
	 */
	protected $section;

	/**
	 * The component.
	 *
	 * @var    string
	 * @since  3.2
	 */
	protected $component;

	/**
	 * The assetField.
	 *
	 * @var    string
	 * @since  3.2
	 */
	protected $assetField;

	/**
	 * Method to get certain otherwise inaccessible properties from the form field object.
	 *
	 * @param   string $name The property name for which to the the value.
	 *
	 * @return  mixed  The property value or null.
	 *
	 * @since   3.2
	 */
	public function __get($name)
	{
		switch ($name)
		{
			case 'section':
			case 'component':
			case 'assetField':
				return $this->$name;
		}

		return parent::__get($name);
	}

	/**
	 * Method to set certain otherwise inaccessible properties of the form field object.
	 *
	 * @param   string $name  The property name for which to the the value.
	 * @param   mixed  $value The value of the property.
	 *
	 * @return  void
	 *
	 * @since   3.2
	 */
	public function __set($name, $value)
	{
		switch ($name)
		{
			case 'section':
			case 'component':
			case 'assetField':
				$this->$name = (string) $value;
				break;

			default:
				parent::__set($name, $value);
		}
	}

	/**
	 * Method to attach a JForm object to the field.
	 *
	 * @param   SimpleXMLElement $element  The SimpleXMLElement object representing the <field /> tag for the form field object.
	 * @param   mixed            $value    The form field value to validate.
	 * @param   string           $group    The field name group control value. This acts as as an array container for the field.
	 *                                     For example if the field has name="foo" and the group value is set to "bar" then the
	 *                                     full field name would end up being "bar[foo]".
	 *
	 * @return  boolean  True on success.
	 *
	 * @see     JFormField::setup()
	 * @since   3.2
	 */
	public function setup(SimpleXMLElement $element, $value, $group = null)
	{
		$return = parent::setup($element, $value, $group);

		if ($return)
		{
			$this->section    = $this->element['section'] ? (string) $this->element['section'] : '';
			$this->component  = $this->element['component'] ? (string) $this->element['component'] : '';
			$this->assetField = $this->element['asset_field'] ? (string) $this->element['asset_field'] : 'asset_id';
		}

		return $return;
	}

	/**
	 * Method to get the field input markup for Access Control Lists.
	 * Optionally can be associated with a specific component and section.
	 *
	 * @return  string  The field input markup.
	 *
	 * @since   11.1
	 * @todo    :   Add access check, who can set which group
	 */
	protected function getInput()
	{
		JHtml::_('bootstrap.tooltip');

		// Get required parameters.
		$assetId = $this->getAssetId();
		$actions = $this->getActions();
		$groups  = $this->getUserGroups();

		// Get the rules for just this asset (non-recursive).
		$assetRules = JAccess::getAssetRules($assetId);

		$data = new stdClass;

		$data->id         = $this->id;
		$data->name       = $this->name;
		$data->component  = $this->component;
		$data->section    = $this->section;
		$data->assetId    = $assetId;
		$data->actions    = $actions;
		$data->groups     = $groups;
		$data->assetRules = $assetRules;

		$html = JLayoutHelper::render('joomla.formfield.rules.input', $data, '', array('debug' => 1));

		return $html;
	}

	/**
	 * Get a list of the user groups.
	 *
	 * @return  stdClass[]
	 *
	 * @since   11.1
	 */
	protected function getUserGroups()
	{
		$db    = JFactory::getDbo();
		$query = $db->getQuery(true);

		$query->select('a.id AS value, a.title AS text, COUNT(DISTINCT b.id) AS level, a.parent_id')
			->from($db->qn('#__usergroups', 'a'))
			->join('LEFT', $db->qn('#__usergroups', 'b') . ' ON a.lft > b.lft AND a.rgt < b.rgt')
			->group('a.id, a.title, a.lft, a.rgt, a.parent_id')
			->order('a.lft ASC');

		$db->setQuery($query);
		$options = $db->loadObjectList();

		return $options;
	}

	/**
	 * Get the asset id for the concern asset object for which permissions are to be set.
	 *
	 * @return  int
	 */
	protected function getAssetId()
	{
		if ($this->section == 'component')
		{
			// Need to find the asset id by the name of the component.
			$db    = JFactory::getDbo();
			$query = $db->getQuery(true);

			$query->select($db->qn('id'))
				->from($db->qn('#__assets'))
				->where($db->qn('name') . ' = ' . $db->q($this->component));

			$db->setQuery($query);
			$assetId = (int) $db->loadResult();
		}
		else
		{
			// Find the asset id of the content.
			// Note that for global configuration, com_config injects asset_id = 1 into the form.
			$assetId = (int) $this->form->getValue($this->assetField);
		}

		return $assetId;
	}

	/**
	 * Method to return a list of actions from the component's access.xml file for which permissions can be set.
	 *
	 * @return  stdClass[]  The list of actions available
	 */
	protected function getActions()
	{
		// Get the actions for the asset.
		$xpath   = "/access/section[@name='" . $this->section . "']/";
		$file    = JPATH_BASE . '/components/' . $this->component . '/access.xml';
		$actions = JAccess::getActionsFromFile($file, $xpath);

		// fixme: Ignoring the error JAccess may have returned.
		if (!is_array($actions))
		{
			$actions = array();
		}

		// Iterate over the children and add to the actions.
		foreach ($this->element->children() as $el)
		{
			/** @var SimpleXMLElement $el */
			if ($el->getName() == 'action')
			{
				$actions[] = (object) array(
					'name'        => (string) $el['name'],
					'title'       => (string) $el['title'],
					'description' => (string) $el['description']
				);
			}
		}

		return $actions;
	}
}
