<?php
  /**
   * @version     1.0.0
   * @package     Joomla 4
   * @subpackage  Formea
   * @author      Feseur Sdn Bhd
   * @copyright   Copyright (C) 2010-2023 Feseur Sdn Bhd. All rights reserved.
   * @license     GNU General Public License version 2 or later;
   */


  defined('_JEXEC') or die();
  require_once __DIR__ . '/src/Validator/load.php';

  // no direct access
  use Feseur\Library\FsrResponse;
  use Joomla\CMS\Language\Text;
  use Joomla\Component\Formea\Site\Libraries\FormeaValidation;
  use Egulias\EmailValidator\EmailValidator;
  use Egulias\EmailValidator\Validation\RFCValidation;

  class EmailValidation extends FormeaValidation
  {

    public function __construct($config)
    {
      parent::__construct($config);
    }

    public function validate()
    {
      $retObject       = new FsrResponse();
      $submitted_value = preg_replace('/\s+/', '', $this->submitted_value);
      $result          = (object) [
        'hasError' => false,
        'msg'      => ''
      ];
      if (!empty($submitted_value))
      {
        $msg = Text::_('COM_FORMEA_INVALID_INPUT');
        if (!empty($this->validation) && isset($this->validation['invalid_msg']))
        {
          if (isset($this->validation['invalid_msg'][$this->langTag]))
          {
            $msg = Text::_($this->validation['invalid_msg'][$this->langTag]);
          }
          else
          {
            $arr      = array_values($this->validation['invalid_msg']);
            $totalArr = count($arr);
            for ($i = 0; $i < $totalArr; $i++)
            {
              if (!empty($arr[$i]))
              {
                $msg = Text::_($arr[$i]);
                break;
              }
            }
          }
        }
        $validator    = new EmailValidator();
        $isValidEmail = $validator->isValid($submitted_value, new RFCValidation()); //true
        if (!$isValidEmail)
        {
          $result->hasError = true;
          $result->msg      = $msg;
        }

      }
      $retObject->setSuccess(true);
      $retObject->setResult($result);

      return $retObject;
    }

  }
