<?php
/**
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @copyright   Copyright (C) 2016-2024 CMExension
 * @license     GNU General Public License version 2 or later
 */

defined('JPATH_BASE') or die();

require_once JPATH_ROOT . '/administrator/components/com_cmgiftcard/models/base_fields/radio.php';

use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Form\Field\RadioField;

/**
 * Form field for pre-defined amount selection.
 *
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @since       1.0.0
 */
class JFormFieldCMGCDefinedAmount extends CMGiftCardRadioField
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  1.0.0
	 */
	protected $type = 'CMGCDefinedAmount';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   1.0.0
	 */
	public function getOptions()
	{
		$options = array();
		$params = ComponentHelper::getParams('com_cmgiftcard');
		$cardType = Factory::getApplication()->input->get('type', 'electronic', 'word');

		if ($cardType == 'physical')
			$amountType = $params->get('physical_amount_type', 'custom');
		else
			$amountType = $params->get('electronic_amount_type', 'custom');

		if ($amountType == 'defined' || $amountType == 'defined_custom')
		{
			if ($cardType == 'physical')
			{
				$amountString = $params->get('physical_defined_amounts');
				$descriptionString = $params->get('physical_defined_amount_descriptions');
			}
			else
			{
				$amountString = $params->get('electronic_defined_amounts');
				$descriptionString = $params->get('electronic_defined_amount_descriptions');
			}

			$amounts = explode(';', $amountString);
			$descriptions = explode(';', $descriptionString);

			if (count($amounts))
			{
				for ($i = 0; $i < count($amounts); $i++)
				{
					$amount = $amounts[$i];
					$postfix = (isset($descriptions[$i]) && $descriptions[$i] != '') ? ' - ' . $descriptions[$i] : '';

					if (count($amounts) == 1)
						$this->value = $amount;

					$option = new StdClass;
					$option->value = $amount;
					$option->text = HTMLHelper::_('cmgiftcard.formatPrice', $amount, $params) . $postfix;
					$options[] = $option;
				}
			}

			if (count($amounts) == 1)
			{
				$this->value = $amounts[0];
			}
		}

		return $options;
	}
}
