<?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;

use Joomla\Registry\Registry;

jimport('joomla.form.formfield');

JFormHelper::loadFieldClass('list');

class JFormFieldVpemtemplate extends JFormFieldList
{
	public $type = 'vpemtemplate';
	
	protected static $templates = null;
	
	protected function getOptions()
	{
		if (self::$templates === null)
		{
			$db    = JFactory::getDBO();
			$query = $db->getQuery(true);
			
			$query->select($db->quoteName(['id', 'name', 'type', 'state']))
				->from($db->quoteName('#__vpem_templates'))
				->where($db->quoteName('state') . ' IN(0, 1)')
				->order($db->quoteName('name') . ' ASC');
				
			try
			{
				$db->setQuery($query);
				self::$templates = $db->loadObjectList();
			}
			catch (Exception $e)
			{
				JError::raiseWarning(500, $e->getMessage());
				return false;
			}
		}
		
		$type    = $this->form->getField('type') && $this->form->getField('type')->value ? $this->form->getField('type')->value : '';

		if (is_array($type) && isset($type[0]))
		{
			$type = $type[0];
		}

		$options = [];
		
		foreach (self::$templates as $template)
		{
			if ($template->type == $type)
			{
				$options[] = JHtml::_('select.option', (int) $template->id, $template->name, 'value', 'text', empty($template->state));
			}
		}
		
		return array_merge(parent::getOptions(), $options);
	}
}