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

defined('_JEXEC') or die;

use Joomla\Registry\Registry;

JFormHelper::loadFieldClass('list');

class JFormFieldVMStatuses extends JFormFieldList
{
	public $type = 'VMStatuses';
	
	protected static $statuses = null;
	
	protected function getInput()
	{
		if (!empty($this->value) && is_string($this->value) && $this->multiple)
		{
			$this->value = explode(',', $this->value);
		}

		return parent::getInput();
	}

	protected function getOptions()
	{
		JLoader::register('VmConfig', JPATH_ADMINISTRATOR . '/components/com_virtuemart/helpers/config.php');

		VmConfig::loadConfig();
		VmConfig::loadJLang('com_virtuemart');
		VmConfig::loadJLang('com_virtuemart_orders', true);

		$options = array();
		
		if (self::$statuses === null)
		{
			$db    = JFactory::getDBO();
			$query = $db->getQuery(true);

			$query->select($db->quoteName('os.order_status_code') . ' AS value')
				->select($db->quoteName('os.order_status_name') . ' AS text')
				->from($db->quoteName('#__virtuemart_orderstates') . ' AS os')
				->where($db->quoteName('os.published') . ' = 1')
				->order($db->quoteName('os.virtuemart_orderstate_id') . ' ASC');
			
			try
			{
				$db->setQuery($query);
				self::$statuses = $db->loadObjectList();
			}
			catch (Exception $e)
			{
				JError::raiseWarning(500, $e->getMessage());
				return false;
			}
		}
		
		foreach (self::$statuses as $status)
		{
			$options[] = JHtml::_('select.option', $status->value, JText::_($status->text));
		}
		
		return array_merge(parent::getOptions(), $options);
	}
}