<?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\Application\ApplicationHelper;
use Joomla\CMS\Form\FormHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Version;
use Joomla\CMS\Factory;

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

FormHelper::loadFieldClass('subform');

class JFormFieldN3tCookieConsentBlocks extends JFormFieldSubform
{
	protected $type = 'N3tCookieConsentBlocks';

	protected function getInput()
	{
		$input = '';
		if (PluginHelper::isEnabled('system', 'n3tcookieconsent')) {
			Text::script('PLG_SYSTEM_N3TCOOKIECONSENT_CFG_SCAN_INSTRUCTIONS');
			Text::script('PLG_SYSTEM_N3TCOOKIECONSENT_CFG_SCAN_BTN');

			$script = "const n3tCookieConsentScan = function() {" .
				"  console.log('Starting scan');" .
				"  let iframe = document.createElement('iframe');" .
				"  let body = document.getElementsByTagName('body')[0];" .
				"  iframe.src = '" . Route::link('site', 'index.php?n3tcc_scan=' . ApplicationHelper::getHash('plg_system_n3tcookiesconsent')) . "';" .
				"  iframe.style = 'position: fixed; z-index: 10000; top: 0; left: 0; width: 100%; height: 100%; border: none;';" .
				"  body.style = 'overflow: hidden';" .
				"  body.appendChild(iframe);" .
				"  window.addEventListener('message', function (e) {" .
				"    if (e.data == 'n3t_cookie_consent_finish_scan') {" .
				"      window.location.reload();" .
				"    }" .
				"  });" .
				"}";
			if (Version::MAJOR_VERSION < 4)
				Factory::getDocument()->addScriptDeclaration($script);
			else {
				$wa = Factory::getApplication()->getDocument()->getWebAssetManager();
				$wa->addInlineScript($script);
			}
			$input.= '<div class="text-right text-end">' .
				'<a href="' . Route::_('index.php?option=com_ajax&group=system&format=raw&plugin=N3tCookieConsentDefaults') . '" class="btn btn-danger" ' .
					'onclick="return confirm(\'' . Text::_('PLG_SYSTEM_N3TCOOKIECONSENT_CFG_DEFAULTS_CONFIRM') . '\')">' .
				'<i class="icon-trash"></i> ' . Text::_('PLG_SYSTEM_N3TCOOKIECONSENT_CFG_DEFAULTS_BTN') .
				'</a> ';
			$input.=
				'<a href="#" class="btn btn-primary" target="_blank " ' .
					'onclick="if (confirm(Joomla.JText._(\'PLG_SYSTEM_N3TCOOKIECONSENT_CFG_SCAN_INSTRUCTIONS\'))) {n3tCookieConsentScan()} return false;">' .
				'<i class="icon-search"></i> ' . Text::_('PLG_SYSTEM_N3TCOOKIECONSENT_CFG_SCAN_BTN') .
				'</a>' .
				'</div>';
		} else
			$input.= '<p class="alert alert-warning">' . Text::_('PLG_SYSTEM_N3TCOOKIECONSENT_CFG_COOKIES_ENABLE_PLUGIN_FIRST') . '</p>';

		return $input . parent::getInput();
	}
}
