<?php

/**
 * ------------------------------------------------------------------------
 * Plugin JA Content Type
 * ------------------------------------------------------------------------
 * Copyright (C) 2004-2018 J.O.O.M Solutions Co., Ltd. All Rights Reserved.
 * @license - GNU/GPL, http://www.gnu.org/licenses/gpl.html
 * Author: J.O.O.M Solutions Co., Ltd
 * Websites: http://www.joomlart.com - http://www.joomlancers.com
 * ------------------------------------------------------------------------
 */

defined('JPATH_BASE') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Form\FormField;
use Joomla\CMS\Form\FormHelper;
use Joomla\CMS\Layout\FileLayout;

/**
 * Supports a modal contact picker.
 *
 * @package     Joomla.Administrator
 * @subpackage  com_contact
 * @since       1.6
 */
class JFormFieldJaitems extends FormField
{
	/**
	 * The form field type.
	 *
	 * @var		string
	 * @since   1.6
	 */
	protected $type = 'Jaitems';

	/**
	 * Method to get the field input markup.
	 *
	 * @return  string  The field input markup.
	 */
	protected function getInput()
	{
		$doc = Factory::getDocument();

		$url = Uri::root(true) . '/plugins/system/jacontenttype/models/fields/asset/';
		if (version_compare(JVERSION, '4.0', 'ge')) {
			$doc->addScript($url . 'script_j4.js');
			$doc->addScript($url . 'jalist_j4.js');
			$doc->addScript($url . 'media_j4.js');
		} else {
			$doc->addScript($url . 'script.js');
			$doc->addScript($url . 'jalist.js');
		}
		$doc->addStyleSheet($url . 'style.css');
		$doc->addStyleSheet($url . 'jalist.css');


		$options = array(
			'field' => $this,
			'attributes' => $this->element,
			'items' => $this->getItems(),
			'form' => $this->form,
			'group' => $this->group,
			'fieldname' => $this->fieldname,
		);
		$layout = new FileLayout('joomlart.fields.items', JAPATH_CONTENT_TYPE . '/layouts');
		return $layout->render($options);
	}

	function getItems()
	{
		$items = array();
		foreach ($this->element->children() as $element) {
			// clone element to make it as field
			$fdata = preg_replace('/<(\/?)item(\s|>)/mi', '<\1field\2', $element->asXML());

			$felement = new SimpleXMLElement($fdata);
			$items[] = $felement;
		}

		return $items;
	}
}
