<?php
/**
 * Form Field class for the Joomla HDP.
 * Supports a checkbox list custom field.
 *
 * @package     Joomla.HDP
 * @subpackage  Form
 */

use OSSolution\HelpdeskPro\Site\Helper\Html as HelpdeskProHelperHtml;

class HDPFormFieldCheckboxes extends HDPFormField
{

	/**
	 * The form field type.
	 *
	 * @var    string
	 *
	 */
	protected $type = 'Checkboxes';

	/**
	 * Options for checkbox lists
	 * @var array
	 */
	protected $options = [];

	/**
	 * Number options displayed perrow
	 * @var int
	 */
	protected $optionsPerRow = 1;

	/**
	 * Method to instantiate the form field object.
	 *
	 * @param JTable $row   the table object store form field definitions
	 * @param mixed  $value the initial value of the form field
	 *
	 */
	public function __construct($row, $value)
	{
		parent::__construct($row, $value);

		if ((int) $row->size)
		{
			$this->optionsPerRow = (int) $row->size;
		}

		if (is_array($row->values))
		{
			$this->options = $row->values;
		}
		elseif (strpos($row->values, "\r\n") !== false)
		{
			$this->options = explode("\r\n", $row->values);
		}
		else
		{
			$this->options = explode(",", $row->values);
		}

		$this->options = array_map('trim', $this->options);
	}

	/**
	 * Method to get the field input markup.
	 *
	 * @param HelpdeskProHelperBootstrap $bootstrapHelper
	 *
	 * @return  string  The field input markup.
	 *
	 */
	protected function getInput($bootstrapHelper = null)
	{
		if (is_array($this->value))
		{
			$selectedOptions = $this->value;
		}
		elseif (strpos($this->value, "\r\n"))
		{
			$selectedOptions = explode("\r\n", $this->value);
		}
		elseif (is_string($this->value) && is_array(json_decode($this->value)))
		{
			$selectedOptions = json_decode($this->value);
		}
		else
		{
			$selectedOptions = [$this->value];
		}

		$selectedOptions = array_map('trim', $selectedOptions);

		// Add uk-checkbox if UIKit3 is used
		if ($bootstrapHelper && $bootstrapHelper->getBootstrapVersion() === 'uikit3')
		{
			$this->addClass('uk-checkbox');
		}

		/* Add form-check-input for bootstrap 4*/
		if ($bootstrapHelper && $bootstrapHelper->getFrameworkClass('form-check-input'))
		{
			$this->addClass('form-check-input');
		}

		$data = [
			'name'            => $this->name,
			'options'         => $this->options,
			'selectedOptions' => $selectedOptions,
			'attributes'      => $this->buildAttributes(),
			'bootstrapHelper' => $bootstrapHelper,
			'row'             => $this->row,
		];

		return HelpdeskproHelperHtml::loadCommonLayout('fieldlayout/checkboxes.php', $data);
	}
}