<?php

/**
 * OBG Customizations
 *
 * Copyright (c) 2021 vonRotenberg
 *
 * @license commercial
 */

namespace vonRotenberg\RealEstateListingBundle\EventListener;

use Contao\CoreBundle\ServiceAnnotation\Hook;
use Contao\Validator;
use Contao\Widget;

class AddCustomRegexpListener
{
  /**
   * @param string $strRegexp
   * @param        $varValue
   * @param Widget $objWidget
   *
   * @return bool
   * @Hook("addCustomRegexp")
   */
  public function onAddCustomRegexp(string $strRegexp, &$varValue, Widget $objWidget): bool
    {
      switch ($strRegexp)
        {
            case 'currency':
            case 'float':

                if ((substr_count($varValue, ',') == 1 && strpos($varValue, '.') === false)
                    || (substr_count($varValue, ',') == 1 && ($dotPos = strpos($varValue, '.')) !== false && $dotPos < strpos($varValue, ',')))
                {
                    $varValue = str_replace('.', '', $varValue);
                    $varValue = str_replace(',', '.', $varValue);
                }

                if (!Validator::isNumeric($varValue))
                {
                    if ($strRegexp == 'currency')
                    {
                        $objWidget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['currency'], $objWidget->label));
                    } else {
                        $objWidget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['digit'], $objWidget->label));
                    }

                    return true;
                }

                break;
        }

        return false;
    }
}
