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

use Joomla\Registry\Registry;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Form\FormRule;

/**
 * Form Rule class for gift card amount.
 *
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @since       1.0.0
 */
class JFormRuleCMGCAmount extends FormRule
{
	/**
	 * Test method.
	 *
	 * @param   SimpleXMLElement  $element  The SimpleXMLElement object representing the <field /> tag for the form field object.
	 * @param   mixed             $value    The form field value to validate.
	 * @param   string            $group    The field name group control value. This acts as as an array container for the field.
	 *                                      For example if the field has name="foo" and the group value is set to "bar" then the
	 *                                      full field name would end up being "bar[foo]".
	 * @param   Registry          $input    An optional Registry object with the entire data set to validate against the entire form.
	 * @param   Form              $form     The form object for which the field is being tested.
	 *
	 * @return  boolean  True if the value is valid, false otherwise.
	 *
	 * @since   3.5.0
	 */
	public function test(SimpleXMLElement $element, $value, $group = null, JRegistry $input = null, JForm $form = null)
	{
		$value = (float) $value;

		$params = ComponentHelper::getParams('com_cmgiftcard');
		$cardType = $input->get('card_type');

		if ($cardType != 'physical' && $cardType != 'electronic')
			$cardType = 'electronic';

		if ($cardType != 'physical' && $cardType != 'electronic')
			$cardType = 'electronic';

		if ($cardType == 'physical')
		{
			$minAmount = $params->get('physical_min_amount');
			$maxAmount = $params->get('physical_max_amount');
		}
		else
		{
			$minAmount = $params->get('electronic_min_amount');
			$maxAmount = $params->get('electronic_max_amount');
		}

		return ($value < $minAmount || $value > $maxAmount) ? false : true;
	}
}
