<?php
/**
 * @package n3t Cookie Consent
 * @author Pavel Poles - n3t.cz
 * @copyright (C) 2021 - Pavel Poles - n3t.cz
 * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 **/

use Joomla\CMS\Form\FormField;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\Registry\Registry;
use Joomla\CMS\Version;

defined( '_JEXEC' ) or die( 'Restricted access' );

class JFormFieldN3tCookieConsentUsage extends FormField
{
	protected $type = 'N3tCookieConsentUsage';

	public function __construct($form = null)
	{
		parent::__construct($form);
		if (Version::MAJOR_VERSION >= 4)
			$this->hiddenLabel = true;
	}

	protected function getInput()
	{
		if (Version::MAJOR_VERSION >= 4) {
			return $this->getHtml();
		}

		return '';
	}

	 protected function getLabel()
	 {
			if (Version::MAJOR_VERSION < 4) {
				// Joomla 3 hack inspired by Note field
				return '</div><div>' . $this->getHtml();
			}

			return '';
	 }

	private function getHtml()
	{
		$html = '';
		if (!PluginHelper::isEnabled('system', 'n3tcookieconsent'))
			$html.= '<p class="alert alert-warning">' . Text::_('PLG_SYSTEM_N3TCOOKIECONSENT_CFG_USAGE_ENABLE_PLUGIN_FIRST') . '</p>';
		else {
			$plugin = PluginHelper::getPlugin('system', 'n3tcookieconsent');
			$params = new Registry($plugin->params);

			$hasDefinition = false;
			$blocks = (array)$params->get('blocks', []);
			foreach ($blocks as $block) {
				if (isset($block->cookies) && !empty($block->cookies)) {
					$hasDefinition = true;
					break;
				}
			}

			if (!$hasDefinition)
				$html.= '<p class="alert alert-warning">' . Text::_('PLG_SYSTEM_N3TCOOKIECONSENT_CFG_USAGE_SETUP_COOKIES_FIRST') . '</p>';
		}

		return $html;
	}
}
