<?php
/**
 * @package    VP Email Manager
 * @copyright  Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @author     Abhishek Das <info@virtueplanet.com>
 * @link       https://www.virtueplanet.com
 */

defined('_JEXEC') or die;

JFormHelper::loadFieldClass('text');

class JFormFieldVpemails extends JFormFieldText
{
	protected $type = 'vpemails';

	function getInput()
	{
		JHtml::_('jquery.framework');
		JHtml::_('script', 'system/html5fallback.js', ['relative' => true, 'version' => 'auto']);
		JHtml::_('script', 'com_vpem/angular.min.js', ['relative' => true, 'version' => 'v1.6.5']);
		JHtml::_('bootstrap.framework');
		JHtml::_('script', 'com_vpem/bootstrap-tagsinput.js', ['relative' => true, 'version' => '1.0']);
		JHtml::_('script', 'com_vpem/bootstrap-tagsinput-angular.js', ['relative' => true, 'version' => '1.0']);
		JHtml::_('stylesheet', 'com_vpem/bootstrap-tagsinput.css', ['relative' => true, 'version' => '1.0']);
		
		JFactory::getDocument()->addScriptDeclaration("
		jQuery(function($) {
			$('#{$this->id}').tagsinput({
					trimValue: true,
					allowDuplicates: false,
					tagClass: 'label'
			});
			$('#{$this->id}').on('beforeItemAdd', function(event) {
				var regex = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
				if (!regex.test(event.item)) {
					alert('Invalid entry. Please enter a valid email address.');
					event.cancel = true;
					return;
				}
			});
		});
		");
		
		$coreasdefault = (!empty($this->element['coreasdefault']) && ($this->element['coreasdefault'] == 'true' || $this->element['coreasdefault'] == '1'));

		if (empty($this->value) && $coreasdefault && !$this->form->getValue('id'))
		{
			$db    = JFactory::getDbo();
			$query = $db->getQuery(true);
			
			$query->select($db->quoteName('email'))
				->from($db->quoteName('#__users'))
				->where($db->quoteName('sendEmail') . ' = 1');

			$db->setQuery($query);
			$emails = $db->loadColumn();
			
			if (!empty($emails))
			{
				$this->value = implode(',', $emails);
			}
		}
		
		$html  = parent::getInput();
		$html .= '<div class="muted small">Eg: support@example.com, bill@mail.com etc.</div>';
		
		return $html;
	}
}